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 get_autologging_config(flavor_name, config_key, default_value=None):
"""
Returns a desired config value for a specified autologging integration.
Returns `None` if specified `flavor_name` has no recorded configs.
If `config_key` is not set on the config object, default value is returned.
Args:
... |
Returns a desired config value for a specified autologging integration.
Returns `None` if specified `flavor_name` has no recorded configs.
If `config_key` is not set on the config object, default value is returned.
Args:
flavor_name: An autologging integration flavor name.
config_key:... | get_autologging_config | 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_is_disabled(integration_name):
"""Returns a boolean flag of whether the autologging integration is disabled.
Args:
integration_name: An autologging integration flavor name.
"""
explicit_disabled = get_autologging_config(integration_name, "disable", True)
if explicit_disable... | Returns a boolean flag of whether the autologging integration is disabled.
Args:
integration_name: An autologging integration flavor name.
| autologging_is_disabled | 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 is_autolog_supported(integration_name: str) -> bool:
"""
Whether the specified autologging integration is supported by the current environment.
Args:
integration_name: An autologging integration flavor name.
"""
# NB: We don't check for the presence of autolog() function as it requires ... |
Whether the specified autologging integration is supported by the current environment.
Args:
integration_name: An autologging integration flavor name.
| is_autolog_supported | 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_autolog_function(integration_name: str) -> Optional[Callable[..., Any]]:
"""
Get the autolog() function for the specified integration.
Returns None if the flavor does not have an autolog() function.
"""
flavor_module = importlib.import_module(f"mlflow.{integration_name}")
return getattr(... |
Get the autolog() function for the specified integration.
Returns None if the flavor does not have an autolog() function.
| get_autolog_function | 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 disable_autologging():
"""
Context manager that temporarily disables autologging globally for all integrations upon
entry and restores the previous autologging configuration upon exit.
"""
global _AUTOLOGGING_GLOBALLY_DISABLED
_AUTOLOGGING_GLOBALLY_DISABLED = True
try:
yield
... |
Context manager that temporarily disables autologging globally for all integrations upon
entry and restores the previous autologging configuration upon exit.
| disable_autologging | 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 disable_discrete_autologging(flavors_to_disable: list[str]) -> None:
"""
Context manager for disabling specific autologging integrations temporarily while another
flavor's autologging is activated. This context wrapper is useful in the event that, for
example, a particular library calls upon another... |
Context manager for disabling specific autologging integrations temporarily while another
flavor's autologging is activated. This context wrapper is useful in the event that, for
example, a particular library calls upon another library within a training API that has a
current MLflow autologging integra... | disable_discrete_autologging | 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_new_training_session_class():
"""
Returns a session manager class for nested autologging runs.
Examples
--------
>>> class Parent:
... pass
>>> class Child:
... pass
>>> class Grandchild:
... pass
>>>
>>> _TrainingSession = _get_new_training_session_... |
Returns a session manager class for nested autologging runs.
Examples
--------
>>> class Parent:
... pass
>>> class Child:
... pass
>>> class Grandchild:
... pass
>>>
>>> _TrainingSession = _get_new_training_session_class()
>>> with _TrainingSession(Parent, ... | _get_new_training_session_class | 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 __init__(self, estimator, allow_children=True):
"""A session manager for nested autologging runs.
Args:
estimator: An estimator that this session originates from.
allow_children: If True, allows autologging in child sessions.
If False, dis... | A session manager for nested autologging runs.
Args:
estimator: An estimator that this session originates from.
allow_children: If True, allows autologging in child sessions.
If False, disallows autologging in all descendant sessions.
| __init__ | 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 should_log(self):
"""
Returns True when at least one of the following conditions satisfies:
1. This session is the root session.
2. The parent session allows autologging and its estimator differs from this session's
estimator.
"""
... |
Returns True when at least one of the following conditions satisfies:
1. This session is the root session.
2. The parent session allows autologging and its estimator differs from this session's
estimator.
| should_log | 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_instance_method_first_arg_value(method, call_pos_args, call_kwargs):
"""Get instance method first argument value (exclude the `self` argument).
Args:
method: A `cls.method` object which includes the `self` argument.
call_pos_args: positional arguments excluding the first `self` argument... | Get instance method first argument value (exclude the `self` argument).
Args:
method: A `cls.method` object which includes the `self` argument.
call_pos_args: positional arguments excluding the first `self` argument.
call_kwargs: keywords arguments.
| get_instance_method_first_arg_value | 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_method_call_arg_value(arg_index, arg_name, default_value, call_pos_args, call_kwargs):
"""Get argument value for a method call.
Args:
arg_index: The argument index in the function signature. Start from 0.
arg_name: The argument name in the function signature.
default_value: Defa... | Get argument value for a method call.
Args:
arg_index: The argument index in the function signature. Start from 0.
arg_name: The argument name in the function signature.
default_value: Default argument value.
call_pos_args: The positional argument values in the method call.
... | get_method_call_arg_value | 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 after_iteration(self, model, epoch, evals_log):
"""
Run after each iteration. Return True when training should stop.
"""
# `evals_log` is a nested dict (type: Dict[str, Dict[str, List[float]]])
# that looks like this:
# {
# "train... |
Run after each iteration. Return True when training should stop.
| after_iteration | python | mlflow/mlflow | mlflow/xgboost/_autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/xgboost/_autolog.py | Apache-2.0 |
def save_model(
xgb_model,
path,
conda_env=None,
code_paths=None,
mlflow_model=None,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
pip_requirements=None,
extra_pip_requirements=None,
model_format="xgb",
metadata=None,
):
"""Save an XGBoost mod... | Save an XGBoost model to a path on the local file system.
Args:
xgb_model: XGBoost model (an instance of `xgboost.Booster`_ or models that implement the
`scikit-learn API`_) to be saved.
path: Local path where the model is to be saved.
conda_env: {{ conda_env }}
code_pat... | save_model | python | mlflow/mlflow | mlflow/xgboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/xgboost/__init__.py | Apache-2.0 |
def log_model(
xgb_model,
artifact_path: Optional[str] = None,
conda_env=None,
code_paths=None,
registered_model_name=None,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
pip_requirements=None,
ex... | Log an XGBoost model as an MLflow artifact for the current run.
Args:
xgb_model: XGBoost model (an instance of `xgboost.Booster`_ or models that implement the
`scikit-learn API`_) to be saved.
artifact_path: Deprecated. Use `name` instead.
conda_env: {{ conda_env }}
code... | log_model | python | mlflow/mlflow | mlflow/xgboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/xgboost/__init__.py | Apache-2.0 |
def _load_model(path):
"""Load Model Implementation.
Args:
path: Local filesystem path to the MLflow Model with the ``xgboost`` flavor
(MLflow < 1.22.0) or the top-level MLflow Model directory (MLflow >= 1.22.0).
"""
model_dir = os.path.dirname(path) if os.path.isfile(path) else path
... | Load Model Implementation.
Args:
path: Local filesystem path to the MLflow Model with the ``xgboost`` flavor
(MLflow < 1.22.0) or the top-level MLflow Model directory (MLflow >= 1.22.0).
| _load_model | python | mlflow/mlflow | mlflow/xgboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/xgboost/__init__.py | Apache-2.0 |
def load_model(model_uri, dst_path=None):
"""Load an XGBoost model from a local file or a run.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/p... | Load an XGBoost model from a local file or a run.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_... | load_model | python | mlflow/mlflow | mlflow/xgboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/xgboost/__init__.py | Apache-2.0 |
def _wrapped_xgboost_model_predict_fn(model, validate_features=True):
"""
Wraps the predict method of the raw model to accept a DataFrame as input.
"""
import xgboost as xgb
if isinstance(model, xgb.Booster):
# we need to wrap the predict function to accept data in pandas format
def... |
Wraps the predict method of the raw model to accept a DataFrame as input.
| _wrapped_xgboost_model_predict_fn | python | mlflow/mlflow | mlflow/xgboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/xgboost/__init__.py | Apache-2.0 |
def remote_backend_for_tracing_sdk_test():
"""
A fixture to start a remote backend for testing mlflow-tracing package integration.
Since the tracing SDK has to be tested in an environment that has minimal dependencies,
we need to start a tracking backend in an isolated uv environment.
"""
port =... |
A fixture to start a remote backend for testing mlflow-tracing package integration.
Since the tracing SDK has to be tested in an environment that has minimal dependencies,
we need to start a tracking backend in an isolated uv environment.
| remote_backend_for_tracing_sdk_test | python | mlflow/mlflow | tests/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/conftest.py | Apache-2.0 |
def reset_tracing():
"""
Reset the global state of the tracing feature.
This fixture is auto-applied for cleaning up the global state between tests
to avoid side effects.
"""
yield
# Reset OpenTelemetry and MLflow tracer setup
mlflow.tracing.reset()
# Clear other global state and ... |
Reset the global state of the tracing feature.
This fixture is auto-applied for cleaning up the global state between tests
to avoid side effects.
| reset_tracing | python | mlflow/mlflow | tests/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/conftest.py | Apache-2.0 |
def validate_trace_finish():
"""
Validate all spans are finished and detached from the context by the end of the each test.
Leaked span is critical problem and also hard to find without an explicit check.
"""
# When the span is leaked, it causes confusing test failure in the subsequent tests. To av... |
Validate all spans are finished and detached from the context by the end of the each test.
Leaked span is critical problem and also hard to find without an explicit check.
| validate_trace_finish | python | mlflow/mlflow | tests/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/conftest.py | Apache-2.0 |
def clean_up_leaked_runs():
"""
Certain test cases validate safety API behavior when runs are leaked. Leaked runs that
are not cleaned up between test cases may result in cascading failures that are hard to
debug. Accordingly, this fixture attempts to end any active runs it encounters and
throws an ... |
Certain test cases validate safety API behavior when runs are leaked. Leaked runs that
are not cleaned up between test cases may result in cascading failures that are hard to
debug. Accordingly, this fixture attempts to end any active runs it encounters and
throws an exception (which reported as an add... | clean_up_leaked_runs | python | mlflow/mlflow | tests/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/conftest.py | Apache-2.0 |
def prevent_infer_pip_requirements_fallback(request):
"""
Prevents `mlflow.models.infer_pip_requirements` from falling back in `mlflow.*.save_model`
unless explicitly disabled via `pytest.mark.allow_infer_pip_requirements_fallback`.
"""
from mlflow.utils.environment import _INFER_PIP_REQUIREMENTS_GE... |
Prevents `mlflow.models.infer_pip_requirements` from falling back in `mlflow.*.save_model`
unless explicitly disabled via `pytest.mark.allow_infer_pip_requirements_fallback`.
| prevent_infer_pip_requirements_fallback | python | mlflow/mlflow | tests/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/conftest.py | Apache-2.0 |
def clean_up_mlruns_directory(request):
"""
Clean up an `mlruns` directory on each test module teardown on CI to save the disk space.
"""
yield
# Only run this fixture on CI.
if "GITHUB_ACTIONS" not in os.environ:
return
mlruns_dir = os.path.join(request.config.rootpath, "mlruns")
... |
Clean up an `mlruns` directory on each test module teardown on CI to save the disk space.
| clean_up_mlruns_directory | python | mlflow/mlflow | tests/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/conftest.py | Apache-2.0 |
def mock_s3_bucket():
"""
Creates a mock S3 bucket using moto
Returns:
The name of the mock bucket.
"""
import boto3
import moto
with moto.mock_s3():
bucket_name = "mock-bucket"
s3_client = boto3.client("s3")
s3_client.create_bucket(Bucket=bucket_name)
... |
Creates a mock S3 bucket using moto
Returns:
The name of the mock bucket.
| mock_s3_bucket | python | mlflow/mlflow | tests/conftest.py | https://github.com/mlflow/mlflow/blob/master/tests/conftest.py | Apache-2.0 |
def get_safe_port():
"""Returns an ephemeral port that is very likely to be free to bind to."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((LOCALHOST, 0))
port = sock.getsockname()[1]
sock.close()
return port | Returns an ephemeral port that is very likely to be free to bind to. | get_safe_port | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def score_model_in_sagemaker_docker_container(
model_uri,
data,
content_type,
flavor="python_function",
activity_polling_timeout_seconds=500,
):
"""
Args:
model_uri: URI to the model to be served.
data: The data to send to the docker container for testing. This is either a
... |
Args:
model_uri: URI to the model to be served.
data: The data to send to the docker container for testing. This is either a
Pandas dataframe or string of the format specified by `content_type`.
content_type: The type of the data to send to the docker container for testing. This... | score_model_in_sagemaker_docker_container | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def pyfunc_generate_dockerfile(output_directory, model_uri=None, extra_args=None, env=None):
"""
Builds a dockerfile for the specified model.
Args:
output_directory: Output directory to generate Dockerfile and model artifacts
model_uri: URI of model, e.g. runs:/some-run-id/run-relative/path... |
Builds a dockerfile for the specified model.
Args:
output_directory: Output directory to generate Dockerfile and model artifacts
model_uri: URI of model, e.g. runs:/some-run-id/run-relative/path/to/model
extra_args: List of extra args to pass to `mlflow models build-docker` command
... | pyfunc_generate_dockerfile | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def pyfunc_build_image(model_uri=None, extra_args=None, env=None):
"""
Builds a docker image containing the specified model, returning the name of the image.
Args:
model_uri: URI of model, e.g. runs:/some-run-id/run-relative/path/to/model
extra_args: List of extra args to pass to `mlflow mo... |
Builds a docker image containing the specified model, returning the name of the image.
Args:
model_uri: URI of model, e.g. runs:/some-run-id/run-relative/path/to/model
extra_args: List of extra args to pass to `mlflow models build-docker` command
env: Environment variables to pass to t... | pyfunc_build_image | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def pyfunc_serve_from_docker_image(image_name, host_port, extra_args=None):
"""
Serves a model from a docker container, exposing it as an endpoint at the specified port
on the host machine. Returns a handle (Popen object) to the server process.
"""
env = dict(os.environ)
env.update(LC_ALL="en_US... |
Serves a model from a docker container, exposing it as an endpoint at the specified port
on the host machine. Returns a handle (Popen object) to the server process.
| pyfunc_serve_from_docker_image | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def pyfunc_scoring_endpoint(
model_uri, activity_polling_timeout_seconds=500, extra_args=None, stdout=sys.stdout
):
"""
Args:
model_uri: URI to the model to be served.
activity_polling_timeout_seconds: The amount of time, in seconds, to wait before
declaring the scoring process t... |
Args:
model_uri: URI to the model to be served.
activity_polling_timeout_seconds: The amount of time, in seconds, to wait before
declaring the scoring process to have failed.
extra_args: A list of extra arguments to pass to the pyfunc scoring server command. For
exam... | pyfunc_scoring_endpoint | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def _get_mlflow_home():
"""
Returns:
The path to the MLflow installation root directory.
"""
mlflow_module_path = os.path.dirname(os.path.abspath(mlflow.__file__))
# The MLflow root directory is one level about the mlflow module location
return os.path.join(mlflow_module_path, os.pardir) |
Returns:
The path to the MLflow installation root directory.
| _get_mlflow_home | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def create_mock_response(status_code, text):
"""
Create a mock response object with the status_code and text
Args:
status_code: HTTP status code.
text: Message from the response.
Returns:
Mock HTTP Response.
"""
response = mock.MagicMock()
response.status_code = sta... |
Create a mock response object with the status_code and text
Args:
status_code: HTTP status code.
text: Message from the response.
Returns:
Mock HTTP Response.
| create_mock_response | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def _get_deps_from_requirement_file(model_uri):
"""
Returns a list of pip dependencies for the model at `model_uri` and truncate the version number.
"""
from mlflow.utils.environment import _REQUIREMENTS_FILE_NAME
local_path = _download_artifact_from_uri(model_uri)
pip_packages = _read_lines(os... |
Returns a list of pip dependencies for the model at `model_uri` and truncate the version number.
| _get_deps_from_requirement_file | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def _assert_pip_requirements(model_uri, requirements, constraints=None, strict=False):
"""
Loads the pip requirements (and optionally constraints) from `model_uri` and compares them
to `requirements` (and `constraints`).
If `strict` is True, evaluate `set(requirements) == set(loaded_requirements)`.
... |
Loads the pip requirements (and optionally constraints) from `model_uri` and compares them
to `requirements` (and `constraints`).
If `strict` is True, evaluate `set(requirements) == set(loaded_requirements)`.
Otherwise, evaluate `set(requirements) <= set(loaded_requirements)`.
| _assert_pip_requirements | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def _is_available_on_pypi(package, version=None, module=None):
"""
Returns True if the specified package version is available on PyPI.
Args:
package: The name of the package.
version: The version of the package. If None, defaults to the installed version.
module: The name of the top... |
Returns True if the specified package version is available on PyPI.
Args:
package: The name of the package.
version: The version of the package. If None, defaults to the installed version.
module: The name of the top-level module provided by the package. For example,
if `pa... | _is_available_on_pypi | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def mock_method_chain(mock_obj, methods, return_value=None, side_effect=None):
"""
Mock a chain of methods.
Examples
--------
>>> from unittest import mock
>>> m = mock.MagicMock()
>>> mock_method_chain(m, ["a", "b"], return_value=0)
>>> m.a().b()
0
>>> mock_method_chain(m, ["c.... |
Mock a chain of methods.
Examples
--------
>>> from unittest import mock
>>> m = mock.MagicMock()
>>> mock_method_chain(m, ["a", "b"], return_value=0)
>>> m.a().b()
0
>>> mock_method_chain(m, ["c.d", "e"], return_value=1)
>>> m.c.d().e()
1
>>> mock_method_chain(m, ["f"]... | mock_method_chain | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def flaky(max_tries=3):
"""
Annotation decorator for retrying flaky functions up to max_tries times, and raise the Exception
if it fails after max_tries attempts.
Args:
max_tries: Maximum number of times to retry the function.
Returns:
Decorated function.
"""
def flaky_tes... |
Annotation decorator for retrying flaky functions up to max_tries times, and raise the Exception
if it fails after max_tries attempts.
Args:
max_tries: Maximum number of times to retry the function.
Returns:
Decorated function.
| flaky | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def start_mock_openai_server():
"""
Start a fake service that mimics the OpenAI endpoints such as /chat/completions.
Yields:
The base URL of the mock OpenAI server.
"""
port = get_safe_port()
script_path = Path(__file__).parent / "openai" / "mock_openai.py"
with subprocess.Popen(
... |
Start a fake service that mimics the OpenAI endpoints such as /chat/completions.
Yields:
The base URL of the mock OpenAI server.
| start_mock_openai_server | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def _is_hf_hub_healthy() -> bool:
"""
Check if the Hugging Face Hub is healthy by attempting to load a small dataset.
"""
try:
import datasets
from huggingface_hub import HfApi
except ImportError:
# Cannot import datasets or huggingface_hub, so we assume the hub is healthy.
... |
Check if the Hugging Face Hub is healthy by attempting to load a small dataset.
| _is_hf_hub_healthy | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def get_logged_model_by_name(name: str) -> Optional[LoggedModel]:
"""
Get a logged model by name. If multiple logged models with
the same name exist, get the latest one.
Args:
name: The name of the logged model.
Returns:
The logged model.
"""
logged_models = mlflow.search_l... |
Get a logged model by name. If multiple logged models with
the same name exist, get the latest one.
Args:
name: The name of the logged model.
Returns:
The logged model.
| get_logged_model_by_name | python | mlflow/mlflow | tests/helper_functions.py | https://github.com/mlflow/mlflow/blob/master/tests/helper_functions.py | Apache-2.0 |
def asyncify(is_async):
"""
Decorator that converts a function to an async function if `is_async` is True. This is useful
for testing purposes, where we want to test both synchronous and asynchronous code paths.
"""
def decorator(fn):
if is_async:
async def async_fn(*args, **kw... |
Decorator that converts a function to an async function if `is_async` is True. This is useful
for testing purposes, where we want to test both synchronous and asynchronous code paths.
| asyncify | python | mlflow/mlflow | tests/autologging/async_helper.py | https://github.com/mlflow/mlflow/blob/master/tests/autologging/async_helper.py | Apache-2.0 |
def run_sync_or_async(fn, *args, **kwargs):
"""Convenience function that runs a function synchronously regardless of whether it is async."""
if inspect.iscoroutinefunction(fn):
return asyncio.run(fn(*args, **kwargs))
else:
return fn(*args, **kwargs) | Convenience function that runs a function synchronously regardless of whether it is async. | run_sync_or_async | python | mlflow/mlflow | tests/autologging/async_helper.py | https://github.com/mlflow/mlflow/blob/master/tests/autologging/async_helper.py | Apache-2.0 |
def turn_test_mode_off_by_default(test_mode_off):
"""
Most of the unit test cases in this module assume that autologging APIs are operating in a
standard execution mode (i.e. where test mode is disabled). Accordingly, we turn off autologging
test mode for this test module by default. Test cases that ver... |
Most of the unit test cases in this module assume that autologging APIs are operating in a
standard execution mode (i.e. where test mode is disabled). Accordingly, we turn off autologging
test mode for this test module by default. Test cases that verify behaviors specific to test
mode enable test mode ... | turn_test_mode_off_by_default | python | mlflow/mlflow | tests/autologging/test_autologging_safety_unit.py | https://github.com/mlflow/mlflow/blob/master/tests/autologging/test_autologging_safety_unit.py | Apache-2.0 |
def _event_stream(raw_response, chunk_size=10):
"""Split the raw response into chunks to simulate the event stream."""
content = raw_response["output"]["message"]["content"]
yield {"messageStart": {"role": "assistant"}}
text_content = content[0]["text"]
for i in range(0, len(text_content), chunk_s... | Split the raw response into chunks to simulate the event stream. | _event_stream | python | mlflow/mlflow | tests/bedrock/test_bedrock_autolog.py | https://github.com/mlflow/mlflow/blob/master/tests/bedrock/test_bedrock_autolog.py | Apache-2.0 |
def test_log_catboost_ranker():
"""
This is a separate test for the CatBoostRanker model.
It is separate since the ranking task requires a group_id column which makes the code different.
"""
# the ranking task requires setting a group_id
# we are creating a dummy group_id here that doesn't make ... |
This is a separate test for the CatBoostRanker model.
It is separate since the ranking task requires a group_id column which makes the code different.
| test_log_catboost_ranker | python | mlflow/mlflow | tests/catboost/test_catboost_model_export.py | https://github.com/mlflow/mlflow/blob/master/tests/catboost/test_catboost_model_export.py | Apache-2.0 |
def test_register_constructor_from_entrypoints_and_call(dataset_registry, tmp_path):
"""This test requires the package in tests/resources/mlflow-test-plugin to be installed"""
from mlflow_test_plugin.dummy_dataset import DummyDataset
dataset_registry.register_entrypoints()
dataset = mlflow.data.from_... | This test requires the package in tests/resources/mlflow-test-plugin to be installed | test_register_constructor_from_entrypoints_and_call | python | mlflow/mlflow | tests/data/test_dataset_registry.py | https://github.com/mlflow/mlflow/blob/master/tests/data/test_dataset_registry.py | Apache-2.0 |
def mock_datasets_load_dataset():
"""
`datasets.load_dataset` is flaky and sometimes fails with a network error.
This fixture retries the call up to 5 times with exponential backoff.
"""
original = datasets.load_dataset
def load_dataset(*args, **kwargs):
for i in range(5):
... |
`datasets.load_dataset` is flaky and sometimes fails with a network error.
This fixture retries the call up to 5 times with exponential backoff.
| mock_datasets_load_dataset | python | mlflow/mlflow | tests/data/test_huggingface_dataset_and_source.py | https://github.com/mlflow/mlflow/blob/master/tests/data/test_huggingface_dataset_and_source.py | Apache-2.0 |
def test_set_run_status_to_killed():
"""
This test ensures the following migration scripts work correctly:
- cfd24bdc0731_update_run_status_constraint_with_killed.py
- 0a8213491aaa_drop_duplicate_killed_constraint.py
"""
with mlflow.start_run() as run:
pass
client = MlflowClient()
... |
This test ensures the following migration scripts work correctly:
- cfd24bdc0731_update_run_status_constraint_with_killed.py
- 0a8213491aaa_drop_duplicate_killed_constraint.py
| test_set_run_status_to_killed | python | mlflow/mlflow | tests/db/test_tracking_operations.py | https://github.com/mlflow/mlflow/blob/master/tests/db/test_tracking_operations.py | Apache-2.0 |
def test_create_endpoint_name_mismatch():
"""Test when name is provided both in config and as named arg with different values.
Should raise an MlflowException.
"""
client = get_deploy_client("databricks")
mock_resp = mock.Mock()
mock_resp.json.return_value = {"name": "test"}
mock_resp.url = ... | Test when name is provided both in config and as named arg with different values.
Should raise an MlflowException.
| test_create_endpoint_name_mismatch | python | mlflow/mlflow | tests/deployments/databricks/test_databricks.py | https://github.com/mlflow/mlflow/blob/master/tests/deployments/databricks/test_databricks.py | Apache-2.0 |
def test_create_endpoint_route_optimized_mismatch():
"""Test when route_optimized is provided both in config and as named arg with different values.
Should raise an MlflowException.
"""
client = get_deploy_client("databricks")
mock_resp = mock.Mock()
mock_resp.json.return_value = {"name": "test"... | Test when route_optimized is provided both in config and as named arg with different values.
Should raise an MlflowException.
| test_create_endpoint_route_optimized_mismatch | python | mlflow/mlflow | tests/deployments/databricks/test_databricks.py | https://github.com/mlflow/mlflow/blob/master/tests/deployments/databricks/test_databricks.py | Apache-2.0 |
def test_from_proto_excludes_undefined_fields():
"""
Test that undefined fields (client_request_id, execution_duration) are excluded when
constructing a TraceInfo from a protobuf message instance that does not define these fields.
"""
# Manually create a protobuf without setting client_request_id or... |
Test that undefined fields (client_request_id, execution_duration) are excluded when
constructing a TraceInfo from a protobuf message instance that does not define these fields.
| test_from_proto_excludes_undefined_fields | python | mlflow/mlflow | tests/entities/test_trace_info.py | https://github.com/mlflow/mlflow/blob/master/tests/entities/test_trace_info.py | Apache-2.0 |
def test_trace_info_from_proto_updates_schema_version():
"""Test that TraceInfo.from_proto updates schema version when it exists and is outdated."""
# Create a proto with old schema version in metadata
request_time = Timestamp()
request_time.FromMilliseconds(1234567890)
proto = ProtoTraceInfoV3(
... | Test that TraceInfo.from_proto updates schema version when it exists and is outdated. | test_trace_info_from_proto_updates_schema_version | python | mlflow/mlflow | tests/entities/test_trace_info.py | https://github.com/mlflow/mlflow/blob/master/tests/entities/test_trace_info.py | Apache-2.0 |
def test_trace_info_from_proto_adds_missing_schema_version():
"""Test that TraceInfo.from_proto adds schema version when it doesn't exist."""
# Create a proto without schema version in metadata
request_time = Timestamp()
request_time.FromMilliseconds(1234567890)
proto = ProtoTraceInfoV3(
tr... | Test that TraceInfo.from_proto adds schema version when it doesn't exist. | test_trace_info_from_proto_adds_missing_schema_version | python | mlflow/mlflow | tests/entities/test_trace_info.py | https://github.com/mlflow/mlflow/blob/master/tests/entities/test_trace_info.py | Apache-2.0 |
def test_trace_info_from_proto_preserves_current_schema_version():
"""Test that TraceInfo.from_proto preserves current schema version."""
# Create a proto with current schema version in metadata
request_time = Timestamp()
request_time.FromMilliseconds(1234567890)
proto = ProtoTraceInfoV3(
t... | Test that TraceInfo.from_proto preserves current schema version. | test_trace_info_from_proto_preserves_current_schema_version | python | mlflow/mlflow | tests/entities/test_trace_info.py | https://github.com/mlflow/mlflow/blob/master/tests/entities/test_trace_info.py | Apache-2.0 |
def test_trace_info_v2_to_v3_updates_schema_version():
"""Test that converting from TraceInfoV2 to V3 updates the schema version correctly."""
# Create a V2 trace with old schema version in metadata
trace_info_v2 = TraceInfoV2(
request_id="test_request_id",
experiment_id="test_experiment",
... | Test that converting from TraceInfoV2 to V3 updates the schema version correctly. | test_trace_info_v2_to_v3_updates_schema_version | python | mlflow/mlflow | tests/entities/test_trace_info_v2.py | https://github.com/mlflow/mlflow/blob/master/tests/entities/test_trace_info_v2.py | Apache-2.0 |
def suppress_dummy_evaluator():
"""
Dummy evaluator is registered by the test plugin and used in
test_evaluation.py, but we don't want it to be used in this test.
This fixture suppress dummy evaluator for the duration of each test.
"""
from mlflow.models.evaluation.evaluator_registry import _mo... |
Dummy evaluator is registered by the test plugin and used in
test_evaluation.py, but we don't want it to be used in this test.
This fixture suppress dummy evaluator for the duration of each test.
| suppress_dummy_evaluator | python | mlflow/mlflow | tests/evaluate/test_default_evaluator.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_default_evaluator.py | Apache-2.0 |
def get_pipeline_model_dataset():
"""
The dataset tweaks the IRIS dataset by changing its first 2 features into categorical features,
and replace some feature values with NA values.
The dataset is prepared for a pipeline model, see `pipeline_model_uri`.
"""
X, y = get_iris()
def convert_num... |
The dataset tweaks the IRIS dataset by changing its first 2 features into categorical features,
and replace some feature values with NA values.
The dataset is prepared for a pipeline model, see `pipeline_model_uri`.
| get_pipeline_model_dataset | python | mlflow/mlflow | tests/evaluate/test_evaluation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_evaluation.py | Apache-2.0 |
def get_pipeline_model_uri():
"""
Create a pipeline model that transforms and trains on the dataset returned by
`get_pipeline_model_dataset`. The pipeline model imputes the missing values in
input dataset, encodes categorical features, and then trains a logistic regression
model.
"""
data, t... |
Create a pipeline model that transforms and trains on the dataset returned by
`get_pipeline_model_dataset`. The pipeline model imputes the missing values in
input dataset, encodes categorical features, and then trains a logistic regression
model.
| get_pipeline_model_uri | python | mlflow/mlflow | tests/evaluate/test_evaluation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_evaluation.py | Apache-2.0 |
def test_custom_evaluators_no_model_or_preds(multiclass_logistic_regressor_model_uri, iris_dataset):
"""
Tests that custom evaluators are called correctly when no model or predictions are provided
"""
with mock.patch.object(
_model_evaluation_registry, "_registry", {"test_evaluator1": FakeEvalua... |
Tests that custom evaluators are called correctly when no model or predictions are provided
| test_custom_evaluators_no_model_or_preds | python | mlflow/mlflow | tests/evaluate/test_evaluation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_evaluation.py | Apache-2.0 |
def test_evaluate_model_id_consistency_check(multiclass_logistic_regressor_model_uri, iris_dataset):
"""
Test that an error is thrown when the specified model_id contradicts the model's associated ID.
"""
# Create a model with a known model ID
with mlflow.start_run():
model = sklearn.linear_... |
Test that an error is thrown when the specified model_id contradicts the model's associated ID.
| test_evaluate_model_id_consistency_check | python | mlflow/mlflow | tests/evaluate/test_evaluation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_evaluation.py | Apache-2.0 |
def metric_threshold_class_test_spec(request):
"""
Test specification for MetricThreshold class:
Returns:
A tuple containing the following elements:
- class_params: A dictionary mapping MetricThreshold class parameter names to values.
- expected_failure_message: Expected failure me... |
Test specification for MetricThreshold class:
Returns:
A tuple containing the following elements:
- class_params: A dictionary mapping MetricThreshold class parameter names to values.
- expected_failure_message: Expected failure message.
| metric_threshold_class_test_spec | python | mlflow/mlflow | tests/evaluate/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_validation.py | Apache-2.0 |
def faulty_baseline_model_param_test_spec(request):
"""
Test specification for faulty `baseline_model` parameter tests:
Returns:
A dict containing the following elements:
- validation_thresholds: A dictionary mapping scalar metric names to
MetricThreshold(threshold=0.2, greater_i... |
Test specification for faulty `baseline_model` parameter tests:
Returns:
A dict containing the following elements:
- validation_thresholds: A dictionary mapping scalar metric names to
MetricThreshold(threshold=0.2, greater_is_better=True).
- baseline_model: Value for the `ba... | faulty_baseline_model_param_test_spec | python | mlflow/mlflow | tests/evaluate/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_validation.py | Apache-2.0 |
def value_threshold_test_spec(request):
"""
Test specification for value threshold tests:
Returns:
A dict containing the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- validation_thresholds: A dictionary mapping scalar metric name... |
Test specification for value threshold tests:
Returns:
A dict containing the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- validation_thresholds: A dictionary mapping scalar metric names to
MetricThreshold(threshold=0.2, g... | value_threshold_test_spec | python | mlflow/mlflow | tests/evaluate/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_validation.py | Apache-2.0 |
def min_absolute_change_threshold_test_spec(request):
"""
Test specification for min_absolute_change threshold tests:
Returns:
A dict containing the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- baseline_model_metrics: A dictiona... |
Test specification for min_absolute_change threshold tests:
Returns:
A dict containing the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- baseline_model_metrics: A dictionary mapping scalar metric names
to scalar metric v... | min_absolute_change_threshold_test_spec | python | mlflow/mlflow | tests/evaluate/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_validation.py | Apache-2.0 |
def min_relative_change_threshold_test_spec(request):
"""
Test specification for min_relative_change threshold tests:
Returns:
A dict with the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- baseline_model_metrics: A dictionary map... |
Test specification for min_relative_change threshold tests:
Returns:
A dict with the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- baseline_model_metrics: A dictionary mapping scalar metric names
to scalar metric values ... | min_relative_change_threshold_test_spec | python | mlflow/mlflow | tests/evaluate/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_validation.py | Apache-2.0 |
def multi_thresholds_test_spec(request):
"""
Test specification for multi-thresholds tests:
Returns:
A dict with the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- baseline_model_metrics: A dictionary mapping scalar metric names
... |
Test specification for multi-thresholds tests:
Returns:
A dict with the following elements:
- metrics: A dictionary mapping scalar metric names to scalar metric values.
- baseline_model_metrics: A dictionary mapping scalar metric names
to scalar metric values of baseline_m... | multi_thresholds_test_spec | python | mlflow/mlflow | tests/evaluate/test_validation.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/test_validation.py | Apache-2.0 |
def get_evaluation(*, run_id: str, evaluation_id: str) -> EvaluationEntity:
"""
Retrieves an Evaluation object from an MLflow Run.
Args:
run_id (str): ID of the MLflow Run containing the evaluation.
evaluation_id (str): The ID of the evaluation.
Returns:
Evaluation: The Evaluat... |
Retrieves an Evaluation object from an MLflow Run.
Args:
run_id (str): ID of the MLflow Run containing the evaluation.
evaluation_id (str): The ID of the evaluation.
Returns:
Evaluation: The Evaluation object.
| get_evaluation | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def _read_evaluations_dataframe(path: str) -> pd.DataFrame:
"""
Reads an evaluations DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The evaluations DataFrame.
"""
schema = _get_evaluations_dataframe_schema()
return pd.read_json(path, orien... |
Reads an evaluations DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The evaluations DataFrame.
| _read_evaluations_dataframe | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def _read_assessments_dataframe(path: str) -> pd.DataFrame:
"""
Reads an assessments DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The assessments DataFrame.
"""
schema = _get_assessments_dataframe_schema()
return pd.read_json(path, orien... |
Reads an assessments DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The assessments DataFrame.
| _read_assessments_dataframe | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def _read_metrics_dataframe(path: str) -> pd.DataFrame:
"""
Reads a metrics DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The metrics DataFrame.
"""
schema = _get_metrics_dataframe_schema()
return pd.read_json(path, orient="split", dtype=... |
Reads a metrics DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The metrics DataFrame.
| _read_metrics_dataframe | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def _read_tags_dataframe(path: str) -> pd.DataFrame:
"""
Reads a tags DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The tags DataFrame.
"""
schema = _get_tags_dataframe_schema()
return pd.read_json(path, orient="split", dtype=schema, conv... |
Reads a tags DataFrame from a file.
Args:
path (str): Path to the file.
Returns:
pd.DataFrame: The tags DataFrame.
| _read_tags_dataframe | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def _get_evaluation_from_dataframes(
*,
run_id: str,
evaluation_id: str,
evaluations_df: pd.DataFrame,
metrics_df: pd.DataFrame,
assessments_df: pd.DataFrame,
tags_df: pd.DataFrame,
) -> EvaluationEntity:
"""
Parses an Evaluation object with the specified evaluation ID from the speci... |
Parses an Evaluation object with the specified evaluation ID from the specified DataFrames.
| _get_evaluation_from_dataframes | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def _dataframes_to_evaluations(
evaluations_df: pd.DataFrame,
metrics_df: pd.DataFrame,
assessments_df: pd.DataFrame,
tags_df: pd.DataFrame,
) -> list[EvaluationEntity]:
"""
Converts four separate DataFrames (main evaluation data, metrics, assessments, and tags) back
into a list of Evaluatio... |
Converts four separate DataFrames (main evaluation data, metrics, assessments, and tags) back
into a list of Evaluation entities.
Args:
evaluations_df (pd.DataFrame): DataFrame with the main evaluation data
(excluding assessment and metrics).
metrics_df (pd.DataFrame): DataFram... | _dataframes_to_evaluations | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def _group_dataframe_by_evaluation_id(df: pd.DataFrame):
"""
Groups evaluation dataframe rows by 'evaluation_id'.
Args:
df (pd.DataFrame): DataFrame to group.
Returns:
Dict[str, List]: A dictionary with 'evaluation_id' as keys and lists of entity
dictionaries as values.
... |
Groups evaluation dataframe rows by 'evaluation_id'.
Args:
df (pd.DataFrame): DataFrame to group.
Returns:
Dict[str, List]: A dictionary with 'evaluation_id' as keys and lists of entity
dictionaries as values.
| _group_dataframe_by_evaluation_id | python | mlflow/mlflow | tests/evaluate/logging/utils.py | https://github.com/mlflow/mlflow/blob/master/tests/evaluate/logging/utils.py | Apache-2.0 |
def test_scheduled_scorer_class_instantiation():
"""Test that ScheduledScorer class can be instantiated without import errors."""
mock_scorer = MockScorer()
scheduled_scorer = ScorerScheduleConfig(
scorer=mock_scorer,
scheduled_scorer_name="test_scorer",
sample_rate=0.5,
filt... | Test that ScheduledScorer class can be instantiated without import errors. | test_scheduled_scorer_class_instantiation | python | mlflow/mlflow | tests/genai/test_scheduled_scorers.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/test_scheduled_scorers.py | Apache-2.0 |
def test_trace_input_can_contain_string_input(pass_full_dataframe):
"""
The `inputs` column must be a dictionary when a static dataset is provided.
However, when a trace is provided, it doesn't need to be validated and the
harness can handle it nicely.
"""
with mlflow.start_span() as span:
... |
The `inputs` column must be a dictionary when a static dataset is provided.
However, when a trace is provided, it doesn't need to be validated and the
harness can handle it nicely.
| test_trace_input_can_contain_string_input | python | mlflow/mlflow | tests/genai/evaluate/test_evaluation.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/evaluate/test_evaluation.py | Apache-2.0 |
def test_to_predict_fn_pass_tracing_check(
sample_rag_trace, mock_deploy_client, mock_tracing_client
):
"""
The function produced by to_predict_fn() is guaranteed to create a trace.
Therefore it should not be wrapped by @mlflow.trace by convert_predict_fn().
"""
mock_deploy_client.predict.side_e... |
The function produced by to_predict_fn() is guaranteed to create a trace.
Therefore it should not be wrapped by @mlflow.trace by convert_predict_fn().
| test_to_predict_fn_pass_tracing_check | python | mlflow/mlflow | tests/genai/evaluate/test_to_predict_fn.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/evaluate/test_to_predict_fn.py | Apache-2.0 |
def test_input_categorical_to_databricks_input():
"""Test conversion to Databricks input type."""
options = ["good", "bad", "neutral"]
input_cat = InputCategorical(options=options)
mock_databricks_input = MagicMock()
with patch(
"databricks.agents.review_app.label_schemas.InputCategorical",... | Test conversion to Databricks input type. | test_input_categorical_to_databricks_input | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_categorical_from_databricks_input():
"""Test creation from Databricks input type."""
options = ["excellent", "good", "poor"]
mock_databricks_input = MagicMock()
mock_databricks_input.options = options
result = InputCategorical._from_databricks_input(mock_databricks_input)
assert... | Test creation from Databricks input type. | test_input_categorical_from_databricks_input | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_text_from_databricks_input_none_max_length():
"""Test creation from Databricks input type with None max_length."""
mock_databricks_input = MagicMock()
mock_databricks_input.max_length = None
result = InputText._from_databricks_input(mock_databricks_input)
assert isinstance(result, I... | Test creation from Databricks input type with None max_length. | test_input_text_from_databricks_input_none_max_length | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_text_list_init_with_all_params():
"""Test InputTextList initialization with all parameters."""
input_text_list = InputTextList(max_length_each=50, max_count=5)
assert input_text_list.max_length_each == 50
assert input_text_list.max_count == 5 | Test InputTextList initialization with all parameters. | test_input_text_list_init_with_all_params | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_text_list_init_with_partial_params():
"""Test InputTextList initialization with partial parameters."""
input_text_list = InputTextList(max_count=3)
assert input_text_list.max_length_each is None
assert input_text_list.max_count == 3 | Test InputTextList initialization with partial parameters. | test_input_text_list_init_with_partial_params | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_text_list_init_with_no_params():
"""Test InputTextList initialization with no parameters."""
input_text_list = InputTextList()
assert input_text_list.max_length_each is None
assert input_text_list.max_count is None | Test InputTextList initialization with no parameters. | test_input_text_list_init_with_no_params | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_numeric_init_with_all_params():
"""Test InputNumeric initialization with all parameters."""
input_numeric = InputNumeric(min_value=0.0, max_value=10.0)
assert input_numeric.min_value == 0.0
assert input_numeric.max_value == 10.0 | Test InputNumeric initialization with all parameters. | test_input_numeric_init_with_all_params | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_numeric_init_with_partial_params():
"""Test InputNumeric initialization with partial parameters."""
input_numeric = InputNumeric(min_value=5.0)
assert input_numeric.min_value == 5.0
assert input_numeric.max_value is None | Test InputNumeric initialization with partial parameters. | test_input_numeric_init_with_partial_params | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_numeric_init_with_no_params():
"""Test InputNumeric initialization with no parameters."""
input_numeric = InputNumeric()
assert input_numeric.min_value is None
assert input_numeric.max_value is None | Test InputNumeric initialization with no parameters. | test_input_numeric_init_with_no_params | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_input_type_all_inputs_implement_required_methods(input_obj):
"""Test that all input classes implement required abstract methods."""
assert hasattr(input_obj, "_to_databricks_input")
assert callable(getattr(input_obj, "_to_databricks_input"))
assert hasattr(input_obj.__class__, "_from_databricks... | Test that all input classes implement required abstract methods. | test_input_type_all_inputs_implement_required_methods | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_label_schema_init_with_categorical_input():
"""Test LabelSchema initialization with categorical input."""
input_cat = InputCategorical(options=["good", "bad"])
schema = LabelSchema(
name="quality",
type=LabelSchemaType.FEEDBACK,
title="Rate the quality",
input=input_... | Test LabelSchema initialization with categorical input. | test_label_schema_init_with_categorical_input | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_label_schema_init_with_all_params():
"""Test LabelSchema initialization with all parameters."""
input_text = InputText(max_length=200)
schema = LabelSchema(
name="feedback_schema",
type=LabelSchemaType.EXPECTATION,
title="Provide feedback",
input=input_text,
... | Test LabelSchema initialization with all parameters. | test_label_schema_init_with_all_params | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_label_schema_init_with_numeric_input():
"""Test LabelSchema initialization with numeric input."""
input_numeric = InputNumeric(min_value=1.0, max_value=5.0)
schema = LabelSchema(
name="rating",
type=LabelSchemaType.FEEDBACK,
title="Rate from 1 to 5",
input=input_nume... | Test LabelSchema initialization with numeric input. | test_label_schema_init_with_numeric_input | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_label_schema_init_with_text_list_input():
"""Test LabelSchema initialization with text list input."""
input_text_list = InputTextList(max_length_each=50, max_count=3)
schema = LabelSchema(
name="suggestions",
type=LabelSchemaType.EXPECTATION,
title="Provide suggestions",
... | Test LabelSchema initialization with text list input. | test_label_schema_init_with_text_list_input | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_label_schema_init_with_categorical_list_input():
"""Test LabelSchema initialization with categorical list input."""
input_cat_list = InputCategoricalList(options=["tag1", "tag2", "tag3"])
schema = LabelSchema(
name="tags",
type=LabelSchemaType.FEEDBACK,
title="Select relevan... | Test LabelSchema initialization with categorical list input. | test_label_schema_init_with_categorical_list_input | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_label_schema_frozen_dataclass():
"""Test that LabelSchema is frozen (immutable)."""
input_cat = InputCategorical(options=["test"])
schema = LabelSchema(
name="test",
type=LabelSchemaType.FEEDBACK,
title="Test",
input=input_cat,
)
with pytest.raises(dataclass... | Test that LabelSchema is frozen (immutable). | test_label_schema_frozen_dataclass | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_label_schema_from_databricks_label_schema():
"""Test creation from Databricks label schema."""
# Mock Databricks schema
mock_databricks_schema = MagicMock()
mock_databricks_schema.name = "test_schema"
mock_databricks_schema.type = LabelSchemaType.FEEDBACK
mock_databricks_schema.title = ... | Test creation from Databricks label schema. | test_label_schema_from_databricks_label_schema | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_integration_complete_workflow_categorical():
"""Test complete workflow with categorical input."""
# Create InputCategorical
options = ["excellent", "good", "fair", "poor"]
input_cat = InputCategorical(options=options)
# Convert to Databricks input and back
with patch("databricks.agents... | Test complete workflow with categorical input. | test_integration_complete_workflow_categorical | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_integration_complete_workflow_numeric():
"""Test complete workflow with numeric input."""
# Create InputNumeric
min_val, max_val = 0.0, 10.0
input_numeric = InputNumeric(min_value=min_val, max_value=max_val)
# Convert to Databricks input and back
with patch("databricks.agents.review_ap... | Test complete workflow with numeric input. | test_integration_complete_workflow_numeric | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_integration_label_schema_with_different_input_types(input_type, schema_name):
"""Test LabelSchema works with all input types."""
schema = LabelSchema(
name=schema_name,
type=LabelSchemaType.FEEDBACK,
title=f"Schema for {schema_name}",
input=input_type,
)
assert ... | Test LabelSchema works with all input types. | test_integration_label_schema_with_different_input_types | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_edge_cases_empty_string_values():
"""Test handling of empty string values."""
schema = LabelSchema(
name="",
type=LabelSchemaType.FEEDBACK,
title="",
input=InputCategorical(options=[]),
instruction="",
)
assert schema.name == ""
assert schema.title =... | Test handling of empty string values. | test_edge_cases_empty_string_values | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_edge_cases_numeric_value_ranges(min_value, max_value, description):
"""Test handling of various numeric value ranges."""
input_numeric = InputNumeric(min_value=min_value, max_value=max_value)
assert input_numeric.min_value == min_value
assert input_numeric.max_value == max_value | Test handling of various numeric value ranges. | test_edge_cases_numeric_value_ranges | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
def test_edge_cases_zero_max_length_text():
"""Test handling of zero max_length for text."""
input_text = InputText(max_length=0)
assert input_text.max_length == 0 | Test handling of zero max_length for text. | test_edge_cases_zero_max_length_text | python | mlflow/mlflow | tests/genai/label_schemas/test_label_schemas.py | https://github.com/mlflow/mlflow/blob/master/tests/genai/label_schemas/test_label_schemas.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.