repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
mlflow | mlflow/optuna/__init__.py | .py | from mlflow.optuna.storage import MlflowStorage
__all__ = ["MlflowStorage"]
| 4 | 77 |
mlflow | mlflow/metrics/__init__.py | .py | import os
from mlflow.metrics import genai
from mlflow.metrics.base import MetricValue
from mlflow.metrics.genai.utils import _MIGRATION_GUIDE
from mlflow.metrics.metric_definitions import (
_accuracy_eval_fn,
_ari_eval_fn,
_bleu_eval_fn,
_f1_score_eval_fn,
_flesch_kincaid_eval_fn,
_mae_eval_fn... | 512 | 16,829 |
mlflow | mlflow/metrics/metric_definitions.py | .py | import functools
import logging
import subprocess
import tempfile
from pathlib import Path
import numpy as np
from mlflow.environment_variables import _MLFLOW_TESTING
from mlflow.metrics.base import MetricValue, standard_aggregations
_logger = logging.getLogger(__name__)
# used to silently fail with invalid metric... | 594 | 21,315 |
mlflow | mlflow/metrics/base.py | .py | from dataclasses import dataclass
import numpy as np
from mlflow.utils.validation import _is_numeric
def standard_aggregations(scores):
return {
"mean": np.mean(scores),
"variance": np.var(scores),
"p90": np.percentile(scores, 90),
}
@dataclass
class MetricValue:
"""
The va... | 39 | 1,015 |
mlflow | mlflow/metrics/genai/prompt_template.py | .py | import string
from typing import Any
class PromptTemplate:
"""A prompt template for a language model.
A prompt template consists of an array of strings that will be concatenated together. It accepts
a set of parameters from the user that can be used to generate a prompt for a language model.
The tem... | 69 | 2,441 |
mlflow | mlflow/metrics/genai/utils.py | .py | _MIGRATION_GUIDE = (
"Use the new GenAI evaluation functionality instead. See "
"https://mlflow.org/docs/latest/genai/eval-monitor/legacy-llm-evaluation/ "
"for the migration guide."
)
def _get_latest_metric_version():
return "v1"
def _get_default_model():
return "openai:/gpt-4"
| 14 | 304 |
mlflow | mlflow/metrics/genai/__init__.py | .py | from mlflow.metrics.genai.base import EvaluationExample
from mlflow.metrics.genai.genai_metric import (
make_genai_metric,
make_genai_metric_from_prompt,
retrieve_custom_metrics,
)
from mlflow.metrics.genai.metric_definitions import (
answer_correctness,
answer_relevance,
answer_similarity,
... | 26 | 596 |
mlflow | mlflow/metrics/genai/genai_metric.py | .py | import json
import logging
import re
import warnings
from concurrent.futures import ThreadPoolExecutor, as_completed
from inspect import Parameter, Signature
from tempfile import TemporaryDirectory
from typing import Any
import pandas as pd
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.metri... | 807 | 33,307 |
mlflow | mlflow/metrics/genai/metric_definitions.py | .py | from typing import Any
from mlflow.exceptions import MlflowException
from mlflow.metrics.genai.base import EvaluationExample
from mlflow.metrics.genai.genai_metric import make_genai_metric
from mlflow.metrics.genai.utils import _MIGRATION_GUIDE, _get_latest_metric_version
from mlflow.models import EvaluationMetric
fro... | 457 | 23,122 |
mlflow | mlflow/metrics/genai/model_utils.py | .py | import logging
import os
from typing import TYPE_CHECKING, Any
import requests
from pydantic import BaseModel
from mlflow.environment_variables import MLFLOW_GENAI_EVAL_LLM_TIMEOUT
from mlflow.exceptions import MlflowException
from mlflow.gateway.config import EndpointConfig
from mlflow.gateway.providers.openai impor... | 639 | 25,017 |
mlflow | mlflow/metrics/genai/base.py | .py | from dataclasses import dataclass
from mlflow.metrics.genai.prompt_template import PromptTemplate
@dataclass
class EvaluationExample:
"""
Stores the sample example during few shot learning during LLM evaluation
Args:
input: The input provided to the model
output: The output generated by ... | 99 | 3,819 |
mlflow | mlflow/metrics/genai/prompts/v1.py | .py | from dataclasses import dataclass, field
from typing import Any
from mlflow.metrics.genai.base import EvaluationExample
from mlflow.metrics.genai.prompt_template import PromptTemplate
# TODO: Update the default_mode and default_parameters to the correct values post experimentation
default_model = "openai:/gpt-4"
# De... | 458 | 22,799 |
mlflow | mlflow/mcp/server.py | .py | import contextlib
import io
import os
from typing import TYPE_CHECKING, Any, Callable
import click
from click.types import BOOL, FLOAT, INT, STRING, UUID
import mlflow.deployments.cli as deployments_cli
import mlflow.experiments
import mlflow.models.cli as models_cli
import mlflow.runs
from mlflow.ai_commands.ai_comm... | 256 | 8,485 |
mlflow | mlflow/mcp/decorator.py | .py | """
Decorator for exposing MLflow CLI commands as MCP tools.
Usage:
from mlflow.mcp.decorator import mlflow_mcp
@commands.command("search")
@mlflow_mcp(tool_name="search_traces")
@click.option(...)
def search_traces(...):
...
The decorator attaches MCP metadata to the Click command, which... | 75 | 2,043 |
mlflow | mlflow/mcp/cli.py | .py | import click
from mlflow.mcp.server import run_server
from mlflow.telemetry.events import McpRunEvent
from mlflow.telemetry.track import record_usage_event
@click.group(
"mcp",
help=(
"Model Context Protocol (MCP) server for MLflow. "
"MCP enables LLM applications to interact with MLflow trac... | 34 | 872 |
mlflow | mlflow/utils/_unity_catalog_oss_utils.py | .py | import re
from mlflow.entities.model_registry import (
ModelVersion,
ModelVersionSearch,
RegisteredModel,
RegisteredModelSearch,
)
from mlflow.exceptions import MlflowException
from mlflow.protos.unity_catalog_messages_pb2 import (
ModelVersionInfo,
ModelVersionStatus,
RegisteredModelInfo,
... | 97 | 3,440 |
mlflow | mlflow/utils/spark_utils.py | .py | def is_spark_connect_mode():
try:
from pyspark.sql.utils import is_remote
except ImportError:
return False
return is_remote()
def get_spark_dataframe_type():
if is_spark_connect_mode():
from pyspark.sql.connect.dataframe import DataFrame as SparkDataFrame
else:
from... | 16 | 395 |
mlflow | mlflow/utils/env_pack.py | .py | import shutil
import subprocess
import sys
import tarfile
import tempfile
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Generator, Literal
import yaml
from mlflow.artifacts import download_artifacts
from mlflow.exceptions import MlflowException
fro... | 216 | 7,998 |
mlflow | mlflow/utils/lazy_load.py | .py | """Utility to lazy load modules."""
import importlib
import sys
import types
class LazyLoader(types.ModuleType):
"""Class for module lazy loading.
This class helps lazily load modules at package level, which avoids pulling in large
dependencies like `tensorflow` or `torch`. This class is mirrored from w... | 52 | 1,726 |
mlflow | mlflow/utils/process.py | .py | import functools
import os
import subprocess
import sys
from mlflow.utils.databricks_utils import is_in_databricks_runtime
from mlflow.utils.os import is_windows
class ShellCommandException(Exception):
@classmethod
def from_completed_process(cls, process):
lines = [
f"Non-zero exit code: ... | 182 | 6,522 |
mlflow | mlflow/utils/exception_utils.py | .py | import traceback
def get_stacktrace(error):
msg = repr(error)
try:
tb = traceback.format_exception(error)
return (msg + "".join(tb)).strip()
except Exception:
return msg
| 11 | 208 |
mlflow | mlflow/utils/oss_registry_utils.py | .py | import urllib.parse
from mlflow.environment_variables import MLFLOW_UC_OSS_TOKEN
from mlflow.exceptions import MlflowException
from mlflow.utils.databricks_utils import get_databricks_host_creds
from mlflow.utils.rest_utils import MlflowHostCreds
from mlflow.utils.uri import (
_DATABRICKS_UNITY_CATALOG_SCHEME,
)
... | 30 | 936 |
mlflow | mlflow/utils/name_utils.py | .py | import random
import uuid
_EXPERIMENT_ID_FIXED_WIDTH = 18
def _generate_unique_integer_id():
"""Utility function for generating a random fixed-length integer
Returns:
a fixed-width integer
"""
random_int = uuid.uuid4().int
# Cast to string to get a fixed length
random_str = str(rand... | 343 | 5,763 |
mlflow | mlflow/utils/_spark_utils.py | .py | import contextlib
import multiprocessing
import os
import shutil
import tempfile
import zipfile
def _get_active_spark_session():
try:
from pyspark.sql import SparkSession
except ImportError:
# Return None if user doesn't have PySpark installed
return None
try:
# getActiveSe... | 203 | 8,065 |
mlflow | mlflow/utils/timeout.py | .py | import signal
from contextlib import contextmanager
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import NOT_IMPLEMENTED
from mlflow.utils.os import is_windows
class MlflowTimeoutError(Exception):
pass
@contextmanager
def run_with_timeout(seconds):
"""
Context manager ... | 43 | 1,214 |
mlflow | mlflow/utils/class_utils.py | .py | import importlib
def _get_class_from_string(fully_qualified_class_name):
module, class_name = fully_qualified_class_name.rsplit(".", maxsplit=1)
return getattr(importlib.import_module(module), class_name)
| 7 | 215 |
mlflow | mlflow/utils/virtualenv.py | .py | import logging
import os
import re
import shutil
import tempfile
import uuid
from pathlib import Path
from typing import Literal
from packaging.version import Version
import mlflow
from mlflow.environment_variables import _MLFLOW_TESTING, MLFLOW_ENV_ROOT
from mlflow.exceptions import MlflowException
from mlflow.model... | 463 | 18,821 |
mlflow | mlflow/utils/search_utils.py | .py | import ast
import base64
import json
import math
import operator
import re
import shlex
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any, Callable
import sqlparse
from packaging.version import Version
from sqlparse.sql import (
Comparison,
Identifier,
Parenthesis,
Stateme... | 2,888 | 118,188 |
mlflow | mlflow/utils/huggingface_utils.py | .py | import functools
import logging
import os
import time
from mlflow.environment_variables import _MLFLOW_TESTING
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST
_logger = logging.getLogger(__name__)
# NB: The maxsize=1 is added for encouraging the cache r... | 83 | 2,966 |
mlflow | mlflow/utils/string_utils.py | .py | import re
import shlex
from datetime import datetime
from typing import Any
from mlflow.utils.os import is_windows
def strip_prefix(original: str, prefix: str) -> str:
if original.startswith(prefix):
return original[len(prefix) :]
return original
def strip_suffix(original: str, suffix: str) -> str:... | 191 | 6,079 |
mlflow | mlflow/utils/thread_utils.py | .py | import contextvars
import os
import threading
from collections.abc import Callable, Iterable
from concurrent.futures import ThreadPoolExecutor
from typing import Any, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class ThreadLocalVariable:
"""
Class for creating a thread local variable.
Args:
defaul... | 86 | 2,932 |
mlflow | mlflow/utils/jsonpath_utils.py | .py | """
JSONPath utilities for navigating and manipulating nested JSON structures.
This module provides a simplified JSONPath-like implementation without adding
external dependencies to MLflow. Instead of using a full JSONPath library,
we implement a lightweight subset focused on trace data navigation using
dot notation w... | 333 | 12,173 |
mlflow | mlflow/utils/environment.py | .py | import hashlib
import importlib.metadata
import logging
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
from copy import deepcopy
import yaml
from packaging.requirements import InvalidRequirement, Requirement
from packaging.specifiers import SpecifierSet
from packaging.ver... | 1,128 | 43,175 |
mlflow | mlflow/utils/server_cli_utils.py | .py | """
Utilities for MLflow cli server config validation and resolving.
NOTE: these functions are intended to be used as utilities for the cli click-based interface.
Do not use for any other purpose as the potential Exceptions being raised will be misleading
for users.
"""
import click
from mlflow.environment_variables ... | 95 | 3,591 |
mlflow | mlflow/utils/rest_utils.py | .py | import base64
import contextlib
import json
import logging
import random
import time
import warnings
from contextvars import ContextVar
from functools import lru_cache
from typing import Any, Callable
import requests
from mlflow.environment_variables import (
_MLFLOW_DATABRICKS_TRAFFIC_ID,
_MLFLOW_HTTP_REQUES... | 809 | 31,874 |
mlflow | mlflow/utils/workspace_utils.py | .py | from __future__ import annotations
from mlflow.environment_variables import MLFLOW_WORKSPACE, MLFLOW_WORKSPACE_STORE_URI
_workspace_store_uri: str | None = None
DEFAULT_WORKSPACE_NAME = "default"
WORKSPACES_DIR_NAME = "workspaces"
WORKSPACE_HEADER_NAME = "X-MLFLOW-WORKSPACE"
def _normalize_workspace(workspace: str... | 119 | 3,459 |
mlflow | mlflow/utils/databricks_tracing_utils.py | .py | import logging
from google.protobuf.duration_pb2 import Duration
from google.protobuf.timestamp_pb2 import Timestamp
from mlflow.entities import Assessment, Span, Trace, TraceData, TraceInfo
from mlflow.entities.trace_info_v2 import _truncate_request_metadata, _truncate_tags
from mlflow.entities.trace_location import... | 292 | 11,200 |
mlflow | mlflow/utils/mime_type_utils.py | .py | import os
import pathlib
from mimetypes import guess_type
from mlflow.version import IS_TRACING_SDK_ONLY
# TODO: Create a module to define constants to avoid circular imports
# and move MLMODEL_FILE_NAME and MLPROJECT_FILE_NAME in the module.
def get_text_extensions():
exts = [
"txt",
"log",
... | 59 | 1,409 |
mlflow | mlflow/utils/__init__.py | .py | import importlib.metadata
import inspect
import logging
import socket
import subprocess
import uuid
from contextlib import closing
from itertools import islice
from sys import version_info
from packaging.version import InvalidVersion, Version
PYTHON_VERSION = f"{version_info.major}.{version_info.minor}.{version_info.... | 334 | 10,356 |
mlflow | mlflow/utils/promptlab_utils.py | .py | import json
import os
import tempfile
import time
from datetime import datetime, timezone
from mlflow.entities.param import Param
from mlflow.entities.run_status import RunStatus
from mlflow.entities.run_tag import RunTag
from mlflow.utils.file_utils import make_containing_dirs, write_to
from mlflow.utils.mlflow_tags ... | 147 | 5,598 |
mlflow | mlflow/utils/git_utils.py | .py | import logging
import os
from urllib.parse import urlsplit, urlunsplit
_logger = logging.getLogger(__name__)
def _strip_credentials_from_url(url: str) -> str:
"""
Strip any embedded userinfo (username/password) from a URL so it's safe to record as a tag.
HTTP(S) and similar remotes can carry credentials... | 98 | 3,430 |
mlflow | mlflow/utils/_unity_catalog_utils.py | .py | import logging
from typing import Callable
from mlflow.entities.logged_model_parameter import LoggedModelParameter as ModelParam
from mlflow.entities.metric import Metric
from mlflow.entities.model_registry import (
ModelVersion,
ModelVersionDeploymentJobState,
ModelVersionTag,
RegisteredModel,
Reg... | 497 | 19,713 |
mlflow | mlflow/utils/mlflow_tags.py | .py | """
File containing all of the run tags in the mlflow. namespace.
See the System Tags section in the MLflow Tracking documentation for information on the
meaning of these tags.
"""
MLFLOW_EXPERIMENT_SOURCE_ID = "mlflow.experiment.sourceId"
MLFLOW_EXPERIMENT_SOURCE_TYPE = "mlflow.experiment.sourceType"
MLFLOW_EXPERIME... | 159 | 7,118 |
mlflow | mlflow/utils/logging_utils.py | .py | import contextlib
import logging
import re
import sys
from mlflow.environment_variables import MLFLOW_LOGGING_LEVEL
from mlflow.utils.thread_utils import ThreadLocalVariable
def get_mlflow_log_level() -> str:
"""Returns the log level from MLFLOW_LOGGING_LEVEL env var, defaulting to INFO."""
return (MLFLOW_LO... | 257 | 8,538 |
mlflow | mlflow/utils/databricks_utils.py | .py | import functools
import getpass
import json
import logging
import os
import platform
import re
import subprocess
import time
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, NamedTuple, ParamSpec, TypeVar
from urllib.parse import urlparse
from packaging.version import Version
from ml... | 1,716 | 64,124 |
mlflow | mlflow/utils/search_logged_model_utils.py | .py | import ast
import re
from dataclasses import dataclass
from enum import Enum
import sqlalchemy
import sqlparse
from mlflow.exceptions import MlflowException
from mlflow.store.tracking.dbmodels.models import SqlLoggedModel
from mlflow.utils.search_utils import _join_in_comparison_tokens
class EntityType(Enum):
A... | 127 | 4,245 |
mlflow | mlflow/utils/uv_utils.py | .py | """
Utilities for uv package manager integration.
This module provides functions for detecting uv projects and exporting dependencies
via ``uv export`` for automatic dependency inference during model logging.
"""
import logging
import os
import re
import shutil
import subprocess
from pathlib import Path
from typing i... | 470 | 15,222 |
mlflow | mlflow/utils/gorilla.py | .py | # __ __ __
# .-----.-----.----|__| | .---.-.
# | _ | _ | _| | | | _ |
# |___ |_____|__| |__|__|__|___._|
# |_____|
#
"""
NOTE: The contents of this file have been inlined from the gorilla package's source code
https://github.com/christophercrouzet/gorilla/blob/v0.3.0/gorilla.p... | 798 | 24,049 |
mlflow | mlflow/utils/request_utils.py | .py | # DO NO IMPORT MLFLOW IN THIS FILE.
# This file is imported by download_cloud_file_chunk.py.
# Importing mlflow is time-consuming and we want to avoid that in artifact download subprocesses.
import os
import random
import socket
from functools import lru_cache
import requests
import urllib3
from packaging.version impo... | 325 | 12,039 |
mlflow | mlflow/utils/env_manager.py | .py | from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
LOCAL = "local"
CONDA = "conda"
VIRTUALENV = "virtualenv"
UV = "uv"
def validate(env_manager):
allowed_values = [LOCAL, CONDA, VIRTUALENV, UV]
if env_manager not in allowed_values:
raise Mlf... | 17 | 488 |
mlflow | mlflow/utils/docstring_utils.py | .py | import textwrap
import warnings
from typing import Any
from mlflow.ml_package_versions import _ML_PACKAGE_VERSIONS
from mlflow.utils.autologging_utils.versioning import (
get_min_max_version_and_pip_release,
)
def _create_placeholder(key: str):
return "{{ " + key + " }}"
def _replace_keys_with_placeholders... | 520 | 21,288 |
mlflow | mlflow/utils/file_utils.py | .py | import atexit
import codecs
import errno
import fnmatch
import gzip
import importlib.util
import json
import logging
import math
import os
import pathlib
import posixpath
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.parse
import urllib.request
from conc... | 987 | 32,784 |
mlflow | mlflow/utils/databricks_sql_warehouse.py | .py | """
Helpers for making sure a Databricks SQL warehouse is running before MLflow tracing API calls
that require it.
"""
import logging
import time
from datetime import timedelta
from mlflow.environment_variables import (
MLFLOW_SQL_WAREHOUSE_AUTO_START,
MLFLOW_SQL_WAREHOUSE_AUTO_START_TIMEOUT_SECONDS,
)
from m... | 85 | 3,115 |
mlflow | mlflow/utils/requirements_utils.py | .py | """
This module provides a set of utilities for interpreting and creating requirements files
(e.g. pip's `requirements.txt`), which is useful for managing ML software environments.
"""
import importlib.metadata
import json
import logging
import os
import re
import subprocess
import sys
import tempfile
from itertools i... | 709 | 26,984 |
mlflow | mlflow/utils/download_cloud_file_chunk.py | .py | """
This script should be executed in a fresh python interpreter process using `subprocess`.
"""
import argparse
import importlib.util
import json
import os
import sys
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--range-start", required=True, type=int)
parser.add_argument("-... | 44 | 1,241 |
mlflow | mlflow/utils/conda.py | .py | import hashlib
import json
import logging
import os
import yaml
from mlflow.environment_variables import MLFLOW_CONDA_CREATE_ENV_CMD, MLFLOW_CONDA_HOME
from mlflow.exceptions import ExecutionException
from mlflow.utils import process
from mlflow.utils.environment import Environment
from mlflow.utils.os import is_wind... | 358 | 13,277 |
mlflow | mlflow/utils/_capture_transformers_modules.py | .py | """
This script should be executed in a fresh python interpreter process using `subprocess`.
"""
import json
import os
import sys
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.utils._capture_modules import (
_CaptureImporte... | 76 | 2,584 |
mlflow | mlflow/utils/plugins.py | .py | import importlib.metadata
def _get_entry_points(group: str) -> list[importlib.metadata.EntryPoint]:
return importlib.metadata.entry_points(group=group)
def get_entry_points(group: str) -> list[importlib.metadata.EntryPoint]:
return _get_entry_points(group)
| 10 | 269 |
mlflow | mlflow/utils/yaml_utils.py | .py | import codecs
import os
import shutil
import tempfile
import yaml
from mlflow.utils.file_utils import ENCODING, exists, get_parent_dir
try:
from yaml import CSafeDumper as YamlSafeDumper
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeDumper as YamlSafeDumper
... | 122 | 4,339 |
mlflow | mlflow/utils/server_info.py | .py | from __future__ import annotations
import os
import threading
import time
from collections import OrderedDict
from dataclasses import dataclass, field
from typing import Any
from mlflow.utils.rest_utils import MlflowHostCreds, http_request
SERVER_INFO_ENDPOINT = "/api/3.0/mlflow/server-info"
SERVER_INFO_STORE_TYPE ... | 154 | 4,769 |
mlflow | mlflow/utils/checkpoint_utils.py | .py | import logging
import os
import posixpath
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.utils.autologging_utils import (
ExceptionSafeAbstractClass,
)
from mlflow.utils.file_utils import TempDir
from mlflow.utils.mlflow_tags import LATEST_CHECKPOINT_ARTIFACT_TAG_KEY
_logger = logging.get... | 207 | 8,591 |
mlflow | mlflow/utils/time.py | .py | import datetime
import time
def get_current_time_millis():
"""
Returns the time in milliseconds since the epoch as an integer number.
"""
return int(time.time() * 1000)
def conv_longdate_to_str(longdate, local_tz=True):
date_time = datetime.datetime.fromtimestamp(longdate / 1000.0)
str_long_... | 54 | 1,260 |
mlflow | mlflow/utils/cli_args.py | .py | """
Definitions of click options shared by several CLI commands.
"""
import warnings
import click
from mlflow.environment_variables import MLFLOW_DISABLE_ENV_MANAGER_CONDA_WARNING
from mlflow.utils import env_manager as _EnvManager
MODEL_PATH = click.option(
"--model-path",
"-m",
default=None,
metav... | 302 | 10,406 |
mlflow | mlflow/utils/annotations.py | .py | import inspect
import re
import types
import warnings
from functools import wraps
from typing import Callable, ParamSpec, TypeVar, overload
def _get_min_indent_of_docstring(docstring_str: str) -> str:
"""
Get the minimum indentation string of a docstring, based on the assumption
that the closing triple qu... | 339 | 11,558 |
mlflow | mlflow/utils/proto_json_utils.py | .py | import base64
import datetime
import importlib
import json
import os
from collections import defaultdict
from copy import deepcopy
from functools import partial
from json import JSONEncoder
from typing import Any
import pydantic
from google.protobuf.descriptor import FieldDescriptor
from google.protobuf.duration_pb2 i... | 736 | 28,650 |
mlflow | mlflow/utils/_capture_modules.py | .py | """
This script should be executed in a fresh python interpreter process using `subprocess`.
"""
import argparse
import builtins
import functools
import importlib
import json
import os
import sys
import mlflow
from mlflow.models.model import MLMODEL_FILE_NAME, Model
from mlflow.pyfunc import MAIN
from mlflow.utils._s... | 260 | 10,270 |
mlflow | mlflow/utils/workspace_context.py | .py | from __future__ import annotations
from contextvars import ContextVar, Token
from mlflow.environment_variables import MLFLOW_WORKSPACE
from mlflow.utils.workspace_utils import DEFAULT_WORKSPACE_NAME
_WORKSPACE: ContextVar[str | None] = ContextVar("mlflow_active_workspace", default=None)
_IS_WORKSPACE_RESOLVED: Conte... | 126 | 4,110 |
mlflow | mlflow/utils/semver_utils.py | .py | from __future__ import annotations
import re
from dataclasses import dataclass
from mlflow.exceptions import MlflowException
# Keep this SemVer-specific implementation instead of ``packaging.Version``:
# MLflow needs SemVer 2.0.0 precedence, while ``packaging.Version`` implements
# PEP 440 and would normalize or rej... | 178 | 6,892 |
mlflow | mlflow/utils/nfs_on_spark.py | .py | import os
import shutil
import uuid
from mlflow.utils._spark_utils import _get_active_spark_session
from mlflow.utils.databricks_utils import (
get_databricks_nfs_temp_dir,
is_databricks_connect,
is_in_databricks_runtime,
is_in_databricks_serverless_runtime,
)
# Set spark config "spark.mlflow.nfs.root... | 63 | 2,698 |
mlflow | mlflow/utils/credentials.py | .py | import configparser
import getpass
import logging
import os
from typing import NamedTuple
from mlflow.environment_variables import (
MLFLOW_TRACKING_AUTH,
MLFLOW_TRACKING_AWS_SIGV4,
MLFLOW_TRACKING_CLIENT_CERT_PATH,
MLFLOW_TRACKING_INSECURE_TLS,
MLFLOW_TRACKING_PASSWORD,
MLFLOW_TRACKING_SERVER_... | 241 | 8,692 |
mlflow | mlflow/utils/model_utils.py | .py | import contextlib
import json
import logging
import os
import shutil
import sys
from pathlib import Path
from typing import Any
import yaml
from mlflow.exceptions import MlflowException
from mlflow.models import Model
from mlflow.models.model import MLMODEL_FILE_NAME
from mlflow.protos.databricks_pb2 import (
INV... | 536 | 20,851 |
mlflow | mlflow/utils/os.py | .py | import os
def is_windows():
"""
Returns true if the local system/OS name is Windows.
Returns:
True if the local system/OS name is Windows.
"""
return os.name == "nt"
| 13 | 198 |
mlflow | mlflow/utils/warnings_utils.py | .py | import warnings
# ANSI escape code
ANSI_BASE = "\033["
COLORS = {
"default_bold": f"{ANSI_BASE}1m",
"red": f"{ANSI_BASE}31m",
"red_bold": f"{ANSI_BASE}1;31m",
"yellow": f"{ANSI_BASE}33m",
"yellow_bold": f"{ANSI_BASE}1;33m",
"blue": f"{ANSI_BASE}34m",
"blue_bold": f"{ANSI_BASE}1;34m",
}
RESE... | 26 | 627 |
mlflow | mlflow/utils/providers.py | .py | import functools
import importlib.resources
import json
import logging
import urllib.parse
import urllib.request
from collections.abc import Iterator
from pathlib import Path
from typing import TypedDict
import cachetools
from typing_extensions import NotRequired
from mlflow.environment_variables import MLFLOW_MODEL_... | 1,077 | 38,760 |
mlflow | mlflow/utils/uri.py | .py | import os
import pathlib
import posixpath
import re
import urllib.parse
import uuid
from typing import Any
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.utils.os import is_windows
from mlflow.utils.validation import _validate_db_type_string
... | 613 | 22,625 |
mlflow | mlflow/utils/arguments_utils.py | .py | import inspect
def _get_arg_names(f):
"""Get the argument names of a function.
Args:
f: A function.
Returns:
A list of argument names.
"""
# `inspect.getargspec` or `inspect.getfullargspec` doesn't work properly for a wrapped function.
# See https://hynek.me/articles/decorat... | 17 | 412 |
mlflow | mlflow/utils/validation.py | .py | """
Utilities for validating user inputs such as metric names and parameter names.
"""
import ipaddress
import json
import logging
import numbers
import posixpath
import re
import socket
import threading
import urllib.parse
from fnmatch import fnmatch
from typing import Any
from mlflow.entities import Dataset, Datase... | 1,203 | 44,967 |
mlflow | mlflow/utils/doctor.py | .py | import os
import platform
import click
import importlib_metadata
import yaml
from packaging.requirements import Requirement
import mlflow
from mlflow.utils.databricks_utils import get_databricks_runtime_version
def doctor(mask_envs=False):
"""Prints out useful information for debugging issues with MLflow.
... | 124 | 3,892 |
mlflow | mlflow/utils/crypto.py | .py | import json
import logging
import os
from dataclasses import dataclass
from typing import Any
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
# KEK (Key Encryption Key) environment variables for envelope encryption
# These are defined here to avoid import... | 651 | 24,824 |
mlflow | mlflow/utils/provider_filter.py | .py | import logging
import threading
from cachetools import LRUCache
from cachetools.func import cached
from mlflow.environment_variables import MLFLOW_GATEWAY_ALLOWED_PROVIDERS
_logger = logging.getLogger(__name__)
# Single source of truth for provider name aliases (string-level).
_PROVIDER_ALIASES: dict[str, str] = {
... | 63 | 1,804 |
mlflow | mlflow/utils/data_utils.py | .py | import urllib.parse
from typing import Any
def parse_s3_uri(uri):
"""Parse an S3 URI, returning (bucket, path)"""
parsed = urllib.parse.urlparse(uri)
if parsed.scheme != "s3":
raise Exception(f"Not an S3 URI: {uri}")
path = parsed.path
path = path.removeprefix("/")
return parsed.netloc... | 27 | 609 |
mlflow | mlflow/utils/openai_utils.py | .py | import os
import time
from enum import Enum
from typing import NamedTuple
import mlflow
REQUEST_URL_CHAT = "https://api.openai.com/v1/chat/completions"
REQUEST_URL_COMPLETIONS = "https://api.openai.com/v1/completions"
REQUEST_URL_EMBEDDINGS = "https://api.openai.com/v1/embeddings"
REQUEST_FIELDS_CHAT = {
"model"... | 165 | 5,215 |
mlflow | mlflow/utils/async_logging/async_logging_queue.py | .py | """
Defines an AsyncLoggingQueue that provides async fashion logging of metrics/tags/params using
queue based approach.
"""
import atexit
import enum
import logging
import threading
from concurrent.futures import ThreadPoolExecutor
from queue import Empty, Queue
from typing import Callable
from mlflow.entities.metric... | 367 | 14,279 |
mlflow | mlflow/utils/async_logging/run_artifact.py | .py | import threading
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
import PIL
class RunArtifact:
def __init__(
self,
filename: str,
artifact_path: str,
artifact: Union["PIL.Image.Image"],
completion_event: threading.Event,
) -> None:
"""Initializes ... | 39 | 1,074 |
mlflow | mlflow/utils/async_logging/run_batch.py | .py | import threading
from mlflow.entities.metric import Metric
from mlflow.entities.param import Param
from mlflow.entities.run_tag import RunTag
class RunBatch:
def __init__(
self,
run_id: str,
params: list["Param"] | None = None,
tags: list["RunTag"] | None = None,
metrics: ... | 58 | 1,802 |
mlflow | mlflow/utils/async_logging/run_operations.py | .py | class RunOperations:
"""Class that helps manage the futures of MLflow async logging."""
def __init__(self, operation_futures):
self._operation_futures = operation_futures or []
def wait(self):
"""Blocks on completion of all futures."""
from mlflow.exceptions import MlflowException
... | 50 | 1,944 |
mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | .py | """
Defines an AsyncArtifactsLoggingQueue that provides async fashion artifact writes using
queue based approach.
"""
import atexit
import logging
import threading
from concurrent.futures import ThreadPoolExecutor
from queue import Empty, Queue
from typing import TYPE_CHECKING, Callable, Union
from mlflow.utils.async... | 259 | 9,993 |
mlflow | mlflow/utils/import_hooks/__init__.py | .py | """
NOTE: The contents of this file have been inlined from the wrapt package's source code
https://github.com/GrahamDumpleton/wrapt/blob/1.12.1/src/wrapt/importer.py.
Some modifications, have been made in order to:
- avoid duplicate registration of import hooks
- inline functions from dependent wrapt submodules... | 358 | 13,321 |
mlflow | mlflow/utils/autologging_utils/metrics_queue.py | .py | import concurrent.futures
from threading import RLock
from mlflow.entities import Metric
from mlflow.tracking.client import MlflowClient
_metrics_queue_lock = RLock()
_metrics_queue = []
_thread_pool = concurrent.futures.ThreadPoolExecutor(
max_workers=1, thread_name_prefix="MlflowMetricsQueue"
)
_MAX_METRIC_QUE... | 74 | 2,739 |
mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | .py | import os
import warnings
from pathlib import Path
from threading import RLock
from threading import get_ident as get_current_thread_id
import mlflow
from mlflow.utils import logging_utils
class _WarningsController:
"""
Provides threadsafe utilities to modify warning behavior for MLflow autologging, includin... | 329 | 14,328 |
mlflow | mlflow/utils/autologging_utils/__init__.py | .py | import contextlib
import importlib
import importlib.metadata
import inspect
import logging
import threading
import time
from typing import Any, Callable
import mlflow
from mlflow.entities import Metric
from mlflow.utils.validation import MAX_METRICS_PER_BATCH
# Define the module-level logger for autologging utilities... | 725 | 29,613 |
mlflow | mlflow/utils/autologging_utils/safety.py | .py | import abc
import functools
import inspect
import itertools
import uuid
from contextlib import asynccontextmanager, contextmanager
from typing import Any, Callable, NamedTuple
import mlflow
import mlflow.utils.autologging_utils
from mlflow.entities.run_status import RunStatus
from mlflow.environment_variables import _... | 1,158 | 53,597 |
mlflow | mlflow/utils/autologging_utils/client.py | .py | """
Defines an MlflowAutologgingQueueingClient developer API that provides batching, queueing, and
asynchronous execution capabilities for a subset of MLflow Tracking logging operations used most
frequently by autologging operations.
TODO(dbczumar): Migrate request batching, queueing, and async execution support from
... | 437 | 16,877 |
mlflow | mlflow/utils/autologging_utils/config.py | .py | import logging
from dataclasses import dataclass
from typing import Any
from mlflow.utils.autologging_utils import AUTOLOGGING_INTEGRATIONS
_logger = logging.getLogger(__name__)
@dataclass
class AutoLoggingConfig:
"""
A dataclass to hold common autologging configuration options.
"""
log_input_examp... | 34 | 1,099 |
mlflow | mlflow/utils/autologging_utils/versioning.py | .py | import importlib
import importlib.metadata
import re
from typing import Literal
from packaging.version import InvalidVersion, Version
from mlflow.ml_package_versions import _ML_PACKAGE_VERSIONS, FLAVOR_TO_MODULE_NAME
from mlflow.utils.databricks_utils import is_in_databricks_runtime
def _check_version_in_range(ver,... | 111 | 4,540 |
mlflow | mlflow/utils/autologging_utils/events.py | .py | import warnings
from typing import Any
from mlflow.utils.autologging_utils import _logger
def _catch_exception(fn):
"""A decorator that catches exceptions thrown by the wrapped function and logs them."""
def wrapper(*args):
try:
fn(*args)
except Exception as e:
_logge... | 295 | 13,155 |
mlflow | mlflow/pyspark/__init__.py | .py | from mlflow.pyspark import ml
__all__ = ["ml"]
| 4 | 48 |
mlflow | mlflow/pyspark/optuna/study.py | .py | import datetime
import logging
import tempfile
import traceback
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import optuna
import pandas as pd
from optuna import exceptions, pruners, samplers, storages
from optuna.study impor... | 431 | 17,775 |
mlflow | mlflow/pyspark/ml/__init__.py | .py | import importlib.resources
import json
import logging
import os
import traceback
import weakref
from collections import OrderedDict, defaultdict
from itertools import zip_longest
from typing import Any, NamedTuple
from urllib.parse import urlparse
import numpy as np
import mlflow
from mlflow.data.code_dataset_source ... | 1,263 | 55,595 |
mlflow | mlflow/pyspark/ml/_autolog.py | .py | import re
from functools import reduce
try:
# For spark >= 4.0
from pyspark.errors.exceptions.base import IllegalArgumentException
except ModuleNotFoundError:
from pyspark.sql.utils import IllegalArgumentException
from pyspark.ml.base import Transformer
from pyspark.ml.functions import vector_to_array
from... | 97 | 3,068 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.