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 rougeL() -> EvaluationMetric:
"""
This function will create a metric for evaluating `rougeL`_.
The score ranges from 0 to 1, where a higher score indicates higher similarity.
`rougeL`_ uses unigram based scoring to calculate similarity.
Aggregations calculated for this metric:
- mean
... |
This function will create a metric for evaluating `rougeL`_.
The score ranges from 0 to 1, where a higher score indicates higher similarity.
`rougeL`_ uses unigram based scoring to calculate similarity.
Aggregations calculated for this metric:
- mean
.. _rougeL: https://huggingface.co/sp... | rougeL | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def rougeLsum() -> EvaluationMetric:
"""
This function will create a metric for evaluating `rougeLsum`_.
The score ranges from 0 to 1, where a higher score indicates higher similarity.
`rougeLsum`_ uses longest common subsequence based scoring to calculate similarity.
Aggregations calculated for t... |
This function will create a metric for evaluating `rougeLsum`_.
The score ranges from 0 to 1, where a higher score indicates higher similarity.
`rougeLsum`_ uses longest common subsequence based scoring to calculate similarity.
Aggregations calculated for this metric:
- mean
.. _rougeLsu... | rougeLsum | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def precision_at_k(k) -> EvaluationMetric:
"""
This function will create a metric for calculating ``precision_at_k`` for retriever models.
This metric computes a score between 0 and 1 for each row representing the precision of the
retriever model at the given ``k`` value. If no relevant documents are r... |
This function will create a metric for calculating ``precision_at_k`` for retriever models.
This metric computes a score between 0 and 1 for each row representing the precision of the
retriever model at the given ``k`` value. If no relevant documents are retrieved, the score is
0, indicating that no r... | precision_at_k | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def recall_at_k(k) -> EvaluationMetric:
"""
This function will create a metric for calculating ``recall_at_k`` for retriever models.
This metric computes a score between 0 and 1 for each row representing the recall ability of
the retriever model at the given ``k`` value. If no ground truth doc IDs are ... |
This function will create a metric for calculating ``recall_at_k`` for retriever models.
This metric computes a score between 0 and 1 for each row representing the recall ability of
the retriever model at the given ``k`` value. If no ground truth doc IDs are provided and no
documents are retrieved, th... | recall_at_k | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def ndcg_at_k(k) -> EvaluationMetric:
"""
This function will create a metric for evaluating `NDCG@k`_ for retriever models.
NDCG score is capable of handling non-binary notions of relevance. However, for simplicity,
we use binary relevance here. The relevance score for documents in the ground truth is ... |
This function will create a metric for evaluating `NDCG@k`_ for retriever models.
NDCG score is capable of handling non-binary notions of relevance. However, for simplicity,
we use binary relevance here. The relevance score for documents in the ground truth is 1,
and the relevance score for documents ... | ndcg_at_k | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def mae() -> EvaluationMetric:
"""
This function will create a metric for evaluating `mae`_.
This metric computes an aggregate score for the mean absolute error for regression.
.. _mae: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html
"""
return make_m... |
This function will create a metric for evaluating `mae`_.
This metric computes an aggregate score for the mean absolute error for regression.
.. _mae: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html
| mae | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def mse() -> EvaluationMetric:
"""
This function will create a metric for evaluating `mse`_.
This metric computes an aggregate score for the mean squared error for regression.
.. _mse: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
"""
return make_met... |
This function will create a metric for evaluating `mse`_.
This metric computes an aggregate score for the mean squared error for regression.
.. _mse: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
| mse | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def rmse() -> EvaluationMetric:
"""
This function will create a metric for evaluating the square root of `mse`_.
This metric computes an aggregate score for the root mean absolute error for regression.
.. _mse: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
... |
This function will create a metric for evaluating the square root of `mse`_.
This metric computes an aggregate score for the root mean absolute error for regression.
.. _mse: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
| rmse | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def r2_score() -> EvaluationMetric:
"""
This function will create a metric for evaluating `r2_score`_.
This metric computes an aggregate score for the coefficient of determination. R2 ranges from
negative infinity to 1, and measures the percentage of variance explained by the predictor
variables in... |
This function will create a metric for evaluating `r2_score`_.
This metric computes an aggregate score for the coefficient of determination. R2 ranges from
negative infinity to 1, and measures the percentage of variance explained by the predictor
variables in a regression.
.. _r2_score: https://s... | r2_score | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def max_error() -> EvaluationMetric:
"""
This function will create a metric for evaluating `max_error`_.
This metric computes an aggregate score for the maximum residual error for regression.
.. _max_error: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.max_error.html
"""
re... |
This function will create a metric for evaluating `max_error`_.
This metric computes an aggregate score for the maximum residual error for regression.
.. _max_error: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.max_error.html
| max_error | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def mape() -> EvaluationMetric:
"""
This function will create a metric for evaluating `mape`_.
This metric computes an aggregate score for the mean absolute percentage error for regression.
.. _mape: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_percentage_error.html
... |
This function will create a metric for evaluating `mape`_.
This metric computes an aggregate score for the mean absolute percentage error for regression.
.. _mape: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_percentage_error.html
| mape | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def bleu() -> EvaluationMetric:
"""
This function will create a metric for evaluating `bleu`_.
The BLEU scores range from 0 to 1, with higher scores indicating greater similarity to
reference texts. BLEU considers n-gram precision and brevity penalty. While adding more
references can boost the scor... |
This function will create a metric for evaluating `bleu`_.
The BLEU scores range from 0 to 1, with higher scores indicating greater similarity to
reference texts. BLEU considers n-gram precision and brevity penalty. While adding more
references can boost the score, perfect scores are rare and not esse... | bleu | python | mlflow/mlflow | mlflow/metrics/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py | Apache-2.0 |
def make_genai_metric_from_prompt(
name: str,
judge_prompt: Optional[str] = None,
model: Optional[str] = _get_default_model(),
parameters: Optional[dict[str, Any]] = None,
aggregations: Optional[list[str]] = None,
greater_is_better: bool = True,
max_workers: int = 10,
metric_metadata: Op... |
Create a genai metric used to evaluate LLM using LLM as a judge in MLflow. This produces
a metric using only the supplied judge prompt without any pre-written system prompt.
This can be useful for use cases that are not covered by the full grading prompt in any
``EvaluationModel`` version.
Args:
... | make_genai_metric_from_prompt | python | mlflow/mlflow | mlflow/metrics/genai/genai_metric.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/genai_metric.py | Apache-2.0 |
def eval_fn(
*args,
**kwargs,
) -> MetricValue:
"""
This is the function that is called when the metric is evaluated.
"""
if missing_variables := allowed_variables - set(kwargs.keys()):
raise MlflowException(
message=f"Missing variable inpu... |
This is the function that is called when the metric is evaluated.
| eval_fn | python | mlflow/mlflow | mlflow/metrics/genai/genai_metric.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/genai_metric.py | Apache-2.0 |
def make_genai_metric(
name: str,
definition: str,
grading_prompt: str,
examples: Optional[list[EvaluationExample]] = None,
version: Optional[str] = _get_latest_metric_version(),
model: Optional[str] = _get_default_model(),
grading_context_columns: Optional[Union[str, list[str]]] = None,
... |
Create a genai metric used to evaluate LLM using LLM as a judge in MLflow. The full grading
prompt is stored in the metric_details field of the ``EvaluationMetric`` object.
Args:
name: Name of the metric.
definition: Definition of the metric.
grading_prompt: Grading criteria of the... | make_genai_metric | python | mlflow/mlflow | mlflow/metrics/genai/genai_metric.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/genai_metric.py | Apache-2.0 |
def retrieve_custom_metrics(
run_id: str,
name: Optional[str] = None,
version: Optional[str] = None,
) -> list[EvaluationMetric]:
"""
Retrieve the custom metrics created by users through `make_genai_metric()` or
`make_genai_metric_from_prompt()` that are associated with a particular evaluation r... |
Retrieve the custom metrics created by users through `make_genai_metric()` or
`make_genai_metric_from_prompt()` that are associated with a particular evaluation run.
Args:
run_id: The unique identifier for the run.
name: (Optional) The name of the custom metric to retrieve.
If ... | retrieve_custom_metrics | python | mlflow/mlflow | mlflow/metrics/genai/genai_metric.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/genai_metric.py | Apache-2.0 |
def answer_similarity(
model: Optional[str] = None,
metric_version: Optional[str] = None,
examples: Optional[list[EvaluationExample]] = None,
metric_metadata: Optional[dict[str, Any]] = None,
parameters: Optional[dict[str, Any]] = None,
extra_headers: Optional[dict[str, str]] = None,
proxy_u... |
This function will create a genai metric used to evaluate the answer similarity of an LLM
using the model provided. Answer similarity will be assessed by the semantic similarity of the
output to the ``ground_truth``, which should be specified in the ``targets`` column. High
scores mean that your model ... | answer_similarity | python | mlflow/mlflow | mlflow/metrics/genai/metric_definitions.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/metric_definitions.py | Apache-2.0 |
def answer_correctness(
model: Optional[str] = None,
metric_version: Optional[str] = None,
examples: Optional[list[EvaluationExample]] = None,
metric_metadata: Optional[dict[str, Any]] = None,
parameters: Optional[dict[str, Any]] = None,
extra_headers: Optional[dict[str, str]] = None,
proxy_... |
This function will create a genai metric used to evaluate the answer correctness of an LLM
using the model provided. Answer correctness will be assessed by the accuracy of the provided
output based on the ``ground_truth``, which should be specified in the ``targets`` column.
High scores mean that your ... | answer_correctness | python | mlflow/mlflow | mlflow/metrics/genai/metric_definitions.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/metric_definitions.py | Apache-2.0 |
def faithfulness(
model: Optional[str] = None,
metric_version: Optional[str] = _get_latest_metric_version(),
examples: Optional[list[EvaluationExample]] = None,
metric_metadata: Optional[dict[str, Any]] = None,
parameters: Optional[dict[str, Any]] = None,
extra_headers: Optional[dict[str, str]] ... |
This function will create a genai metric used to evaluate the faithfullness of an LLM using the
model provided. Faithfulness will be assessed based on how factually consistent the output
is to the ``context``. High scores mean that the outputs contain information that is in
line with the context, while... | faithfulness | python | mlflow/mlflow | mlflow/metrics/genai/metric_definitions.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/metric_definitions.py | Apache-2.0 |
def answer_relevance(
model: Optional[str] = None,
metric_version: Optional[str] = _get_latest_metric_version(),
examples: Optional[list[EvaluationExample]] = None,
metric_metadata: Optional[dict[str, Any]] = None,
parameters: Optional[dict[str, Any]] = None,
extra_headers: Optional[dict[str, st... |
This function will create a genai metric used to evaluate the answer relevance of an LLM
using the model provided. Answer relevance will be assessed based on the appropriateness and
applicability of the output with respect to the input. High scores mean that your model
outputs are about the same subjec... | answer_relevance | python | mlflow/mlflow | mlflow/metrics/genai/metric_definitions.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/metric_definitions.py | Apache-2.0 |
def relevance(
model: Optional[str] = None,
metric_version: Optional[str] = None,
examples: Optional[list[EvaluationExample]] = None,
metric_metadata: Optional[dict[str, Any]] = None,
parameters: Optional[dict[str, Any]] = None,
extra_headers: Optional[dict[str, str]] = None,
proxy_url: Opti... |
This function will create a genai metric used to evaluate the evaluate the relevance of an
LLM using the model provided. Relevance will be assessed by the appropriateness, significance,
and applicability of the output with respect to the input and ``context``. High scores mean
that the model has unders... | relevance | python | mlflow/mlflow | mlflow/metrics/genai/metric_definitions.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/metric_definitions.py | Apache-2.0 |
def get_endpoint_type(endpoint_uri: str) -> Optional[str]:
"""
Get the type of the endpoint if it is MLflow deployment
endpoint. For other endpoints e.g. OpenAI, or if the
endpoint does not specify type, return None.
"""
schema, path = _parse_model_uri(endpoint_uri)
if schema != "endpoints"... |
Get the type of the endpoint if it is MLflow deployment
endpoint. For other endpoints e.g. OpenAI, or if the
endpoint does not specify type, return None.
| get_endpoint_type | python | mlflow/mlflow | mlflow/metrics/genai/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/model_utils.py | Apache-2.0 |
def score_model_on_payload(
model_uri,
payload,
eval_parameters=None,
extra_headers=None,
proxy_url=None,
endpoint_type=None,
):
"""Call the model identified by the given uri with the given string prompt."""
from mlflow.deployments import get_deploy_client
eval_parameters = eval_par... | Call the model identified by the given uri with the given string prompt. | score_model_on_payload | python | mlflow/mlflow | mlflow/metrics/genai/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/model_utils.py | Apache-2.0 |
def _call_llm_provider_api(
provider_name: str,
model: str,
input_data: str,
eval_parameters: dict[str, Any],
extra_headers: dict[str, str],
proxy_url: Optional[str] = None,
) -> str:
"""
Invoke chat endpoint of various LLM providers.
Under the hood, this function uses the MLflow Ga... |
Invoke chat endpoint of various LLM providers.
Under the hood, this function uses the MLflow Gateway to transform the input/output data
for different LLM providers.
Args:
provider_name: The provider name, e.g., "anthropic".
model: The model name, e.g., "claude-3-5-sonnet"
inpu... | _call_llm_provider_api | python | mlflow/mlflow | mlflow/metrics/genai/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/model_utils.py | Apache-2.0 |
def _get_provider_instance(provider: str, model: str) -> "BaseProvider":
"""Get the provider instance for the given provider name and the model name."""
from mlflow.gateway.config import Provider, RouteConfig
def _get_route_config(config):
return RouteConfig(
name=provider,
... | Get the provider instance for the given provider name and the model name. | _get_provider_instance | python | mlflow/mlflow | mlflow/metrics/genai/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/model_utils.py | Apache-2.0 |
def call_deployments_api(
deployment_uri: str,
input_data: Union[str, dict[str, Any]],
eval_parameters: Optional[dict[str, Any]] = None,
endpoint_type: Optional[str] = None,
):
"""Call the deployment endpoint with the given payload and parameters.
Args:
deployment_uri: The URI of the de... | Call the deployment endpoint with the given payload and parameters.
Args:
deployment_uri: The URI of the deployment endpoint.
input_data: The input string or dictionary to send to the endpoint.
- If it is a string, MLflow tries to construct the payload based on the endpoint type.
... | call_deployments_api | python | mlflow/mlflow | mlflow/metrics/genai/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/model_utils.py | Apache-2.0 |
def _construct_payload_from_str(prompt: str, endpoint_type: str) -> dict[str, Any]:
"""
Construct the payload from the input string based on the endpoint type.
If the endpoint type is not specified or unsupported one, raise an exception.
"""
if endpoint_type == "llm/v1/completions":
return {... |
Construct the payload from the input string based on the endpoint type.
If the endpoint type is not specified or unsupported one, raise an exception.
| _construct_payload_from_str | python | mlflow/mlflow | mlflow/metrics/genai/model_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/genai/model_utils.py | Apache-2.0 |
def convert_message_to_mlflow_chat(message: Union[BaseModel, dict]) -> ChatMessage:
"""
Convert Mistral AI message object into MLflow's standard format (OpenAI compatible).
Ref: https://docs.mistral.ai/api/#tag/chat/operation/chat_completion_v1_chat_completions_post
Args:
message: Mistral AI m... |
Convert Mistral AI message object into MLflow's standard format (OpenAI compatible).
Ref: https://docs.mistral.ai/api/#tag/chat/operation/chat_completion_v1_chat_completions_post
Args:
message: Mistral AI message object or a dictionary representing the message.
Returns:
ChatMessage: ... | convert_message_to_mlflow_chat | python | mlflow/mlflow | mlflow/mistral/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/mistral/chat.py | Apache-2.0 |
def convert_tool_to_mlflow_chat_tool(tool: dict) -> ChatTool:
"""
Convert Mistral AI tool definition into MLflow's standard format (OpenAI compatible).
Ref: https://docs.mistral.ai/capabilities/function_calling/#tools
Args:
tool: A dictionary represents a single tool definition in the input re... |
Convert Mistral AI tool definition into MLflow's standard format (OpenAI compatible).
Ref: https://docs.mistral.ai/capabilities/function_calling/#tools
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/mistral/chat.py | https://github.com/mlflow/mlflow/blob/master/mlflow/mistral/chat.py | Apache-2.0 |
def autolog(
log_traces: bool = True,
disable: bool = False,
silent: bool = False,
):
"""
Enables (or disables) and configures autologging from Mistral AI to MLflow.
Only synchronous calls to the Text generation API are supported.
Asynchronous APIs and streaming are not recorded.
Args:
... |
Enables (or disables) and configures autologging from Mistral AI to MLflow.
Only synchronous calls to the Text generation API are supported.
Asynchronous APIs and streaming are not recorded.
Args:
log_traces: If ``True``, traces are logged for Mistral AI models.
If ``False``, no tr... | autolog | python | mlflow/mlflow | mlflow/mistral/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/mistral/__init__.py | Apache-2.0 |
def commands():
"""
Deploy MLflow models locally.
To deploy a model associated with a run on a tracking server, set the MLFLOW_TRACKING_URI
environment variable to the URL of the desired server.
""" |
Deploy MLflow models locally.
To deploy a model associated with a run on a tracking server, set the MLFLOW_TRACKING_URI
environment variable to the URL of the desired server.
| commands | python | mlflow/mlflow | mlflow/models/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/cli.py | Apache-2.0 |
def serve(
model_uri,
port,
host,
timeout,
workers,
env_manager=None,
no_conda=False,
install_mlflow=False,
enable_mlserver=False,
):
"""
Serve a model saved with MLflow by launching a webserver on the specified host and port.
The command supports models with the ``python... |
Serve a model saved with MLflow by launching a webserver on the specified host and port.
The command supports models with the ``python_function`` or ``crate`` (R Function) flavor.
For information about the input data formats accepted by the webserver, see the following
documentation: https://www.mlflow... | serve | python | mlflow/mlflow | mlflow/models/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/cli.py | Apache-2.0 |
def predict(
model_uri,
input_data=None,
input_path=None,
content_type=python_api._CONTENT_TYPE_JSON,
output_path=None,
env_manager=_EnvManager.VIRTUALENV,
install_mlflow=False,
pip_requirements_override=None,
env=None,
):
"""
Generate predictions in json format using a saved... |
Generate predictions in json format using a saved MLflow model. For information about the input
data formats accepted by this function, see the following documentation:
https://www.mlflow.org/docs/latest/models.html#built-in-deployment-tools.
| predict | python | mlflow/mlflow | mlflow/models/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/cli.py | Apache-2.0 |
def prepare_env(
model_uri,
env_manager,
install_mlflow,
):
"""
Performs any preparation necessary to predict or serve the model, for example
downloading dependencies or initializing a conda environment. After preparation,
calling predict or serve should be fast.
"""
return get_flavo... |
Performs any preparation necessary to predict or serve the model, for example
downloading dependencies or initializing a conda environment. After preparation,
calling predict or serve should be fast.
| prepare_env | python | mlflow/mlflow | mlflow/models/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/cli.py | Apache-2.0 |
def generate_dockerfile(
model_uri,
output_directory,
env_manager,
mlflow_home,
install_java,
install_mlflow,
enable_mlserver,
):
"""
Generates a directory with Dockerfile whose default entrypoint serves an MLflow model at port
8080 using the python_function flavor. The generated... |
Generates a directory with Dockerfile whose default entrypoint serves an MLflow model at port
8080 using the python_function flavor. The generated Dockerfile is written to the specified
output directory, along with the model (if specified). This Dockerfile defines an image that
is equivalent to the one... | generate_dockerfile | python | mlflow/mlflow | mlflow/models/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/cli.py | Apache-2.0 |
def update_pip_requirements(model_uri, operation, requirement_strings):
"""
Add or remove requirements from a model's conda.yaml and requirements.txt files.
If using a remote tracking server, please make sure to set the MLFLOW_TRACKING_URI
environment variable to the URL of the desired server.
REQU... |
Add or remove requirements from a model's conda.yaml and requirements.txt files.
If using a remote tracking server, please make sure to set the MLFLOW_TRACKING_URI
environment variable to the URL of the desired server.
REQUIREMENT_STRINGS is a list of pip requirements specifiers.
See below for exa... | update_pip_requirements | python | mlflow/mlflow | mlflow/models/cli.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/cli.py | Apache-2.0 |
def set_retriever_schema(
*,
primary_key: str,
text_column: str,
doc_uri: Optional[str] = None,
other_columns: Optional[list[str]] = None,
name: Optional[str] = "retriever",
):
"""
Specify the return schema of a retriever span within your agent or generative AI app code.
**Note**: M... |
Specify the return schema of a retriever span within your agent or generative AI app code.
**Note**: MLflow recommends that your retriever return the default MLflow retriever output
schema described in https://mlflow.org/docs/latest/tracing/tracing-schema#retriever-spans,
in which case you do not need... | set_retriever_schema | python | mlflow/mlflow | mlflow/models/dependencies_schemas.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/dependencies_schemas.py | Apache-2.0 |
def _get_retriever_schema():
"""
Get the vector search schema defined by the user.
Returns:
VectorSearchIndex: The vector search index schema.
"""
retriever_schemas = globals().get(DependenciesSchemasType.RETRIEVERS.value, [])
if not retriever_schemas:
return []
return [
... |
Get the vector search schema defined by the user.
Returns:
VectorSearchIndex: The vector search index schema.
| _get_retriever_schema | python | mlflow/mlflow | mlflow/models/dependencies_schemas.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/dependencies_schemas.py | Apache-2.0 |
def _get_dependencies_schema_from_model(model: "Model") -> Optional[dict]:
"""
Get the dependencies schema from the logged model metadata.
`dependencies_schemas` is a dictionary that defines the dependencies schemas, such as
the retriever schemas. This code is now only useful for Databricks integration... |
Get the dependencies schema from the logged model metadata.
`dependencies_schemas` is a dictionary that defines the dependencies schemas, such as
the retriever schemas. This code is now only useful for Databricks integration.
| _get_dependencies_schema_from_model | python | mlflow/mlflow | mlflow/models/dependencies_schemas.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/dependencies_schemas.py | Apache-2.0 |
def to_dict(self):
"""
Convert the resource to a dictionary.
Subclasses must implement this method.
""" |
Convert the resource to a dictionary.
Subclasses must implement this method.
| to_dict | python | mlflow/mlflow | mlflow/models/dependencies_schemas.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/dependencies_schemas.py | Apache-2.0 |
def from_dict(cls, data: dict[str, str]):
"""
Convert the dictionary to a Resource.
Subclasses must implement this method.
""" |
Convert the dictionary to a Resource.
Subclasses must implement this method.
| from_dict | python | mlflow/mlflow | mlflow/models/dependencies_schemas.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/dependencies_schemas.py | Apache-2.0 |
def generate_dockerfile(
output_dir: str,
base_image: str,
model_install_steps: Optional[str],
entrypoint: str,
env_manager: Union[em.CONDA, em.LOCAL, em.VIRTUALENV],
mlflow_home: Optional[str] = None,
enable_mlserver: bool = False,
disable_env_creation_at_runtime: bool = True,
insta... |
Generates a Dockerfile that can be used to build a docker image, that serves ML model
stored and tracked in MLflow.
| generate_dockerfile | python | mlflow/mlflow | mlflow/models/docker_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/docker_utils.py | Apache-2.0 |
def _pip_mlflow_install_step(dockerfile_context_dir, mlflow_home):
"""
Get docker build commands for installing MLflow given a Docker context dir and optional source
directory
"""
if mlflow_home:
mlflow_dir = _copy_project(
src_path=os.path.abspath(mlflow_home), dst_path=dockerfi... |
Get docker build commands for installing MLflow given a Docker context dir and optional source
directory
| _pip_mlflow_install_step | python | mlflow/mlflow | mlflow/models/docker_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/docker_utils.py | Apache-2.0 |
def predict(self, model_uri, input_path, output_path, content_type):
"""
Generate predictions using a saved MLflow model referenced by the given URI.
Input and output are read from and written to a file or stdin / stdout.
Args:
model_uri: URI pointing to the MLflow model to ... |
Generate predictions using a saved MLflow model referenced by the given URI.
Input and output are read from and written to a file or stdin / stdout.
Args:
model_uri: URI pointing to the MLflow model to be used for scoring.
input_path: Path to the file with input data. I... | predict | python | mlflow/mlflow | mlflow/models/flavor_backend.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/flavor_backend.py | Apache-2.0 |
def serve(
self,
model_uri,
port,
host,
timeout,
enable_mlserver,
synchronous=True,
stdout=None,
stderr=None,
):
"""
Serve the specified MLflow model locally.
Args:
model_uri: URI pointing to the MLflow mode... |
Serve the specified MLflow model locally.
Args:
model_uri: URI pointing to the MLflow model to be used for scoring.
port: Port to use for the model deployment.
host: Host to use for the model deployment. Defaults to ``localhost``.
timeout: Timeout in sec... | serve | python | mlflow/mlflow | mlflow/models/flavor_backend.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/flavor_backend.py | Apache-2.0 |
def prepare_env(self, model_uri, capture_output=False):
"""
Performs any preparation necessary to predict or serve the model, for example
downloading dependencies or initializing a conda environment. After preparation,
calling predict or serve should be fast.
""" |
Performs any preparation necessary to predict or serve the model, for example
downloading dependencies or initializing a conda environment. After preparation,
calling predict or serve should be fast.
| prepare_env | python | mlflow/mlflow | mlflow/models/flavor_backend.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/flavor_backend.py | Apache-2.0 |
def can_score_model(self):
"""
Check whether this flavor backend can be deployed in the current environment.
Returns:
True if this flavor backend can be applied in the current environment.
""" |
Check whether this flavor backend can be deployed in the current environment.
Returns:
True if this flavor backend can be applied in the current environment.
| can_score_model | python | mlflow/mlflow | mlflow/models/flavor_backend.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/flavor_backend.py | Apache-2.0 |
def get_serving_input(self, path: str) -> Optional[str]:
"""
Load serving input example from a model directory. Returns None if there is no serving input
example.
Args:
path: Path to the model directory.
Returns:
Serving input example or None if the mode... |
Load serving input example from a model directory. Returns None if there is no serving input
example.
Args:
path: Path to the model directory.
Returns:
Serving input example or None if the model has no serving input example.
| get_serving_input | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def load_input_example(self, path: Optional[str] = None) -> Optional[str]:
"""
Load the input example saved along a model. Returns None if there is no example metadata
(i.e. the model was saved without example). Raises FileNotFoundError if there is model
metadata but the example file is ... |
Load the input example saved along a model. Returns None if there is no example metadata
(i.e. the model was saved without example). Raises FileNotFoundError if there is model
metadata but the example file is missing.
Args:
path: Model or run URI, or path to the `model` dir... | load_input_example | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def load_input_example_params(self, path: str):
"""
Load the params of input example saved along a model. Returns None if there are no params in
the input_example.
Args:
path: Path to the model directory.
Returns:
params (dict) or None if the model has n... |
Load the params of input example saved along a model. Returns None if there are no params in
the input_example.
Args:
path: Path to the model directory.
Returns:
params (dict) or None if the model has no params.
| load_input_example_params | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def get_model_info(self, logged_model: Optional[LoggedModel] = None) -> ModelInfo:
"""
Create a :py:class:`ModelInfo <mlflow.models.model.ModelInfo>` instance that contains the
model metadata.
"""
return ModelInfo(
artifact_path=self.artifact_path,
flavors... |
Create a :py:class:`ModelInfo <mlflow.models.model.ModelInfo>` instance that contains the
model metadata.
| get_model_info | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def load(cls, path) -> "Model":
"""
Load a model from its YAML representation.
Args:
path: A local filesystem path or URI referring to the MLmodel YAML file
representation of the Model object or to the directory containing
the MLmodel YAML file repres... |
Load a model from its YAML representation.
Args:
path: A local filesystem path or URI referring to the MLmodel YAML file
representation of the Model object or to the directory containing
the MLmodel YAML file representation.
Returns:
An ... | load | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def from_dict(cls, model_dict) -> "Model":
"""Load a model from its YAML representation."""
from mlflow.models.signature import ModelSignature
model_dict = model_dict.copy()
if "signature" in model_dict and isinstance(model_dict["signature"], dict):
signature = ModelSignatu... | Load a model from its YAML representation. | from_dict | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def _log_v2(
cls,
artifact_path,
flavor,
registered_model_name=None,
await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
metadata=None,
run_id=None,
resources=None,
auth_policy=None,
prompts=None,
**kwargs,
) -> ModelInfo:
... |
Log model using supplied flavor module. If no run is active, this method will create a new
active run.
Args:
artifact_path: Run relative path identifying the model.
flavor: Flavor module to save the model with. The module must have
the ``save_model`` fun... | _log_v2 | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def _copy_model_metadata_for_uc_sharing(local_path: str, flavor) -> None:
"""
Copy model metadata files to a sub-directory 'metadata',
For Databricks Unity Catalog sharing use-cases.
Args:
local_path: Local path to the model directory.
flavor: Flavor module to save the model with.
"... |
Copy model metadata files to a sub-directory 'metadata',
For Databricks Unity Catalog sharing use-cases.
Args:
local_path: Local path to the model directory.
flavor: Flavor module to save the model with.
| _copy_model_metadata_for_uc_sharing | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def update_model_requirements(
model_uri: str,
operation: Literal["add", "remove"],
requirement_list: list[str],
) -> None:
"""
Add or remove requirements from a model's conda.yaml and requirements.txt files.
The process involves downloading these two files from the model artifacts
(if they... |
Add or remove requirements from a model's conda.yaml and requirements.txt files.
The process involves downloading these two files from the model artifacts
(if they're non-local), updating them with the specified requirements,
and then overwriting the existing files. Should the artifact repository
... | update_model_requirements | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def set_model(model) -> None:
"""
When logging model as code, this function can be used to set the model object
to be logged.
Args:
model: The model object to be logged. Supported model types are:
- A Python function or callable object.
- A Langchain model or pa... |
When logging model as code, this function can be used to set the model object
to be logged.
Args:
model: The model object to be logged. Supported model types are:
- A Python function or callable object.
- A Langchain model or path to a Langchain model.
... | set_model | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def _update_active_model_id_based_on_mlflow_model(mlflow_model: Model):
"""
Update the current active model ID based on the provided MLflow model.
Only set the active model ID if it is not already set by the user.
This is useful for setting the active model ID when loading a model
to ensure traces g... |
Update the current active model ID based on the provided MLflow model.
Only set the active model ID if it is not already set by the user.
This is useful for setting the active model ID when loading a model
to ensure traces generated are associated with the loaded model.
| _update_active_model_id_based_on_mlflow_model | python | mlflow/mlflow | mlflow/models/model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model.py | Apache-2.0 |
def _read_config(self):
"""Reads the YAML configuration file and returns its contents.
Raises:
FileNotFoundError: If the configuration file does not exist.
yaml.YAMLError: If there is an error parsing the YAML content.
Returns:
dict or None: The content of t... | Reads the YAML configuration file and returns its contents.
Raises:
FileNotFoundError: If the configuration file does not exist.
yaml.YAMLError: If there is an error parsing the YAML content.
Returns:
dict or None: The content of the YAML file as a dictionary, or No... | _read_config | python | mlflow/mlflow | mlflow/models/model_config.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model_config.py | Apache-2.0 |
def get(self, key):
"""Gets the value of a top-level parameter in the configuration."""
config_data = self._read_config()
if config_data and key in config_data:
return config_data[key]
else:
raise KeyError(f"Key '{key}' not found in configuration: {config_data}."... | Gets the value of a top-level parameter in the configuration. | get | python | mlflow/mlflow | mlflow/models/model_config.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/model_config.py | Apache-2.0 |
def build_docker(
model_uri=None,
name="mlflow-pyfunc",
env_manager=_EnvManager.VIRTUALENV,
mlflow_home=None,
install_java=False,
install_mlflow=False,
enable_mlserver=False,
base_image=None,
):
"""
Builds a Docker image whose default entrypoint serves an MLflow model at port 808... |
Builds a Docker image whose default entrypoint serves an MLflow model at port 8080, using the
python_function flavor. The container serves the model referenced by ``model_uri``, if
specified. If ``model_uri`` is not specified, an MLflow Model directory must be mounted as a
volume into the /opt/ml/model... | build_docker | python | mlflow/mlflow | mlflow/models/python_api.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/python_api.py | Apache-2.0 |
def _validate_csv_string(input_data: str):
"""
Validate the string must be the path to a CSV file.
"""
try:
import pandas as pd
pd.read_csv(StringIO(input_data))
except Exception as e:
raise MlflowException.invalid_parameter_value(
message="Failed to deserialize ... |
Validate the string must be the path to a CSV file.
| _validate_csv_string | python | mlflow/mlflow | mlflow/models/python_api.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/python_api.py | Apache-2.0 |
def type(self) -> ResourceType:
"""
The resource type (must be defined by subclasses).
""" |
The resource type (must be defined by subclasses).
| type | python | mlflow/mlflow | mlflow/models/resources.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/resources.py | Apache-2.0 |
def target_uri(self) -> str:
"""
The target URI where the resource is hosted (must be defined by subclasses).
""" |
The target URI where the resource is hosted (must be defined by subclasses).
| target_uri | python | mlflow/mlflow | mlflow/models/resources.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/resources.py | Apache-2.0 |
def to_dict(self) -> dict[str, Any]:
"""
Serialize into a 'jsonable' dictionary.
Input and output schema are represented as json strings. This is so that the
representation is compact when embedded in an MLmodel yaml file.
Returns:
dictionary representation with inp... |
Serialize into a 'jsonable' dictionary.
Input and output schema are represented as json strings. This is so that the
representation is compact when embedded in an MLmodel yaml file.
Returns:
dictionary representation with input and output schema represented as json strings... | to_dict | python | mlflow/mlflow | mlflow/models/signature.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/signature.py | Apache-2.0 |
def from_dict(cls, signature_dict: dict[str, Any]):
"""
Deserialize from dictionary representation.
Args:
signature_dict: Dictionary representation of model signature.
Expected dictionary format:
`{'inputs': <json string>,
'outputs': <... |
Deserialize from dictionary representation.
Args:
signature_dict: Dictionary representation of model signature.
Expected dictionary format:
`{'inputs': <json string>,
'outputs': <json string>,
'params': <json string>" }`
... | from_dict | python | mlflow/mlflow | mlflow/models/signature.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/signature.py | Apache-2.0 |
def infer_signature(
model_input: Any = None,
model_output: "MlflowInferableDataset" = None,
params: Optional[dict[str, Any]] = None,
) -> ModelSignature:
"""
Infer an MLflow model signature from the training data (input), model predictions (output)
and parameters (for inference).
The signa... |
Infer an MLflow model signature from the training data (input), model predictions (output)
and parameters (for inference).
The signature represents model input and output as data frames with (optionally) named columns
and data type specified as one of types defined in :py:class:`mlflow.types.DataType`... | infer_signature | python | mlflow/mlflow | mlflow/models/signature.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/signature.py | Apache-2.0 |
def _extract_type_hints(f, input_arg_index):
"""
Extract type hints from a function.
Args:
f: Function to extract type hints from.
input_arg_index: Index of the function argument that corresponds to the model input.
Returns:
A `_TypeHints` object containing the input and output... |
Extract type hints from a function.
Args:
f: Function to extract type hints from.
input_arg_index: Index of the function argument that corresponds to the model input.
Returns:
A `_TypeHints` object containing the input and output type hints.
| _extract_type_hints | python | mlflow/mlflow | mlflow/models/signature.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/signature.py | Apache-2.0 |
def _infer_signature_from_type_hints(
func, type_hints: _TypeHints, input_example=None
) -> Optional[ModelSignature]:
"""
Infer the signature from type hints.
"""
if type_hints.input is None:
return None
params = None
params_key = "params"
if _contains_params(input_example):
... |
Infer the signature from type hints.
| _infer_signature_from_type_hints | python | mlflow/mlflow | mlflow/models/signature.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/signature.py | Apache-2.0 |
def _infer_signature_from_input_example(
input_example: Optional[_Example], wrapped_model
) -> Optional[ModelSignature]:
"""
Infer the signature from an example input and a PyFunc wrapped model. Catches all exceptions.
Args:
input_example: Saved _Example object that contains input example insta... |
Infer the signature from an example input and a PyFunc wrapped model. Catches all exceptions.
Args:
input_example: Saved _Example object that contains input example instance.
wrapped_model: A PyFunc wrapped model which has a `predict` method.
Returns:
A `ModelSignature` object con... | _infer_signature_from_input_example | python | mlflow/mlflow | mlflow/models/signature.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/signature.py | Apache-2.0 |
def set_signature(
model_uri: str,
signature: ModelSignature,
):
"""
Sets the model signature for specified model artifacts.
The process involves downloading the MLmodel file in the model artifacts (if it's non-local),
updating its model signature, and then overwriting the existing MLmodel file... |
Sets the model signature for specified model artifacts.
The process involves downloading the MLmodel file in the model artifacts (if it's non-local),
updating its model signature, and then overwriting the existing MLmodel file. Should the
artifact repository associated with the model artifacts disallo... | set_signature | python | mlflow/mlflow | mlflow/models/signature.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/signature.py | Apache-2.0 |
def save(self, parent_dir_path: str):
"""
Save the example as json at ``parent_dir_path``/`self.info['artifact_path']`.
Save serving input as json at ``parent_dir_path``/`self.info['serving_input_path']`.
"""
with open(os.path.join(parent_dir_path, self.info[INPUT_EXAMPLE_PATH]),... |
Save the example as json at ``parent_dir_path``/`self.info['artifact_path']`.
Save serving input as json at ``parent_dir_path``/`self.info['serving_input_path']`.
| save | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def convert_input_example_to_serving_input(input_example) -> Optional[str]:
"""
Helper function to convert a model's input example to a serving input example that
can be used for model inference in the scoring server.
Args:
input_example: model input example. Supported types are pandas.DataFram... |
Helper function to convert a model's input example to a serving input example that
can be used for model inference in the scoring server.
Args:
input_example: model input example. Supported types are pandas.DataFrame, numpy.ndarray,
dictionary of (name -> numpy.ndarray), list, scalars ... | convert_input_example_to_serving_input | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _save_example( # noqa: D417
mlflow_model: Model, input_example: Optional[ModelInputExample], path: str
) -> Optional[_Example]:
"""
Saves example to a file on the given path and updates passed Model with example metadata.
The metadata is a dictionary with the following fields:
- 'artifact_pa... |
Saves example to a file on the given path and updates passed Model with example metadata.
The metadata is a dictionary with the following fields:
- 'artifact_path': example path relative to the model directory.
- 'type': Type of example. Currently the supported values are 'dataframe' and 'ndarray'... | _save_example | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _get_mlflow_model_input_example_dict(mlflow_model: Model, uri_or_path: str) -> Optional[dict]:
"""
Args:
mlflow_model: Model metadata.
uri_or_path: Model or run URI, or path to the `model` directory.
e.g. models://<model_name>/<model_version>, runs:/<run_id>/<artifact_path>
... |
Args:
mlflow_model: Model metadata.
uri_or_path: Model or run URI, or path to the `model` directory.
e.g. models://<model_name>/<model_version>, runs:/<run_id>/<artifact_path>
or /path/to/model
Returns:
Input example or None if the model has no example.
| _get_mlflow_model_input_example_dict | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _load_serving_input_example(mlflow_model: Model, path: str) -> Optional[str]:
"""
Load serving input example from a model directory. Returns None if there is no serving input
example.
Args:
mlflow_model: Model metadata.
path: Path to the model directory.
Returns:
Servin... |
Load serving input example from a model directory. Returns None if there is no serving input
example.
Args:
mlflow_model: Model metadata.
path: Path to the model directory.
Returns:
Serving input example or None if the model has no serving input example.
| _load_serving_input_example | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _read_file_content(uri_or_path: str, file_name: str):
"""
Read file content from a model directory or URI.
Args:
uri_or_path: Model or run URI, or path to the `model` directory.
e.g. models://<model_name>/<model_version>, runs:/<run_id>/<artifact_path>
or /path/to/model
... |
Read file content from a model directory or URI.
Args:
uri_or_path: Model or run URI, or path to the `model` directory.
e.g. models://<model_name>/<model_version>, runs:/<run_id>/<artifact_path>
or /path/to/model
file_name: Name of the file to read.
| _read_file_content | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _read_example(mlflow_model: Model, uri_or_path: str):
"""
Read example from a model directory. Returns None if there is no example metadata (i.e. the
model was saved without example). Raises FileNotFoundError if there is model metadata but the
example file is missing.
Args:
mlflow_model... |
Read example from a model directory. Returns None if there is no example metadata (i.e. the
model was saved without example). Raises FileNotFoundError if there is model metadata but the
example file is missing.
Args:
mlflow_model: Model metadata.
uri_or_path: Model or run URI, or path ... | _read_example | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _read_example_params(mlflow_model: Model, path: str):
"""
Read params of input_example from a model directory. Returns None if there is no params
in the input_example or the model was saved without example.
"""
if (
mlflow_model.saved_input_example_info is None
or mlflow_model.sa... |
Read params of input_example from a model directory. Returns None if there is no params
in the input_example or the model was saved without example.
| _read_example_params | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_tensor_spec(
values: Union[np.ndarray, "csc_matrix", "csr_matrix"],
tensor_spec: TensorSpec,
):
"""
Enforce the input tensor shape and type matches the provided tensor spec.
"""
expected_shape = tensor_spec.shape
expected_type = tensor_spec.type
actual_shape = values.shape
... |
Enforce the input tensor shape and type matches the provided tensor spec.
| _enforce_tensor_spec | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_mlflow_datatype(name, values: pd.Series, t: DataType):
"""
Enforce the input column type matches the declared in model input schema.
The following type conversions are allowed:
1. object -> string
2. int -> long (upcast)
3. float -> double (upcast)
4. int -> double (safe conve... |
Enforce the input column type matches the declared in model input schema.
The following type conversions are allowed:
1. object -> string
2. int -> long (upcast)
3. float -> double (upcast)
4. int -> double (safe conversion)
5. np.datetime64[x] -> datetime (any precision)
6. object ->... | _enforce_mlflow_datatype | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_param_datatype(value: Any, dtype: DataType):
"""
Enforce the value matches the data type. This is used to enforce params datatype.
The returned data is of python built-in type or a datetime object.
The following type conversions are allowed:
1. int -> long, float, double
2. long -... |
Enforce the value matches the data type. This is used to enforce params datatype.
The returned data is of python built-in type or a datetime object.
The following type conversions are allowed:
1. int -> long, float, double
2. long -> float, double
3. float -> double
4. any -> datetime (tr... | _enforce_param_datatype | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_unnamed_col_schema(pf_input: pd.DataFrame, input_schema: Schema):
"""Enforce the input columns conform to the model's column-based signature."""
input_names = pf_input.columns[: len(input_schema.inputs)]
input_types = input_schema.input_types()
new_pf_input = {}
for i, x in enumerate(in... | Enforce the input columns conform to the model's column-based signature. | _enforce_unnamed_col_schema | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_tensor_schema(pf_input: PyFuncInput, input_schema: Schema):
"""Enforce the input tensor(s) conforms to the model's tensor-based signature."""
def _is_sparse_matrix(x):
if not HAS_SCIPY:
# we can safely assume that it's not a sparse matrix if scipy is not installed
r... | Enforce the input tensor(s) conforms to the model's tensor-based signature. | _enforce_tensor_schema | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_schema(pf_input: PyFuncInput, input_schema: Schema, flavor: Optional[str] = None):
"""
Enforces the provided input matches the model's input schema,
For signatures with input names, we check there are no missing inputs and reorder the inputs to
match the ordering declared in schema if nece... |
Enforces the provided input matches the model's input schema,
For signatures with input names, we check there are no missing inputs and reorder the inputs to
match the ordering declared in schema if necessary. Any extra columns are ignored.
For column-based signatures, we make sure the types of the i... | _enforce_schema | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_pyspark_dataframe_schema(
original_pf_input: SparkDataFrame,
pf_input_as_pandas,
input_schema: Schema,
flavor: Optional[str] = None,
):
"""
Enforce that the input PySpark DataFrame conforms to the model's input schema.
This function creates a new DataFrame that only includes th... |
Enforce that the input PySpark DataFrame conforms to the model's input schema.
This function creates a new DataFrame that only includes the columns from the original
DataFrame that are declared in the model's input schema. Any extra columns in the original
DataFrame are dropped.Note that this function... | _enforce_pyspark_dataframe_schema | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _enforce_array(data: Any, arr: Array, required: bool = True):
"""
Enforce data against an Array type.
If the field is required, then the data must be provided.
If Array's internal dtype is AnyType, then None and empty lists are also accepted.
"""
if not required or isinstance(arr.dtype, AnyT... |
Enforce data against an Array type.
If the field is required, then the data must be provided.
If Array's internal dtype is AnyType, then None and empty lists are also accepted.
| _enforce_array | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def add_libraries_to_model(model_uri, run_id=None, registered_model_name=None):
"""
Given a registered model_uri (e.g. models:/<model_name>/<model_version>), this utility
re-logs the model along with all the required model libraries back to the Model Registry.
The required model libraries are stored alo... |
Given a registered model_uri (e.g. models:/<model_name>/<model_version>), this utility
re-logs the model along with all the required model libraries back to the Model Registry.
The required model libraries are stored along with the model as model artifacts. In
addition, supporting files to the model (e... | add_libraries_to_model | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def get_model_version_from_model_uri(model_uri):
"""
Helper function to fetch a model version from a model uri of the form
models:/<model_name>/<model_version/stage/latest>.
"""
import mlflow
from mlflow import MlflowClient
databricks_profile_uri = (
get_databricks_profile_uri_from_... |
Helper function to fetch a model version from a model uri of the form
models:/<model_name>/<model_version/stage/latest>.
| get_model_version_from_model_uri | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _validate_model_code_from_notebook(code):
"""
Validate there isn't any code that would work in a notebook but not as exported Python file.
For now, this checks for dbutils and magic commands.
"""
output_code_list = []
for line in code.splitlines():
for match in re.finditer(r"\bdbuti... |
Validate there isn't any code that would work in a notebook but not as exported Python file.
For now, this checks for dbutils and magic commands.
| _validate_model_code_from_notebook | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _convert_llm_ndarray_to_list(data):
"""
Convert numpy array in the input data to list, because numpy array is not json serializable.
"""
if isinstance(data, np.ndarray):
return data.tolist()
if isinstance(data, list):
return [_convert_llm_ndarray_to_list(d) for d in data]
if ... |
Convert numpy array in the input data to list, because numpy array is not json serializable.
| _convert_llm_ndarray_to_list | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _convert_llm_input_data(data: Any) -> Union[list, dict]:
"""
Convert input data to a format that can be passed to the model with GenAI flavors such as
LangChain and LLamaIndex.
Args
data: Input data to be converted. We assume it is a single request payload, but it can be
in any ... |
Convert input data to a format that can be passed to the model with GenAI flavors such as
LangChain and LLamaIndex.
Args
data: Input data to be converted. We assume it is a single request payload, but it can be
in any format such as a single scalar value, a dictionary, list (with one e... | _convert_llm_input_data | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _databricks_path_exists(path: Path) -> bool:
"""
Check if a path exists in Databricks workspace.
"""
if not is_in_databricks_runtime():
return False
from databricks.sdk import WorkspaceClient
from databricks.sdk.errors import ResourceDoesNotExist
client = WorkspaceClient()
... |
Check if a path exists in Databricks workspace.
| _databricks_path_exists | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def _validate_and_get_model_code_path(model_code_path: str, temp_dir: str) -> str:
"""
Validate model code path exists. When failing to open the model file on Databricks,
creates a temp file in temp_dir and validate its contents if it's a notebook.
Returns either `model_code_path` or a temp file path w... |
Validate model code path exists. When failing to open the model file on Databricks,
creates a temp file in temp_dir and validate its contents if it's a notebook.
Returns either `model_code_path` or a temp file path with the contents of the notebook.
| _validate_and_get_model_code_path | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def validate_serving_input(model_uri: str, serving_input: Union[str, dict[str, Any]]):
"""
Helper function to validate the model can be served and provided input is valid
prior to serving the model.
Args:
model_uri: URI of the model to be served.
serving_input: Input data to be validate... |
Helper function to validate the model can be served and provided input is valid
prior to serving the model.
Args:
model_uri: URI of the model to be served.
serving_input: Input data to be validated. Should be a dictionary or a JSON string.
Returns:
The prediction result from t... | validate_serving_input | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def get_external_mlflow_model_spec(logged_model: LoggedModel) -> Model:
"""
Create the MLflow Model specification for a given logged model whose artifacts
(code, weights, etc.) are stored externally outside of MLflow.
Args:
logged_model: The external logged model for which to create an MLflow M... |
Create the MLflow Model specification for a given logged model whose artifacts
(code, weights, etc.) are stored externally outside of MLflow.
Args:
logged_model: The external logged model for which to create an MLflow Model specification.
Returns:
Model: MLflow Model specification for... | get_external_mlflow_model_spec | python | mlflow/mlflow | mlflow/models/utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/utils.py | Apache-2.0 |
def log_model(cls, model_uri, registered_model_name=None):
"""
Logs a registered model as an MLflow artifact for the current run. This only operates on
a model which has been registered to the Model Registry. Given a registered model_uri (
e.g. models:/<model_name>/<model_version>), this... |
Logs a registered model as an MLflow artifact for the current run. This only operates on
a model which has been registered to the Model Registry. Given a registered model_uri (
e.g. models:/<model_name>/<model_version>), this utility re-logs the model along with all
the required model l... | log_model | python | mlflow/mlflow | mlflow/models/wheeled_model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/wheeled_model.py | Apache-2.0 |
def save_model(self, path, mlflow_model=None):
"""
Given an existing registered model, saves the model along with it's dependencies stored as
wheels to a path on the local file system.
This does not modify existing model behavior or existing model flavors. It simply downloads
th... |
Given an existing registered model, saves the model along with it's dependencies stored as
wheels to a path on the local file system.
This does not modify existing model behavior or existing model flavors. It simply downloads
the model dependencies as wheels and modifies the requiremen... | save_model | python | mlflow/mlflow | mlflow/models/wheeled_model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/wheeled_model.py | Apache-2.0 |
def _update_conda_env(self, new_pip_deps, conda_env_path):
"""
Updates the list pip packages in the conda.yaml file to the list of wheels in the wheels
directory.
{
"name": "env",
"channels": [...],
"dependencies": [
...,
... |
Updates the list pip packages in the conda.yaml file to the list of wheels in the wheels
directory.
{
"name": "env",
"channels": [...],
"dependencies": [
...,
"pip",
{"pip": [...]}, <- Overwrite this with list ... | _update_conda_env | python | mlflow/mlflow | mlflow/models/wheeled_model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/wheeled_model.py | Apache-2.0 |
def _update_mlflow_model(self, original_model_metadata, mlflow_model):
"""
Modifies the MLModel file to reflect updated information such as the run_id,
utc_time_created. Additionally, this also adds `wheels` to the MLModel file to indicate that
this is a `wheeled` model.
Args:
... |
Modifies the MLModel file to reflect updated information such as the run_id,
utc_time_created. Additionally, this also adds `wheels` to the MLModel file to indicate that
this is a `wheeled` model.
Args:
original_model_metadata: The model metadata stored in the original MLmo... | _update_mlflow_model | python | mlflow/mlflow | mlflow/models/wheeled_model.py | https://github.com/mlflow/mlflow/blob/master/mlflow/models/wheeled_model.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.