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 test_signature_and_examples_saved_correctly(
auto_arima_model, data_airline, model_path, use_signature, use_example
):
"""Test saving of mlflow signature and example for native sktime predict method."""
# Note: Signature inference fails on native model predict_interval/predict_quantiles
prediction =... | Test saving of mlflow signature and example for native sktime predict method. | test_signature_and_examples_saved_correctly | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_predict_var_signature_saved_correctly(
auto_arima_model, data_airline, model_path, use_signature
):
"""Test saving of mlflow signature for native sktime predict_var method."""
prediction = auto_arima_model.predict_var(fh=FH)
signature = infer_signature(data_airline, prediction) if use_signature... | Test saving of mlflow signature for native sktime predict_var method. | test_predict_var_signature_saved_correctly | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_signature_and_example_for_pyfunc_predict_interval(
auto_arima_model, model_path, data_airline, use_signature, use_example
):
"""Test saving of mlflow signature and example for pyfunc predict."""
model_path_primary = model_path.joinpath("primary")
model_path_secondary = model_path.joinpath("seco... | Test saving of mlflow signature and example for pyfunc predict. | test_signature_and_example_for_pyfunc_predict_interval | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_signature_for_pyfunc_predict_quantiles(
auto_arima_model, model_path, data_airline, use_signature
):
"""Test saving of mlflow signature for pyfunc sktime predict_quantiles method."""
model_path_primary = model_path.joinpath("primary")
model_path_secondary = model_path.joinpath("secondary")
... | Test saving of mlflow signature for pyfunc sktime predict_quantiles method. | test_signature_for_pyfunc_predict_quantiles | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_load_from_remote_uri_succeeds(auto_arima_model, model_path, mock_s3_bucket):
"""Test loading native sktime model from mock S3 bucket."""
flavor.save_model(sktime_model=auto_arima_model, path=model_path)
artifact_root = f"s3://{mock_s3_bucket}"
artifact_path = "model"
artifact_repo = S3Arti... | Test loading native sktime model from mock S3 bucket. | test_load_from_remote_uri_succeeds | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_log_model(auto_arima_model, tmp_path, should_start_run, serialization_format):
"""Test logging and reloading sktime model."""
try:
if should_start_run:
mlflow.start_run()
artifact_path = "sktime"
conda_env = tmp_path.joinpath("conda_env.yaml")
_mlflow_conda_e... | Test logging and reloading sktime model. | test_log_model | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_log_model_calls_register_model(auto_arima_model, tmp_path):
"""Test log model calls register model."""
artifact_path = "sktime"
register_model_patch = mock.patch("mlflow.register_model")
with mlflow.start_run(), register_model_patch:
conda_env = tmp_path.joinpath("conda_env.yaml")
... | Test log model calls register model. | test_log_model_calls_register_model | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_log_model_no_registered_model_name(auto_arima_model, tmp_path):
"""Test log model calls register model without registered model name."""
artifact_path = "sktime"
register_model_patch = mock.patch("mlflow.register_model")
with mlflow.start_run(), register_model_patch:
conda_env = tmp_pat... | Test log model calls register model without registered model name. | test_log_model_no_registered_model_name | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_sktime_pyfunc_raises_invalid_df_input(auto_arima_model, model_path):
"""Test pyfunc call raises error with invalid dataframe configuration."""
flavor.save_model(sktime_model=auto_arima_model, path=model_path)
loaded_pyfunc = flavor.pyfunc.load_model(model_uri=model_path)
with pytest.raises(Mlf... | Test pyfunc call raises error with invalid dataframe configuration. | test_sktime_pyfunc_raises_invalid_df_input | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_sktime_save_model_raises_invalid_serialization_format(auto_arima_model, model_path):
"""Test save_model call raises error with invalid serialization format."""
with pytest.raises(MlflowException, match="Unrecognized serialization format: "):
flavor.save_model(
sktime_model=auto_arim... | Test save_model call raises error with invalid serialization format. | test_sktime_save_model_raises_invalid_serialization_format | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def run(
uri,
entry_point,
version,
param_list,
docker_args,
experiment_name,
experiment_id,
backend,
backend_config,
env_manager,
storage_dir,
run_id,
run_name,
build_image,
):
"""
Run an MLflow project from the given URI.
For local runs, the run wil... |
Run an MLflow project from the given URI.
For local runs, the run will block until it completes.
Otherwise, the project will run asynchronously.
If running locally (the default), the URI can be either a Git repository URI or a local path.
If running on Databricks, the URI must be a Git repository... | run | python | mlflow/mlflow | mlflow/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/cli.py | Apache-2.0 |
def _validate_static_prefix(ctx, param, value):
"""
Validate that the static_prefix option starts with a "/" and does not end in a "/".
Conforms to the callback interface of click documented at
http://click.pocoo.org/5/options/#callbacks-for-validation.
"""
if value is not None:
if not v... |
Validate that the static_prefix option starts with a "/" and does not end in a "/".
Conforms to the callback interface of click documented at
http://click.pocoo.org/5/options/#callbacks-for-validation.
| _validate_static_prefix | python | mlflow/mlflow | mlflow/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/cli.py | Apache-2.0 |
def server(
backend_store_uri,
registry_store_uri,
default_artifact_root,
serve_artifacts,
artifacts_only,
artifacts_destination,
host,
port,
workers,
static_prefix,
gunicorn_opts,
waitress_opts,
expose_prometheus,
app_name,
dev,
):
"""
Run the MLflow ... |
Run the MLflow tracking server.
The server listens on http://localhost:5000 by default and only accepts connections
from the local machine. To let the server accept connections from other machines, you will need
to pass ``--host 0.0.0.0`` to listen on all network interfaces
(or a specific interfac... | server | python | mlflow/mlflow | mlflow/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/cli.py | Apache-2.0 |
def gc(older_than, backend_store_uri, artifacts_destination, run_ids, experiment_ids, tracking_uri):
"""
Permanently delete runs in the `deleted` lifecycle stage from the specified backend store.
This command deletes all artifacts and metadata associated with the specified runs.
If the provided artifact... |
Permanently delete runs in the `deleted` lifecycle stage from the specified backend store.
This command deletes all artifacts and metadata associated with the specified runs.
If the provided artifact URL is invalid, the artifact deletion will be bypassed,
and the gc process will continue.
.. atten... | gc | python | mlflow/mlflow | mlflow/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/cli.py | Apache-2.0 |
def commands():
"""
Commands for managing an MLflow tracking database.
""" |
Commands for managing an MLflow tracking database.
| commands | python | mlflow/mlflow | mlflow/db.py | https://github.com/mlflow/mlflow/blob/master/mlflow/db.py | Apache-2.0 |
def upgrade(url):
"""
Upgrade the schema of an MLflow tracking database to the latest supported version.
**IMPORTANT**: Schema migrations can be slow and are not guaranteed to be transactional -
**always take a backup of your database before running migrations**. The migrations README,
which is loc... |
Upgrade the schema of an MLflow tracking database to the latest supported version.
**IMPORTANT**: Schema migrations can be slow and are not guaranteed to be transactional -
**always take a backup of your database before running migrations**. The migrations README,
which is located at
https://githu... | upgrade | python | mlflow/mlflow | mlflow/db.py | https://github.com/mlflow/mlflow/blob/master/mlflow/db.py | Apache-2.0 |
def get(self):
"""
Reads the value of the environment variable if it exists and converts it to the desired
type. Otherwise, returns the default value.
"""
if (val := self.get_raw()) is not None:
try:
return self.type(val)
except Exception a... |
Reads the value of the environment variable if it exists and converts it to the desired
type. Otherwise, returns the default value.
| get | python | mlflow/mlflow | mlflow/environment_variables.py | https://github.com/mlflow/mlflow/blob/master/mlflow/environment_variables.py | Apache-2.0 |
def __init__(self, message, error_code=INTERNAL_ERROR, **kwargs):
"""
Args:
message: The message or exception describing the error that occurred. This will be
included in the exception's serialized JSON representation.
error_code: An appropriate error code for the... |
Args:
message: The message or exception describing the error that occurred. This will be
included in the exception's serialized JSON representation.
error_code: An appropriate error code for the error that occurred; it will be
included in the exception's ... | __init__ | python | mlflow/mlflow | mlflow/exceptions.py | https://github.com/mlflow/mlflow/blob/master/mlflow/exceptions.py | Apache-2.0 |
def commands():
"""
Manage experiments. To manage experiments associated with a tracking server, set the
MLFLOW_TRACKING_URI environment variable to the URL of the desired server.
""" |
Manage experiments. To manage experiments associated with a tracking server, set the
MLFLOW_TRACKING_URI environment variable to the URL of the desired server.
| commands | python | mlflow/mlflow | mlflow/experiments.py | https://github.com/mlflow/mlflow/blob/master/mlflow/experiments.py | Apache-2.0 |
def create(experiment_name, artifact_location):
"""
Create an experiment.
All artifacts generated by runs related to this experiment will be stored under artifact
location, organized under specific run_id sub-directories.
Implementation of experiment and metadata store is dependent on backend stor... |
Create an experiment.
All artifacts generated by runs related to this experiment will be stored under artifact
location, organized under specific run_id sub-directories.
Implementation of experiment and metadata store is dependent on backend storage. ``FileStore``
creates a folder for each experi... | create | python | mlflow/mlflow | mlflow/experiments.py | https://github.com/mlflow/mlflow/blob/master/mlflow/experiments.py | Apache-2.0 |
def search_experiments(view):
"""
Search for experiments in the configured tracking server.
"""
view_type = ViewType.from_string(view) if view else ViewType.ACTIVE_ONLY
experiments = mlflow.search_experiments(view_type=view_type)
table = [
[
exp.experiment_id,
exp... |
Search for experiments in the configured tracking server.
| search_experiments | python | mlflow/mlflow | mlflow/experiments.py | https://github.com/mlflow/mlflow/blob/master/mlflow/experiments.py | Apache-2.0 |
def delete_experiment(experiment_id):
"""
Mark an active experiment for deletion. This also applies to experiment's metadata, runs and
associated data, and artifacts if they are store in default location. Use ``list`` command to
view artifact location. Command will throw an error if experiment is not fo... |
Mark an active experiment for deletion. This also applies to experiment's metadata, runs and
associated data, and artifacts if they are store in default location. Use ``list`` command to
view artifact location. Command will throw an error if experiment is not found or already
marked for deletion.
... | delete_experiment | python | mlflow/mlflow | mlflow/experiments.py | https://github.com/mlflow/mlflow/blob/master/mlflow/experiments.py | Apache-2.0 |
def restore_experiment(experiment_id):
"""
Restore a deleted experiment. This also applies to experiment's metadata, runs and associated
data. The command throws an error if the experiment is already active, cannot be found, or
permanently deleted.
"""
store = _get_store()
store.restore_expe... |
Restore a deleted experiment. This also applies to experiment's metadata, runs and associated
data. The command throws an error if the experiment is already active, cannot be found, or
permanently deleted.
| restore_experiment | python | mlflow/mlflow | mlflow/experiments.py | https://github.com/mlflow/mlflow/blob/master/mlflow/experiments.py | Apache-2.0 |
def rename_experiment(experiment_id, new_name):
"""
Renames an active experiment.
Returns an error if the experiment is inactive.
"""
store = _get_store()
store.rename_experiment(experiment_id, new_name)
click.echo(f"Experiment with id {experiment_id} has been renamed to '{new_name}'.") |
Renames an active experiment.
Returns an error if the experiment is inactive.
| rename_experiment | python | mlflow/mlflow | mlflow/experiments.py | https://github.com/mlflow/mlflow/blob/master/mlflow/experiments.py | Apache-2.0 |
def generate_csv_with_runs(experiment_id, filename):
# type: (str, str) -> None
"""
Generate CSV with all runs for an experiment
"""
runs = fluent.search_runs(experiment_ids=experiment_id)
if filename:
runs.to_csv(filename, index=False)
click.echo(
f"Experiment with I... |
Generate CSV with all runs for an experiment
| generate_csv_with_runs | python | mlflow/mlflow | mlflow/experiments.py | https://github.com/mlflow/mlflow/blob/master/mlflow/experiments.py | Apache-2.0 |
def _check_version_mismatch() -> None:
"""
Warns if both mlflow and mlflow-skinny are installed but their versions are different.
Reference: https://github.com/pypa/pip/issues/4625
"""
if (
(mlflow_ver := _get_version("mlflow"))
and ("dev" not in mlflow_ver)
and (skinny_ver ... |
Warns if both mlflow and mlflow-skinny are installed but their versions are different.
Reference: https://github.com/pypa/pip/issues/4625
| _check_version_mismatch | python | mlflow/mlflow | mlflow/mismatch.py | https://github.com/mlflow/mlflow/blob/master/mlflow/mismatch.py | Apache-2.0 |
def commands():
"""
Manage runs. To manage runs of experiments associated with a tracking server, set the
MLFLOW_TRACKING_URI environment variable to the URL of the desired server.
""" |
Manage runs. To manage runs of experiments associated with a tracking server, set the
MLFLOW_TRACKING_URI environment variable to the URL of the desired server.
| commands | python | mlflow/mlflow | mlflow/runs.py | https://github.com/mlflow/mlflow/blob/master/mlflow/runs.py | Apache-2.0 |
def list_run(experiment_id, view):
"""
List all runs of the specified experiment in the configured tracking server.
"""
store = _get_store()
view_type = ViewType.from_string(view) if view else ViewType.ACTIVE_ONLY
runs = store.search_runs([experiment_id], None, view_type)
table = []
for ... |
List all runs of the specified experiment in the configured tracking server.
| list_run | python | mlflow/mlflow | mlflow/runs.py | https://github.com/mlflow/mlflow/blob/master/mlflow/runs.py | Apache-2.0 |
def delete_run(run_id):
"""
Mark a run for deletion. Return an error if the run does not exist or
is already marked. You can restore a marked run with ``restore_run``,
or permanently delete a run in the backend store.
"""
store = _get_store()
store.delete_run(run_id)
click.echo(f"Run wit... |
Mark a run for deletion. Return an error if the run does not exist or
is already marked. You can restore a marked run with ``restore_run``,
or permanently delete a run in the backend store.
| delete_run | python | mlflow/mlflow | mlflow/runs.py | https://github.com/mlflow/mlflow/blob/master/mlflow/runs.py | Apache-2.0 |
def restore_run(run_id):
"""
Restore a deleted run.
Returns an error if the run is active or has been permanently deleted.
"""
store = _get_store()
store.restore_run(run_id)
click.echo(f"Run with id {run_id} has been restored.") |
Restore a deleted run.
Returns an error if the run is active or has been permanently deleted.
| restore_run | python | mlflow/mlflow | mlflow/runs.py | https://github.com/mlflow/mlflow/blob/master/mlflow/runs.py | Apache-2.0 |
def describe_run(run_id):
"""
All of run details will print to the stdout as JSON format.
"""
store = _get_store()
run = store.get_run(run_id)
json_run = json.dumps(run.to_dictionary(), indent=4)
click.echo(json_run) |
All of run details will print to the stdout as JSON format.
| describe_run | python | mlflow/mlflow | mlflow/runs.py | https://github.com/mlflow/mlflow/blob/master/mlflow/runs.py | Apache-2.0 |
def log_new_agent(self, agent: ConversableAgent, init_args: dict[str, Any]) -> None:
"""
This handler is called whenever a new agent instance is created.
Here we patch the agent's methods to start and end a trace around its chat session.
"""
# TODO: Patch generate_reply() method ... |
This handler is called whenever a new agent instance is created.
Here we patch the agent's methods to start and end a trace around its chat session.
| log_new_agent | python | mlflow/mlflow | mlflow/ag2/ag2_logger.py | https://github.com/mlflow/mlflow/blob/master/mlflow/ag2/ag2_logger.py | Apache-2.0 |
def _get_patch_function(self, span_type: str = SpanType.UNKNOWN, root_only: bool = False):
"""
Patch a function to start and end a span around its invocation.
Args:
f: The function to patch.
span_name: The name of the span. If None, the function name is used.
... |
Patch a function to start and end a span around its invocation.
Args:
f: The function to patch.
span_name: The name of the span. If None, the function name is used.
span_type: The type of the span. Default is SpanType.UNKNOWN.
root_only: If True, only cr... | _get_patch_function | python | mlflow/mlflow | mlflow/ag2/ag2_logger.py | https://github.com/mlflow/mlflow/blob/master/mlflow/ag2/ag2_logger.py | Apache-2.0 |
def _start_span_in_session(
self,
name: str,
span_type: str,
inputs: dict[str, Any],
attributes: Optional[dict[str, Any]] = None,
start_time_ns: Optional[int] = None,
) -> Span:
"""
Start a span in the current chat session.
"""
if self.... |
Start a span in the current chat session.
| _start_span_in_session | python | mlflow/mlflow | mlflow/ag2/ag2_logger.py | https://github.com/mlflow/mlflow/blob/master/mlflow/ag2/ag2_logger.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from ag2 to MLflow. Currently, MLflow
only supports tracing for ag2 agents.
Args:
log_traces: If ``True``, traces are logged for AG2 agents by u... |
Enables (or disables) and configures autologging from ag2 to MLflow. Currently, MLflow
only supports tracing for ag2 agents.
Args:
log_traces: If ``True``, traces are logged for AG2 agents by using runtime logging.
If ``False``, no traces are collected during inference. Default to ``Tr... | autolog | python | mlflow/mlflow | mlflow/ag2/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/ag2/__init__.py | Apache-2.0 |
def _autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
This is a dummy function only for the purpose of adding the autologging_integration annotation.
We cannot add the annotation directly to the autolog() function above due to the reason
mentioned in the ... |
This is a dummy function only for the purpose of adding the autologging_integration annotation.
We cannot add the annotation directly to the autolog() function above due to the reason
mentioned in the comment above. Note that this function MUST declare the same signature as the
autolog(), otherwise the... | _autolog | python | mlflow/mlflow | mlflow/ag2/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/ag2/__init__.py | Apache-2.0 |
def convert_message_to_mlflow_chat(message: Union[BaseModel, dict]) -> ChatMessage:
"""
Convert Anthropic message object into MLflow's standard format (OpenAI compatible).
Ref: https://docs.anthropic.com/en/api/messages#body-messages
Args:
message: Anthropic message object or a dictionary repr... |
Convert Anthropic message object into MLflow's standard format (OpenAI compatible).
Ref: https://docs.anthropic.com/en/api/messages#body-messages
Args:
message: Anthropic message object or a dictionary representing the message.
Returns:
ChatMessage: MLflow's standard chat message obj... | convert_message_to_mlflow_chat | python | mlflow/mlflow | mlflow/anthropic/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/anthropic/chat.py | Apache-2.0 |
def convert_tool_to_mlflow_chat_tool(tool: dict) -> ChatTool:
"""
Convert Anthropic tool definition into MLflow's standard format (OpenAI compatible).
Ref: https://docs.anthropic.com/en/docs/build-with-claude/tool-use
Args:
tool: A dictionary represents a single tool definition in the input re... |
Convert Anthropic tool definition into MLflow's standard format (OpenAI compatible).
Ref: https://docs.anthropic.com/en/docs/build-with-claude/tool-use
Args:
tool: A dictionary represents a single tool definition in the input request.
Returns:
ChatTool: MLflow's standard tool definit... | convert_tool_to_mlflow_chat_tool | python | mlflow/mlflow | mlflow/anthropic/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/anthropic/chat.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from Anthropic to MLflow.
Only synchronous calls and asynchnorous APIs are supported. Streaming is not recorded.
Args:
log_traces: If ``True``, ... |
Enables (or disables) and configures autologging from Anthropic to MLflow.
Only synchronous calls and asynchnorous APIs are supported. Streaming is not recorded.
Args:
log_traces: If ``True``, traces are logged for Anthropic models.
If ``False``, no traces are collected during inferenc... | autolog | python | mlflow/mlflow | mlflow/anthropic/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/anthropic/__init__.py | Apache-2.0 |
def download_artifacts(
artifact_uri: Optional[str] = None,
run_id: Optional[str] = None,
artifact_path: Optional[str] = None,
dst_path: Optional[str] = None,
tracking_uri: Optional[str] = None,
) -> str:
"""Download an artifact file or directory to a local directory.
Args:
artifact... | Download an artifact file or directory to a local directory.
Args:
artifact_uri: URI pointing to the artifacts. Supported formats include:
* ``runs:/<run_id>/<artifact_path>``
Example: ``runs:/500cf58bee2b40a4a82861cc31a617b1/my_model.pkl``
* ``models:/<model_name>/<... | download_artifacts | python | mlflow/mlflow | mlflow/artifacts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/artifacts/__init__.py | Apache-2.0 |
def list_artifacts(
artifact_uri: Optional[str] = None,
run_id: Optional[str] = None,
artifact_path: Optional[str] = None,
tracking_uri: Optional[str] = None,
) -> list[FileInfo]:
"""List artifacts at the specified URI.
Args:
artifact_uri: URI pointing to the artifacts, such as
... | List artifacts at the specified URI.
Args:
artifact_uri: URI pointing to the artifacts, such as
``"runs:/500cf58bee2b40a4a82861cc31a617b1/my_model.pkl"``,
``"models:/my_model/Production"``, or ``"s3://my_bucket/my/file.txt"``.
Exactly one of ``artifact_uri`` or ``run_id`... | list_artifacts | python | mlflow/mlflow | mlflow/artifacts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/artifacts/__init__.py | Apache-2.0 |
def load_text(artifact_uri: str) -> str:
"""Loads the artifact contents as a string.
Args:
artifact_uri: Artifact location.
Returns:
The contents of the artifact as a string.
.. code-block:: python
:caption: Example
import mlflow
with mlflow.start_run() as ru... | Loads the artifact contents as a string.
Args:
artifact_uri: Artifact location.
Returns:
The contents of the artifact as a string.
.. code-block:: python
:caption: Example
import mlflow
with mlflow.start_run() as run:
artifact_uri = run.info.artifact_... | load_text | python | mlflow/mlflow | mlflow/artifacts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/artifacts/__init__.py | Apache-2.0 |
def load_dict(artifact_uri: str) -> dict:
"""Loads the artifact contents as a dictionary.
Args:
artifact_uri: artifact location.
Returns:
A dictionary.
.. code-block:: python
:caption: Example
import mlflow
with mlflow.start_run() as run:
artifact_uri = r... | Loads the artifact contents as a dictionary.
Args:
artifact_uri: artifact location.
Returns:
A dictionary.
.. code-block:: python
:caption: Example
import mlflow
with mlflow.start_run() as run:
artifact_uri = run.info.artifact_uri
mlflow.log_dict({"... | load_dict | python | mlflow/mlflow | mlflow/artifacts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/artifacts/__init__.py | Apache-2.0 |
def load_image(artifact_uri: str):
"""Loads artifact contents as a ``PIL.Image.Image`` object
Args:
artifact_uri: Artifact location.
Returns:
A PIL.Image object.
.. code-block:: python
:caption: Example
import mlflow
from PIL import Image
with mlflow.... | Loads artifact contents as a ``PIL.Image.Image`` object
Args:
artifact_uri: Artifact location.
Returns:
A PIL.Image object.
.. code-block:: python
:caption: Example
import mlflow
from PIL import Image
with mlflow.start_run() as run:
image = Im... | load_image | python | mlflow/mlflow | mlflow/artifacts/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/artifacts/__init__.py | Apache-2.0 |
def log_tools(span: Span, tools: list[Union["BaseTool", "ToolSchema"]]):
"""
Log Autogen tool definitions into the passed in span.
Ref: https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/components/tools.html
Args:
span: The span to log the tools into.
tools: A list ... |
Log Autogen tool definitions into the passed in span.
Ref: https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/components/tools.html
Args:
span: The span to log the tools into.
tools: A list of Autogen BaseTool.
| log_tools | python | mlflow/mlflow | mlflow/autogen/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/autogen/chat.py | Apache-2.0 |
def convert_assistant_message_to_chat_message(
content: Union[str, list["FunctionCall"]],
) -> Optional[ChatMessage]:
"""
Convert an Autogen assistant message to a ChatMessage.
The content of assistant message is a str or a list of tool calls.
Args:
content: The Autogen assistant message co... |
Convert an Autogen assistant message to a ChatMessage.
The content of assistant message is a str or a list of tool calls.
Args:
content: The Autogen assistant message content to convert.
Returns:
A ChatMessage object
| convert_assistant_message_to_chat_message | python | mlflow/mlflow | mlflow/autogen/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/autogen/chat.py | Apache-2.0 |
def log_chat_messages(span: Span, messages: list["LLMMessage"]):
"""
Log Autogen chat messages into the passed in span.
Args:
span: The span to log the tools into.
messages: A list of Autogen chat messages.
"""
from autogen_core.models import (
AssistantMessage,
Func... |
Log Autogen chat messages into the passed in span.
Args:
span: The span to log the tools into.
messages: A list of Autogen chat messages.
| log_chat_messages | python | mlflow/mlflow | mlflow/autogen/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/autogen/chat.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging for AutoGen flavor.
Due to its patch design, this method needs to be called after importing AutoGen classes.
Args:
log_traces: If ``True``, trac... |
Enables (or disables) and configures autologging for AutoGen flavor.
Due to its patch design, this method needs to be called after importing AutoGen classes.
Args:
log_traces: If ``True``, traces are logged for AutoGen models.
If ``False``, no traces are collected during inference. Def... | autolog | python | mlflow/mlflow | mlflow/autogen/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/autogen/__init__.py | Apache-2.0 |
def put_adls_file_creation(sas_url, headers):
"""Performs an ADLS Azure file create `Put` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create)
Args:
sas_url: A shared access signature URL referring to the Azure ADLS server
to which the fi... | Performs an ADLS Azure file create `Put` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create)
Args:
sas_url: A shared access signature URL referring to the Azure ADLS server
to which the file creation command should be issued.
headers... | put_adls_file_creation | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def patch_adls_file_upload(sas_url, local_file, start_byte, size, position, headers, is_single):
"""
Performs an ADLS Azure file create `Patch` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update)
Args:
sas_url: A shared access signature URL refe... |
Performs an ADLS Azure file create `Patch` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update)
Args:
sas_url: A shared access signature URL referring to the Azure ADLS server
to which the file update command should be issued.
lo... | patch_adls_file_upload | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def patch_adls_flush(sas_url, position, headers):
"""Performs an ADLS Azure file flush `Patch` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update)
Args:
sas_url: A shared access signature URL referring to the Azure ADLS server
to which t... | Performs an ADLS Azure file flush `Patch` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update)
Args:
sas_url: A shared access signature URL referring to the Azure ADLS server
to which the file update command should be issued.
position... | patch_adls_flush | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def put_block(sas_url, block_id, data, headers):
"""
Performs an Azure `Put Block` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/put-block)
Args:
sas_url: A shared access signature URL referring to the Azure Block Blob
to which the specified data should be sta... |
Performs an Azure `Put Block` operation
(https://docs.microsoft.com/en-us/rest/api/storageservices/put-block)
Args:
sas_url: A shared access signature URL referring to the Azure Block Blob
to which the specified data should be staged.
block_id: A base64-encoded string identifyi... | put_block | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def _is_valid_put_block_list_header(header_name):
"""
Returns:
True if the specified header name is a valid header for the Put Block List operation,
False otherwise. For a list of valid headers, see https://docs.microsoft.com/en-us/
rest/api/storageservices/put-block-list#request-headers... |
Returns:
True if the specified header name is a valid header for the Put Block List operation,
False otherwise. For a list of valid headers, see https://docs.microsoft.com/en-us/
rest/api/storageservices/put-block-list#request-headers and https://docs.microsoft.com/
en-us/rest/api/s... | _is_valid_put_block_list_header | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def _is_valid_put_block_header(header_name):
"""
Returns:
True if the specified header name is a valid header for the Put Block operation, False
otherwise. For a list of valid headers, see
https://docs.microsoft.com/en-us/rest/api/storageservices/put-block#request-headers and
htt... |
Returns:
True if the specified header name is a valid header for the Put Block operation, False
otherwise. For a list of valid headers, see
https://docs.microsoft.com/en-us/rest/api/storageservices/put-block#request-headers and
https://docs.microsoft.com/en-us/rest/api/storageservic... | _is_valid_put_block_header | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def _is_valid_adls_put_header(header_name):
"""
Returns:
True if the specified header name is a valid header for the ADLS Put operation, False
otherwise. For a list of valid headers, see
https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create
"""
... |
Returns:
True if the specified header name is a valid header for the ADLS Put operation, False
otherwise. For a list of valid headers, see
https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create
| _is_valid_adls_put_header | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def _is_valid_adls_patch_header(header_name):
"""
Returns:
True if the specified header name is a valid header for the ADLS Patch operation, False
otherwise. For a list of valid headers, see
https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update
"""... |
Returns:
True if the specified header name is a valid header for the ADLS Patch operation, False
otherwise. For a list of valid headers, see
https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update
| _is_valid_adls_patch_header | python | mlflow/mlflow | mlflow/azure/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/azure/client.py | Apache-2.0 |
def convert_message_to_mlflow_chat(message: dict) -> ChatMessage:
"""
Convert Bedrock Converse API's message object into MLflow's standard format (OpenAI compatible).
Ref: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html
Args:
message: Bedrock Converse API's mes... |
Convert Bedrock Converse API's message object into MLflow's standard format (OpenAI compatible).
Ref: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html
Args:
message: Bedrock Converse API's message object.
Returns:
ChatMessage: MLflow's standard chat me... | convert_message_to_mlflow_chat | python | mlflow/mlflow | mlflow/bedrock/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/chat.py | Apache-2.0 |
def _parse_content(content: dict) -> Optional[Union[TextContentPart, ImageContentPart]]:
"""
Parse a single content block in the Bedrock message object.
Some content types like video and document are not supported by OpenAI's spec. This
function returns None for those content types.
Ref: https://d... |
Parse a single content block in the Bedrock message object.
Some content types like video and document are not supported by OpenAI's spec. This
function returns None for those content types.
Ref: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html
| _parse_content | python | mlflow/mlflow | mlflow/bedrock/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/chat.py | Apache-2.0 |
def convert_tool_to_mlflow_chat_tool(tool: dict) -> ChatTool:
"""
Convert Bedrock tool definition into MLflow's standard format (OpenAI compatible).
Ref: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Tool.html
Args:
tool: A dictionary represents a single tool definition i... |
Convert Bedrock tool definition into MLflow's standard format (OpenAI compatible).
Ref: https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Tool.html
Args:
tool: A dictionary represents a single tool definition in the input request.
Returns:
ChatTool: MLflow's standar... | convert_tool_to_mlflow_chat_tool | python | mlflow/mlflow | mlflow/bedrock/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/chat.py | Apache-2.0 |
def _handle_event(self, span, event):
"""
Process a single event from the stream.
Refer to the following documentation for the event format:
https://boto3.amazonaws.com/v1/documentation/api/1.35.8/reference/services/bedrock-runtime/client/converse_stream.html
"""
event_n... |
Process a single event from the stream.
Refer to the following documentation for the event format:
https://boto3.amazonaws.com/v1/documentation/api/1.35.8/reference/services/bedrock-runtime/client/converse_stream.html
| _handle_event | python | mlflow/mlflow | mlflow/bedrock/stream.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/stream.py | Apache-2.0 |
def capture_exception(logging_message: str):
"""
A decorator to capture exceptions during a function execution.
"""
def decorator(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
_logger.debug(loggin... |
A decorator to capture exceptions during a function execution.
| capture_exception | python | mlflow/mlflow | mlflow/bedrock/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/utils.py | Apache-2.0 |
def skip_if_trace_disabled(func: Callable[..., Any]) -> Callable[..., Any]:
"""
A decorator to apply the function only if trace autologging is enabled.
This decorator is used to skip the test if the trace autologging is disabled.
"""
def wrapper(original, self, *args, **kwargs):
config = Au... |
A decorator to apply the function only if trace autologging is enabled.
This decorator is used to skip the test if the trace autologging is disabled.
| skip_if_trace_disabled | python | mlflow/mlflow | mlflow/bedrock/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/utils.py | Apache-2.0 |
def patched_create_client(original, self, *args, **kwargs):
"""
Patched version of the boto3 ClientCreator.create_client method that returns
a patched client class.
"""
if kwargs.get("service_name") != _BEDROCK_RUNTIME_SERVICE_NAME:
return original(self, *args, **kwargs)
client = origin... |
Patched version of the boto3 ClientCreator.create_client method that returns
a patched client class.
| patched_create_client | python | mlflow/mlflow | mlflow/bedrock/_autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/_autolog.py | Apache-2.0 |
def patch_bedrock_runtime_client(client_class: type[BaseClient]):
"""
Patch the BedrockRuntime client to log traces and models.
"""
# The most basic model invocation API
safe_patch(FLAVOR_NAME, client_class, "invoke_model", _patched_invoke_model)
safe_patch(
FLAVOR_NAME,
client_c... |
Patch the BedrockRuntime client to log traces and models.
| patch_bedrock_runtime_client | python | mlflow/mlflow | mlflow/bedrock/_autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/_autolog.py | Apache-2.0 |
def _buffer_stream(raw_stream: StreamingBody) -> StreamingBody:
"""
Create a buffered stream from the raw byte stream.
The boto3's invoke_model() API returns the LLM response as a byte stream.
We need to read the stream data to set the span outputs, however, the stream
can only be read once and not... |
Create a buffered stream from the raw byte stream.
The boto3's invoke_model() API returns the LLM response as a byte stream.
We need to read the stream data to set the span outputs, however, the stream
can only be read once and not seekable (https://github.com/boto/boto3/issues/564).
To work aroun... | _buffer_stream | python | mlflow/mlflow | mlflow/bedrock/_autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/_autolog.py | Apache-2.0 |
def _set_chat_messages_attributes(span, messages: list[dict], response: Optional[dict]):
"""
Extract standard chat span attributes for the Bedrock Converse API call.
NB: We only support standard attribute extraction for the Converse API, because
the InvokeModel API exposes the raw API spec from each LL... |
Extract standard chat span attributes for the Bedrock Converse API call.
NB: We only support standard attribute extraction for the Converse API, because
the InvokeModel API exposes the raw API spec from each LLM provider, hence
maintaining the compatibility for all providers is significantly cumbersom... | _set_chat_messages_attributes | python | mlflow/mlflow | mlflow/bedrock/_autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/_autolog.py | Apache-2.0 |
def _set_tool_attributes(span, kwargs):
"""Extract tool attributes for the Bedrock Converse API call."""
if tool_config := kwargs.get("toolConfig"):
try:
tools = [convert_tool_to_mlflow_chat_tool(tool) for tool in tool_config["tools"]]
set_span_chat_tools(span, tools)
exc... | Extract tool attributes for the Bedrock Converse API call. | _set_tool_attributes | python | mlflow/mlflow | mlflow/bedrock/_autolog.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/_autolog.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from Amazon Bedrock to MLflow.
Only synchronous calls are supported. Asynchnorous APIs and streaming are not recorded.
Args:
log_traces: If ``Tr... |
Enables (or disables) and configures autologging from Amazon Bedrock to MLflow.
Only synchronous calls are supported. Asynchnorous APIs and streaming are not recorded.
Args:
log_traces: If ``True``, traces are logged for Bedrock models.
If ``False``, no traces are collected during infe... | autolog | python | mlflow/mlflow | mlflow/bedrock/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/bedrock/__init__.py | Apache-2.0 |
def save_model(
cb_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,
metadata=None,
**kwargs,
):
"""Save a CatBoost model to a pat... | Save a CatBoost model to a path on the local file system.
Args:
cb_model: CatBoost model (an instance of `CatBoost`_, `CatBoostClassifier`_,
`CatBoostRanker`_, or `CatBoostRegressor`_) to be saved.
path: Local path where the model is to be saved.
conda_env: {{ conda_env }}
... | save_model | python | mlflow/mlflow | mlflow/catboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/catboost/__init__.py | Apache-2.0 |
def log_model(
cb_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,
ext... | Log a CatBoost model as an MLflow artifact for the current run.
Args:
cb_model: CatBoost model (an instance of `CatBoost`_, `CatBoostClassifier`_,
`CatBoostRanker`_, or `CatBoostRegressor`_) to be saved.
artifact_path: Deprecated. Use `name` instead.
conda_env: {{ conda_env }}
... | log_model | python | mlflow/mlflow | mlflow/catboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/catboost/__init__.py | Apache-2.0 |
def _load_pyfunc(path):
"""Load PyFunc implementation. Called by ``pyfunc.load_model``.
Args:
path: Local filesystem path to the MLflow Model with the ``catboost`` flavor.
"""
flavor_conf = _get_flavor_configuration(
model_path=os.path.dirname(path), flavor_name=FLAVOR_NAME
)
re... | Load PyFunc implementation. Called by ``pyfunc.load_model``.
Args:
path: Local filesystem path to the MLflow Model with the ``catboost`` flavor.
| _load_pyfunc | python | mlflow/mlflow | mlflow/catboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/catboost/__init__.py | Apache-2.0 |
def load_model(model_uri, dst_path=None):
"""Load a CatBoost 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 a CatBoost 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/catboost/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/catboost/__init__.py | Apache-2.0 |
def set_span_chat_attributes(span: LiveSpan, messages: list[dict[str, Any]], output: Any):
"""
This method logs chat messages to a span when LLM class is called. Since the CrewAI library
includes tool definition in the text content, mlflow.chat.tools attribute is not recorded.
Args:
span: A spa... |
This method logs chat messages to a span when LLM class is called. Since the CrewAI library
includes tool definition in the text content, mlflow.chat.tools attribute is not recorded.
Args:
span: A span object to record the chat messages.
messages: Input messages for the LLM call.
o... | set_span_chat_attributes | python | mlflow/mlflow | mlflow/crewai/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/crewai/chat.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from CrewAI to MLflow.
Note that asynchnorous APIs and Tool calling are not recorded now.
Args:
log_traces: If ``True``, traces are logged for C... |
Enables (or disables) and configures autologging from CrewAI to MLflow.
Note that asynchnorous APIs and Tool calling are not recorded now.
Args:
log_traces: If ``True``, traces are logged for CrewAI agents.
If ``False``, no traces are collected during inference. Default to ``True``.
... | autolog | python | mlflow/mlflow | mlflow/crewai/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/crewai/__init__.py | Apache-2.0 |
def to_dict(self) -> dict[Any, Any]:
"""
Returns:
A JSON-compatible dictionary representation of the {dataset_source_name}.
"""
return {
"uri": self.uri,
} |
Returns:
A JSON-compatible dictionary representation of the {dataset_source_name}.
| to_dict | python | mlflow/mlflow | mlflow/data/artifact_dataset_sources.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/artifact_dataset_sources.py | Apache-2.0 |
def __init__(
self, source: DatasetSource, name: Optional[str] = None, digest: Optional[str] = None
):
"""
Base constructor for a dataset. All subclasses must call this constructor.
"""
self._name = name
self._source = source
# Note: Subclasses should call sup... |
Base constructor for a dataset. All subclasses must call this constructor.
| __init__ | python | mlflow/mlflow | mlflow/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset.py | Apache-2.0 |
def _compute_digest(self) -> str:
"""Computes a digest for the dataset. Called if the user doesn't supply
a digest when constructing the dataset.
Returns:
A string digest for the dataset. We recommend a maximum digest length
of 10 characters with an ideal length of 8 cha... | Computes a digest for the dataset. Called if the user doesn't supply
a digest when constructing the dataset.
Returns:
A string digest for the dataset. We recommend a maximum digest length
of 10 characters with an ideal length of 8 characters.
| _compute_digest | python | mlflow/mlflow | mlflow/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset.py | Apache-2.0 |
def to_dict(self) -> dict[str, str]:
"""Create config dictionary for the dataset.
Subclasses should override this method to provide additional fields in the config dict,
e.g., schema, profile, etc.
Returns a string dictionary containing the following fields: name, digest, source, sourc... | Create config dictionary for the dataset.
Subclasses should override this method to provide additional fields in the config dict,
e.g., schema, profile, etc.
Returns a string dictionary containing the following fields: name, digest, source, source
type.
| to_dict | python | mlflow/mlflow | mlflow/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset.py | Apache-2.0 |
def name(self) -> str:
"""
The name of the dataset, e.g. ``"iris_data"``, ``"myschema.mycatalog.mytable@v1"``, etc.
"""
if self._name is not None:
return self._name
else:
return "dataset" |
The name of the dataset, e.g. ``"iris_data"``, ``"myschema.mycatalog.mytable@v1"``, etc.
| name | python | mlflow/mlflow | mlflow/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset.py | Apache-2.0 |
def profile(self) -> Optional[Any]:
"""
Optional summary statistics for the dataset, such as the number of rows in a table, the
mean / median / std of each table column, etc.
""" |
Optional summary statistics for the dataset, such as the number of rows in a table, the
mean / median / std of each table column, etc.
| profile | python | mlflow/mlflow | mlflow/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset.py | Apache-2.0 |
def schema(self) -> Optional[Any]:
"""
Optional dataset schema, such as an instance of :py:class:`mlflow.types.Schema` representing
the features and targets of the dataset.
""" |
Optional dataset schema, such as an instance of :py:class:`mlflow.types.Schema` representing
the features and targets of the dataset.
| schema | python | mlflow/mlflow | mlflow/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset.py | Apache-2.0 |
def _to_mlflow_entity(self) -> DatasetEntity:
"""
Returns:
A `mlflow.entities.Dataset` instance representing the dataset.
"""
dataset_dict = self.to_dict()
return DatasetEntity(
name=dataset_dict["name"],
digest=dataset_dict["digest"],
... |
Returns:
A `mlflow.entities.Dataset` instance representing the dataset.
| _to_mlflow_entity | python | mlflow/mlflow | mlflow/data/dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset.py | Apache-2.0 |
def register_constructor(
self, constructor_fn: Callable, constructor_name: Optional[str] = None
) -> str:
"""Registers a dataset constructor.
Args:
constructor_fn: A function that accepts at least the following
inputs and returns an instance of a subclass of
... | Registers a dataset constructor.
Args:
constructor_fn: A function that accepts at least the following
inputs and returns an instance of a subclass of
:py:class:`mlflow.data.dataset.Dataset`:
- name: Optional. A string dataset name
- d... | register_constructor | python | mlflow/mlflow | mlflow/data/dataset_registry.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_registry.py | Apache-2.0 |
def register_entrypoints(self):
"""
Registers dataset sources defined as Python entrypoints. For reference, see
https://mlflow.org/docs/latest/plugins.html#defining-a-plugin.
"""
for entrypoint in get_entry_points("mlflow.dataset_constructor"):
try:
se... |
Registers dataset sources defined as Python entrypoints. For reference, see
https://mlflow.org/docs/latest/plugins.html#defining-a-plugin.
| register_entrypoints | python | mlflow/mlflow | mlflow/data/dataset_registry.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_registry.py | Apache-2.0 |
def register_constructor(constructor_fn: Callable, constructor_name: Optional[str] = None) -> str:
"""Registers a dataset constructor.
Args:
constructor_fn: A function that accepts at least the following
inputs and returns an instance of a subclass of
:py:class:`mlflow.data.data... | Registers a dataset constructor.
Args:
constructor_fn: A function that accepts at least the following
inputs and returns an instance of a subclass of
:py:class:`mlflow.data.dataset.Dataset`:
- name: Optional. A string dataset name
- digest: Optional. A strin... | register_constructor | python | mlflow/mlflow | mlflow/data/dataset_registry.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_registry.py | Apache-2.0 |
def _get_source_type() -> str:
"""Obtains a string representing the source type of the dataset.
Returns:
A string representing the source type of the dataset, e.g. "s3", "delta_table", ...
""" | Obtains a string representing the source type of the dataset.
Returns:
A string representing the source type of the dataset, e.g. "s3", "delta_table", ...
| _get_source_type | python | mlflow/mlflow | mlflow/data/dataset_source.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source.py | Apache-2.0 |
def load(self) -> Any:
"""
Loads files / objects referred to by the DatasetSource. For example, depending on the type
of :py:class:`DatasetSource <mlflow.data.dataset_source.DatasetSource>`, this may download
source CSV files from S3 to the local filesystem, load a source Delta Table as ... |
Loads files / objects referred to by the DatasetSource. For example, depending on the type
of :py:class:`DatasetSource <mlflow.data.dataset_source.DatasetSource>`, this may download
source CSV files from S3 to the local filesystem, load a source Delta Table as a Spark
DataFrame, etc.
... | load | python | mlflow/mlflow | mlflow/data/dataset_source.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source.py | Apache-2.0 |
def _can_resolve(raw_source: Any) -> bool:
"""Determines whether this type of DatasetSource can be resolved from a specified raw source
object. For example, an S3DatasetSource can be resolved from an S3 URI like
"s3://mybucket/path/to/iris/data" but not from an Azure Blob Storage URI like
... | Determines whether this type of DatasetSource can be resolved from a specified raw source
object. For example, an S3DatasetSource can be resolved from an S3 URI like
"s3://mybucket/path/to/iris/data" but not from an Azure Blob Storage URI like
"wasbs:/account@host.blob.core.windows.net".
... | _can_resolve | python | mlflow/mlflow | mlflow/data/dataset_source.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source.py | Apache-2.0 |
def _resolve(cls, raw_source: Any) -> "DatasetSource":
"""Constructs an instance of the DatasetSource from a raw source object, such as a
string URI like "s3://mybucket/path/to/iris/data" or a delta table identifier
like "my.delta.table@2".
Args:
raw_source: The raw source, ... | Constructs an instance of the DatasetSource from a raw source object, such as a
string URI like "s3://mybucket/path/to/iris/data" or a delta table identifier
like "my.delta.table@2".
Args:
raw_source: The raw source, e.g. a string like "s3://mybucket/path/to/iris/data".
Ret... | _resolve | python | mlflow/mlflow | mlflow/data/dataset_source.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source.py | Apache-2.0 |
def to_dict(self) -> dict[str, Any]:
"""Obtains a JSON-compatible dictionary representation of the DatasetSource.
Returns:
A JSON-compatible dictionary representation of the DatasetSource.
""" | Obtains a JSON-compatible dictionary representation of the DatasetSource.
Returns:
A JSON-compatible dictionary representation of the DatasetSource.
| to_dict | python | mlflow/mlflow | mlflow/data/dataset_source.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source.py | Apache-2.0 |
def from_dict(cls, source_dict: dict[Any, Any]) -> "DatasetSource":
"""Constructs an instance of the DatasetSource from a dictionary representation.
Args:
source_dict: A dictionary representation of the DatasetSource.
Returns:
A DatasetSource instance.
""" | Constructs an instance of the DatasetSource from a dictionary representation.
Args:
source_dict: A dictionary representation of the DatasetSource.
Returns:
A DatasetSource instance.
| from_dict | python | mlflow/mlflow | mlflow/data/dataset_source.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source.py | Apache-2.0 |
def resolve(
self, raw_source: Any, candidate_sources: Optional[list[DatasetSource]] = None
) -> DatasetSource:
"""Resolves a raw source object, such as a string URI, to a DatasetSource for use with
MLflow Tracking.
Args:
raw_source: The raw source, e.g. a string like "s... | Resolves a raw source object, such as a string URI, to a DatasetSource for use with
MLflow Tracking.
Args:
raw_source: The raw source, e.g. a string like "s3://mybucket/path/to/iris/data" or a
HuggingFace :py:class:`datasets.Dataset` object.
candidate_sources: A ... | resolve | python | mlflow/mlflow | mlflow/data/dataset_source_registry.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source_registry.py | Apache-2.0 |
def get_source_from_json(self, source_json: str, source_type: str) -> DatasetSource:
"""Parses and returns a DatasetSource object from its JSON representation.
Args:
source_json: The JSON representation of the DatasetSource.
source_type: The string type of the DatasetSource, whi... | Parses and returns a DatasetSource object from its JSON representation.
Args:
source_json: The JSON representation of the DatasetSource.
source_type: The string type of the DatasetSource, which indicates how to parse the
source JSON.
| get_source_from_json | python | mlflow/mlflow | mlflow/data/dataset_source_registry.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source_registry.py | Apache-2.0 |
def resolve_dataset_source(
raw_source: Any, candidate_sources: Optional[list[DatasetSource]] = None
) -> DatasetSource:
"""Resolves a raw source object, such as a string URI, to a DatasetSource for use with
MLflow Tracking.
Args:
raw_source: The raw source, e.g. a string like "s3://mybucket/pa... | Resolves a raw source object, such as a string URI, to a DatasetSource for use with
MLflow Tracking.
Args:
raw_source: The raw source, e.g. a string like "s3://mybucket/path/to/iris/data" or a
HuggingFace :py:class:`datasets.Dataset` object.
candidate_sources: A list of DatasetSourc... | resolve_dataset_source | python | mlflow/mlflow | mlflow/data/dataset_source_registry.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source_registry.py | Apache-2.0 |
def get_dataset_source_from_json(source_json: str, source_type: str) -> DatasetSource:
"""Parses and returns a DatasetSource object from its JSON representation.
Args:
source_json: The JSON representation of the DatasetSource.
source_type: The string type of the DatasetSource, which indicates h... | Parses and returns a DatasetSource object from its JSON representation.
Args:
source_json: The JSON representation of the DatasetSource.
source_type: The string type of the DatasetSource, which indicates how to parse the
source JSON.
| get_dataset_source_from_json | python | mlflow/mlflow | mlflow/data/dataset_source_registry.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/dataset_source_registry.py | Apache-2.0 |
def load(self, **kwargs):
"""
Loads the dataset source as a Delta Dataset Source.
Returns:
An instance of ``pyspark.sql.DataFrame``.
"""
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
spark_read_op = spark.read.forma... |
Loads the dataset source as a Delta Dataset Source.
Returns:
An instance of ``pyspark.sql.DataFrame``.
| load | python | mlflow/mlflow | mlflow/data/delta_dataset_source.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/delta_dataset_source.py | Apache-2.0 |
def compute_pandas_digest(df) -> str:
"""Computes a digest for the given Pandas DataFrame.
Args:
df: A Pandas DataFrame.
Returns:
A string digest.
"""
import numpy as np
import pandas as pd
# trim to max rows
trimmed_df = df.head(MAX_ROWS)
# keep string and number... | Computes a digest for the given Pandas DataFrame.
Args:
df: A Pandas DataFrame.
Returns:
A string digest.
| compute_pandas_digest | python | mlflow/mlflow | mlflow/data/digest_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/digest_utils.py | Apache-2.0 |
def compute_numpy_digest(features, targets=None) -> str:
"""Computes a digest for the given numpy array.
Args:
features: A numpy array containing dataset features.
targets: A numpy array containing dataset targets. Optional.
Returns:
A string digest.
"""
import numpy as np
... | Computes a digest for the given numpy array.
Args:
features: A numpy array containing dataset features.
targets: A numpy array containing dataset targets. Optional.
Returns:
A string digest.
| compute_numpy_digest | python | mlflow/mlflow | mlflow/data/digest_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/digest_utils.py | Apache-2.0 |
def get_normalized_md5_digest(elements: list[Any]) -> str:
"""Computes a normalized digest for a list of hashable elements.
Args:
elements: A list of hashable elements for inclusion in the md5 digest.
Returns:
An 8-character, truncated md5 digest.
"""
if not elements:
rais... | Computes a normalized digest for a list of hashable elements.
Args:
elements: A list of hashable elements for inclusion in the md5 digest.
Returns:
An 8-character, truncated md5 digest.
| get_normalized_md5_digest | python | mlflow/mlflow | mlflow/data/digest_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/digest_utils.py | Apache-2.0 |
def _hash_array_like_obj_as_bytes(data):
"""
Helper method to convert pandas dataframe/numpy array/list into bytes for
MD5 calculation purpose.
"""
if isinstance(data, pd.DataFrame):
# add checking `'pyspark' in sys.modules` to avoid importing pyspark when user
# run code not related... |
Helper method to convert pandas dataframe/numpy array/list into bytes for
MD5 calculation purpose.
| _hash_array_like_obj_as_bytes | python | mlflow/mlflow | mlflow/data/evaluation_dataset.py | https://github.com/mlflow/mlflow/blob/master/mlflow/data/evaluation_dataset.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.