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
tests/autologging/test_autologging_safety_unit.py
.py
import abc import copy import inspect from contextlib import nullcontext as does_not_raise from typing import Any, NamedTuple from unittest import mock import pytest import mlflow from mlflow import MlflowClient from mlflow.entities import RunStatus from mlflow.utils import autologging_utils from mlflow.utils.autolog...
1,686
56,729
mlflow
tests/autologging/test_autologging_behaviors_unit.py
.py
import logging import sys import threading import time import warnings from concurrent.futures import ThreadPoolExecutor from io import StringIO import numpy as np import pytest import mlflow from mlflow.utils.autologging_utils import autologging_integration, safe_patch from mlflow.utils.logging_utils import eprint ...
352
13,139
mlflow
tests/autologging/fixtures.py
.py
import os import sys import pytest from mlflow.environment_variables import _MLFLOW_AUTOLOGGING_TESTING from mlflow.utils import logging_utils from mlflow.utils.autologging_utils import is_testing PATCH_DESTINATION_FN_DEFAULT_RESULT = "original_result" # Fixture to run the test case with and without async logging ...
118
3,324
mlflow
tests/autologging/test_training_session.py
.py
import pytest from mlflow.utils.autologging_utils import _get_new_training_session_class _TrainingSession = _get_new_training_session_class() class Parent: pass class Child: pass class Grandchild: pass PARENT = Parent() CHILD = Child() GRAND_CHILD = Grandchild() @pytest.fixture(autouse=True) def...
122
3,630
mlflow
tests/autologging/async_helper.py
.py
import asyncio import inspect from concurrent.futures import ThreadPoolExecutor from mlflow.utils.autologging_utils.safety import update_wrapper_extended def asyncify(is_async): """ Decorator that converts a function to an async function if `is_async` is True. This is useful for testing purposes, where w...
45
1,696
mlflow
tests/autologging/test_autologging_behaviors_integration.py
.py
import importlib import logging import sys import warnings from concurrent.futures import ThreadPoolExecutor from io import StringIO from itertools import permutations from unittest import mock import pytest import mlflow from mlflow import MlflowClient from mlflow.utils import gorilla from mlflow.utils.autologging_u...
335
11,961
mlflow
tests/autologging/test_autologging_client.py
.py
import time from unittest import mock import pytest import mlflow from mlflow import MlflowClient from mlflow.exceptions import MlflowException from mlflow.utils import _truncate_dict from mlflow.utils.autologging_utils import MlflowAutologgingQueueingClient from mlflow.utils.validation import ( MAX_ENTITY_KEY_LE...
272
10,603
mlflow
tests/autologging/test_autologging_utils.py
.py
import importlib import inspect import sys import time from typing import Any, NamedTuple from unittest import mock import pytest import mlflow from mlflow import MlflowClient from mlflow.ml_package_versions import FLAVOR_TO_MODULE_NAME from mlflow.utils import gorilla from mlflow.utils.autologging_utils import ( ...
945
34,883
mlflow
tests/llama_index/test_llama_index_autolog.py
.py
from importlib import metadata from unittest import mock import pytest from llama_index.core.chat_engine.types import ChatMode from llama_index.core.instrumentation import get_dispatcher from llama_index.core.instrumentation.event_handlers.base import BaseEventHandler from llama_index.core.instrumentation.span_handler...
388
12,937
mlflow
tests/llama_index/test_llama_index_pyfunc_wrapper.py
.py
import llama_index.core import numpy as np import pandas as pd import pytest from llama_index.core import QueryBundle from llama_index.core.llms import ChatMessage from packaging.version import Version import mlflow from mlflow.llama_index.pyfunc_wrapper import ( _CHAT_MESSAGE_HISTORY_PARAMETER_NAME, CHAT_ENGI...
324
10,712
mlflow
tests/llama_index/test_llama_index_node_conversion.py
.py
from llama_index.core.schema import NodeWithScore, TextNode from mlflow.entities import Document def test_from_llama_index_node_with_score(): text_node = TextNode(text="Hello", metadata={"key": "value"}) node_with_score = NodeWithScore(node=text_node, score=0.5) document = Document.from_llama_index_node_...
13
505
mlflow
tests/llama_index/test_llama_index_evaluate.py
.py
import pandas as pd import pytest import mlflow from mlflow.metrics import latency from mlflow.tracing.constant import TraceMetadataKey from tests.openai.test_openai_evaluate import purge_traces from tests.tracing.helper import get_traces, reset_autolog_state # noqa: F401 _EVAL_DATA = pd.DataFrame({ "inputs": [...
113
3,552
mlflow
tests/llama_index/test_llama_index_serialization.py
.py
import json from collections import Counter, deque from unittest import mock import pytest from llama_index.core import PromptTemplate, Settings from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms.openai import OpenAI from mlflow.llama_index.serialize_objects import ( _construct_prompt...
151
5,419
mlflow
tests/llama_index/test_llama_index_model_export.py
.py
import json import os from pathlib import Path from typing import Any from unittest import mock import llama_index.core import numpy as np import pandas as pd import pytest from llama_index.core import QueryBundle, Settings, VectorStoreIndex from llama_index.core.base.base_query_engine import BaseQueryEngine from llam...
603
21,559
mlflow
tests/llama_index/test_llama_index_tracer.py
.py
import asyncio import base64 import inspect import random from dataclasses import asdict from importlib import metadata from pathlib import Path from typing import Any from unittest.mock import ANY import llama_index.core import openai import pytest from llama_index.core import Settings from llama_index.core.base.resp...
911
32,719
mlflow
tests/llama_index/conftest.py
.py
import os import re import shutil import sys import pytest from llama_index.core import ( Document, KnowledgeGraphIndex, PromptTemplate, Settings, VectorStoreIndex, ) from llama_index.core.callbacks import CallbackManager, LlamaDebugHandler from llama_index.core.node_parser import SentenceSplitter ...
120
3,315
mlflow
tests/llama_index/sample_code/with_model_config.py
.py
""" Sample code to define a chat engine and save it with model config (dictionary). """ from llama_index.core import Document, VectorStoreIndex from llama_index.core.chat_engine.types import ChatMode from llama_index.llms.openai import OpenAI import mlflow model_config = mlflow.models.ModelConfig() model_name = mode...
21
698
mlflow
tests/llama_index/sample_code/query_engine_with_reranker.py
.py
""" Sample code to define a query engine with post processors and save it with model-from-code logging. Ref: https://qdrant.tech/documentation/quickstart/ """ from llama_index.core import Document, QueryBundle, VectorStoreIndex from llama_index.core.postprocessor import LLMRerank from llama_index.core.postprocessor.t...
42
1,093
mlflow
tests/llama_index/sample_code/basic_retriever.py
.py
from llama_index.core import Document, VectorStoreIndex import mlflow index = VectorStoreIndex.from_documents(documents=[Document.example()]) retriever = index.as_retriever() mlflow.models.set_model(retriever)
9
213
mlflow
tests/llama_index/sample_code/external_vector_store.py
.py
""" Sample code to define an index using an external vector store (Faiss) for model-from-code logging. Ref: https://qdrant.tech/documentation/quickstart/ """ from llama_index.core import VectorStoreIndex from llama_index.vector_stores.qdrant import QdrantVectorStore from qdrant_client import QdrantClient from qdrant_...
37
1,078
mlflow
tests/llama_index/sample_code/basic_vector_store.py
.py
from llama_index.core import Document, VectorStoreIndex import mlflow index = VectorStoreIndex.from_documents(documents=[Document.example()]) mlflow.models.set_model(index)
8
176
mlflow
tests/llama_index/sample_code/basic_chat_engine.py
.py
""" Sample code to define a chat engine and save it with model-from-code logging. Ref: https://qdrant.tech/documentation/quickstart/ """ from llama_index.core import Document, VectorStoreIndex from llama_index.core.chat_engine.types import ChatMode import mlflow index = VectorStoreIndex.from_documents(documents=[Do...
17
506
mlflow
tests/llama_index/sample_code/with_model_config_yaml_file.py
.py
""" Sample code to define a chat engine and save it with model config (YAML file). """ from llama_index.core import Document, VectorStoreIndex from llama_index.core.chat_engine.types import ChatMode from llama_index.llms.openai import OpenAI import mlflow model_config = mlflow.models.ModelConfig(development_config="...
22
768
mlflow
tests/llama_index/sample_code/simple_workflow.py
.py
from llama_index.core.workflow import ( Event, StartEvent, StopEvent, Workflow, step, ) from llama_index.llms.openai import OpenAI import mlflow class JokeEvent(Event): joke: str class JokeFlow(Workflow): llm = OpenAI() @step async def generate_joke(self, ev: StartEvent) -> Jok...
38
860
mlflow
examples/johnsnowlabs/export.py
.py
import json import os import pandas as pd from johnsnowlabs import nlp import mlflow from mlflow.pyfunc import spark_udf # 1) Write your raw license.json string into the 'JOHNSNOWLABS_LICENSE_JSON' env variable for MLflow creds = { "AWS_ACCESS_KEY_ID": "...", "AWS_SECRET_ACCESS_KEY": "...", "SPARK_NLP_LI...
53
1,596
mlflow
examples/spark_udf/structs_and_arrays.py
.py
from pyspark.sql import SparkSession from pyspark.sql import types as T import mlflow class MyModel(mlflow.pyfunc.PythonModel): def predict(self, context, model_input): return [str(" | ".join(map(str, row))) for _, row in model_input.iterrows()] def main(): with SparkSession.builder.getOrCreate() a...
68
1,868
mlflow
examples/spark_udf/spark_udf_datetime.py
.py
import datetime import random from pyspark.sql import SparkSession from sklearn.compose import ColumnTransformer from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from sklearn.preprocessing import FunctionTransformer import mlflow def pri...
68
2,221
mlflow
examples/spark_udf/spark_udf.py
.py
from pyspark.sql import SparkSession from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier import mlflow from mlflow.models import infer_signature with SparkSession.builder.getOrCreate() as spark: X, y = datasets.load_iris(as_frame=True, return_X_y=True) model = KNeighborsClassifier(...
24
792
mlflow
examples/spark_udf/spark_udf_with_prebuilt_env.py
.py
""" This example code shows how to use `mlflow.pyfunc.spark_udf` with Databricks Connect outside Databricks runtime. """ import os from databricks.connect import DatabricksSession from databricks.sdk import WorkspaceClient from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier import mlflow ...
45
1,465
mlflow
examples/spacy/train.py
.py
import random import spacy from packaging.version import Version from spacy.training import Example from spacy.util import compounding, minibatch import mlflow.spacy IS_SPACY_VERSION_NEWER_THAN_OR_EQUAL_TO_3_0_0 = Version(spacy.__version__).major >= 3 # training data TRAIN_DATA = [ ("Who is Shaka Khan?", {"enti...
66
2,246
mlflow
examples/quickstart/mlflow_tracking.py
.py
import os from random import randint, random from mlflow import log_artifacts, log_metric, log_param if __name__ == "__main__": print("Running mlflow_tracking.py") log_param("param1", randint(0, 100)) log_metric("foo", random()) log_metric("foo", random() + 1) log_metric("foo", random() + 2) ...
21
494
mlflow
examples/gemini/tracing.py
.py
""" This is an example for leveraging MLflow's auto tracing capabilities for Gemini. For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html """ import os import mlflow # Turn on auto tracing for Gemini by calling mlflow.gemini.autolog() mlflow.gemini.autolog() # Impo...
40
1,328
mlflow
examples/sklearn_elasticnet_wine/train.py
.py
# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality # P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. # Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009. import logging import sys i...
93
3,286
mlflow
examples/pyspark_ml_autologging/pipeline.py
.py
from pyspark.ml import Pipeline from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import StandardScaler, VectorAssembler from pyspark.sql import SparkSession from sklearn.datasets import load_iris import mlflow with SparkSession.builder.getOrCreate() as spark: mlflow.pyspark.ml.auto...
34
1,250
mlflow
examples/pyspark_ml_autologging/logistic_regression.py
.py
from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import VectorAssembler from pyspark.sql import SparkSession from sklearn.datasets import load_iris import mlflow with SparkSession.builder.getOrCreate() as spark: df = load_iris(as_frame=True).frame.rename(columns={"target": "label"}...
22
718
mlflow
examples/pyspark_ml_autologging/one_vs_rest.py
.py
from pyspark.ml.classification import LogisticRegression, OneVsRest from pyspark.ml.feature import VectorAssembler from pyspark.sql import SparkSession from sklearn.datasets import load_iris import mlflow with SparkSession.builder.getOrCreate() as spark: df = load_iris(as_frame=True).frame.rename(columns={"target...
23
765
mlflow
examples/ray_serve/train_model.py
.py
from sklearn.datasets import load_iris from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import mean_squared_error from sklearn.utils import shuffle import mlflow if __name__ == "__main__": # Enable auto-logging mlflow.set_tracking_uri("sqlite:///mlruns.db") mlflow.sklearn.autol...
42
1,252
mlflow
examples/strands/tracing.py
.py
import mlflow mlflow.strands.autolog() mlflow.set_experiment("Strand Agent") from strands import Agent from strands.models.openai import OpenAIModel from strands_tools import calculator model = OpenAIModel( client_args={"api_key": "<api-key>"}, # **model_config model_id="gpt-4o", params={ "ma...
23
470
mlflow
examples/diffusers/demo_diffusers_adapter.py
.py
""" Demo: MLflow Diffusers Adapter Flavor (LoRA) This script demonstrates the full workflow of logging and loading a diffusion model LoRA adapter using the native mlflow.diffusers flavor. No GPU or real model weights required — uses a fake adapter for validation. """ import tempfile from pathlib import Path import ...
114
4,203
mlflow
examples/tracing/multithreading.py
.py
""" This example demonstrates how to create a trace to track the execution of a multi-threaded application. To trace a multi-threaded operation, you need to use the low-level MLflow client APIs to create a trace and spans, because the high-level fluent APIs are not thread-safe. """ import contextvars from concurrent....
65
1,818
mlflow
examples/tracing/langchain_auto.py
.py
""" This example demonstrates how to enable automatic tracing for LangChain. Note: this example requires the `langchain` and `langchain-openai` package to be installed. """ import json import os from langchain.prompts import PromptTemplate from langchain.schema.output_parser import StrOutputParser from langchain_ope...
51
1,810
mlflow
examples/tracing/client.py
.py
""" This example demonstrates how to create a trace with multiple spans using the low-level MLflow client APIs. """ import mlflow exp = mlflow.set_experiment("mlflow-tracing-example") exp_id = exp.experiment_id # Initialize MLflow client. client = mlflow.MlflowClient() def run(x: int, y: int) -> int: # Create ...
102
2,995
mlflow
examples/tracing/fluent.py
.py
""" This example demonstrates how to create a trace with multiple spans using the high-level MLflow fluent APIs. """ import mlflow mlflow.set_experiment("mlflow-tracing-example") # Decorating the function with `@mlflow.trace` decorator is the easiest way to trace your function. # MLflow will create a trace for func...
59
1,705
mlflow
examples/pytorch/mnist_tensorboard_artifact.py
.py
# # Trains an MNIST digit recognizer using PyTorch, and uses tensorboardX to log training metrics # and weights in TensorBoard event format to the MLflow run's artifact directory. This stores the # TensorBoard events in MLflow for later access using the TensorBoard command line tool. # # NOTE: This example requires you...
253
8,353
mlflow
examples/pytorch/torchscript/IrisClassification/iris_classification.py
.py
import argparse import torch import torch.nn.functional as F from sklearn.datasets import load_iris from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from torch import nn import mlflow.pytorch from mlflow.models import infer_signature class IrisClassifier(nn.Module): ...
106
3,339
mlflow
examples/pytorch/torchscript/MNIST/mnist_torchscript.py
.py
import argparse import torch import torch.nn.functional as F from torch import nn, optim from torch.optim.lr_scheduler import StepLR from torchvision import datasets, transforms import mlflow import mlflow.pytorch class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2...
197
6,202
mlflow
examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py
.py
""" Getting started with Captum - Titanic Data Analysis """ # Initial imports import os from argparse import ArgumentParser import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from captum.attr import IntegratedGradients, LayerConductance, NeuronConductance from prettytable import Prett...
347
14,340
mlflow
examples/pytorch/HPOExample/hpo_mnist.py
.py
""" Hyperparameter Optimization Example with Pure PyTorch and MLflow This example demonstrates: - Using MLflow to track hyperparameter optimization trials - Parent/child run structure for organizing HPO experiments - Pure PyTorch training (no Lightning dependencies) - Simple MNIST classification with configurable hype...
158
5,410
mlflow
examples/pytorch/MNIST/mnist_autolog_example.py
.py
# # Trains an MNIST digit recognizer using PyTorch Lightning, # and uses MLflow to log metrics, params and artifacts # NOTE: This example requires you to first install # pytorch-lightning (using pip install pytorch-lightning) # and mlflow (using pip install mlflow). # import os import lightning as L import tor...
261
7,388
mlflow
examples/multistep_workflow/etl_data.py
.py
""" Converts the raw CSV form to a Parquet form with just the columns we want """ import os import tempfile import click import pyspark import mlflow @click.command( help="Given a CSV file (see load_raw_data), transforms it into Parquet " "in an mlflow artifact called 'ratings-parquet-dir'" ) @click.option...
45
1,412
mlflow
examples/multistep_workflow/main.py
.py
""" Downloads the MovieLens dataset, ETLs it into Parquet, trains an ALS model, and uses the ALS model to train a Keras neural network. See README.md for more details. """ import os import click import mlflow from mlflow.entities import RunStatus from mlflow.tracking import MlflowClient from mlflow.tracking.fluent ...
108
4,405
mlflow
examples/multistep_workflow/load_raw_data.py
.py
""" Downloads the MovieLens dataset and saves it as an artifact """ import os import tempfile import zipfile import click import requests import mlflow @click.command( help="Downloads the MovieLens dataset and saves it as an mlflow artifact " "called 'ratings-csv-dir'." ) @click.option("--url", default="ht...
44
1,292
mlflow
examples/multistep_workflow/als.py
.py
""" Trains an Alternating Least Squares (ALS) model for user/movie ratings. The input is a Parquet ratings dataset (see etl_data.py), and we output an mlflow artifact called 'als-model'. """ import click import pyspark from pyspark.ml import Pipeline from pyspark.ml.evaluation import RegressionEvaluator from pyspark.m...
71
2,369
mlflow
examples/multistep_workflow/train_keras.py
.py
""" Trains a Keras model for user/movie ratings. The input is a Parquet ratings dataset (see etl_data.py) and an ALS model (see als.py), which we will use to supplement our input and train using. """ from itertools import chain import click import numpy as np import pandas as pd import pyspark import tensorflow as tf...
118
4,436
mlflow
examples/demos/mlflow-3/genai.py
.py
# MLflow 3 GenAI Example # In this example, we will create an agent and then evaluate its performance. First, we will define the agent and log it to MLflow. from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI import mlflow # Define the chain chat_model = ChatOpenAI(name="gpt...
47
1,955
mlflow
examples/demos/mlflow-3/ml.py
.py
# MLflow 3 Traditional ML Example # In this example, we will first run a model training job, which is tracked as # an MLflow Run, to produce a trained model, which is tracked as an MLflow Logged Model. import pandas as pd from sklearn.datasets import load_iris from sklearn.linear_model import ElasticNet from sklearn.me...
114
4,450
mlflow
examples/demos/mlflow-3/deep_learning.py
.py
# # MLflow 3 Deep Learning Example # In this example, we will first run a model training job, which is tracked as an MLflow Run. # Every 10 epochs, we will store model checkpoints, which are tracked as MLflow Logged Models. # We will then select the best checkpoint for production deployment. import pandas as pd import ...
126
4,575
mlflow
examples/databricks/multipart.py
.py
""" Benchmark for multi-part upload and download of artifacts. """ import hashlib import json import os import pathlib import tempfile from concurrent.futures import ThreadPoolExecutor, as_completed import pandas as pd import psutil from tqdm.auto import tqdm import mlflow from mlflow.environment_variables import ( ...
149
4,167
mlflow
examples/databricks/dbconnect.py
.py
""" python examples/databricks/dbconnect.py --cluster-id <cluster-id> """ import argparse from databricks.connect import DatabricksSession from databricks.sdk import WorkspaceClient from pyspark.sql.types import DoubleType from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier import mlflow ...
57
1,532
mlflow
examples/databricks/log_runs.py
.py
""" Logs MLflow runs in Databricks from an external host. How to run: $ python examples/databricks/log_runs.py --host <host> --token <token> --user <user> [--experiment-id 123] See also: https://docs.databricks.com/dev-tools/api/latest/authentication.html#generate-a-personal-access-token """ import argparse import o...
57
1,756
mlflow
examples/paddle/train_high_level_api.py
.py
import numpy as np import paddle import mlflow.paddle train_dataset = paddle.text.datasets.UCIHousing(mode="train") eval_dataset = paddle.text.datasets.UCIHousing(mode="test") class UCIHousing(paddle.nn.Layer): def __init__(self): super().__init__() self.fc_ = paddle.nn.Linear(13, 1, None) ...
35
965
mlflow
examples/paddle/train_low_level_api.py
.py
import numpy as np import paddle import paddle.nn.functional as F from paddle.nn import Linear from sklearn import preprocessing from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split import mlflow.paddle def load_data(): X, y = load_diabetes(return_X_y=True) min_max...
82
2,542
mlflow
examples/ag2/tracing.py
.py
""" This is an example for leveraging MLflow's auto tracing capabilities for AutoGen. For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html """ import os from typing import Annotated, Literal from autogen import ConversableAgent import mlflow # Turn on auto tracing ...
64
1,913
mlflow
examples/langchain/retrieval_qa_chain_azure_openai.py
.py
import os import tempfile from langchain.chains import RetrievalQA from langchain.document_loaders import TextLoader from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import FAISS from langchain_openai import AzureOpenAI, AzureOpenAIEmbeddings import mlflow # Set this to `azure` o...
64
2,472
mlflow
examples/langchain/chain_as_code_driver.py
.py
# This is an example for logging a Langchain model from code using the # mlflow.langchain.log_model API. When a path to a valid Python script is submitted to the # lc_model argument, the model code itself is serialized instead of the model object. # Within the targeted script, the model implementation must be defined a...
40
1,267
mlflow
examples/langchain/retriever_chain.py
.py
import os import tempfile from langchain.document_loaders import TextLoader from langchain.embeddings.openai import OpenAIEmbeddings from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import FAISS import mlflow assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY e...
43
1,620
mlflow
examples/langchain/chain_autolog.py
.py
import os from operator import itemgetter from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.schema.output_parser import StrOutputParser from langchain.schema.runnable import RunnableLambda import mlflow # Uncomment the following to use the full abilities of langchain autol...
71
2,122
mlflow
examples/langchain/chain_as_code.py
.py
# This example demonstrates defining a model directly from code. # This feature allows for defining model logic within a python script, module, or notebook that is stored # directly as serialized code, as opposed to object serialization that would otherwise occur when saving # or logging a model object. # This script d...
65
2,123
mlflow
examples/langchain/retrieval_qa_chain.py
.py
import os import tempfile from langchain.chains import RetrievalQA from langchain.document_loaders import TextLoader from langchain.embeddings.openai import OpenAIEmbeddings from langchain.llms import OpenAI from langchain.text_splitter import CharacterTextSplitter from langchain.vectorstores import FAISS import mlfl...
47
1,696
mlflow
examples/langchain/simple_chain.py
.py
import os from langchain.chains import LLMChain from langchain.llms import OpenAI from langchain.prompts import PromptTemplate import mlflow # Ensure the OpenAI API key is set in the environment assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable." # Initialize the OpenAI mode...
31
979
mlflow
examples/langchain/chain_stream_output.py
.py
import os from langchain.llms import OpenAI from langchain_core.output_parsers import StrOutputParser import mlflow # Ensure the OpenAI API key is set in the environment assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable." # Initialize the OpenAI model and the prompt template...
24
692
mlflow
examples/langchain/simple_agent.py
.py
import os from langchain.agents import AgentType, initialize_agent, load_tools from langchain.llms import OpenAI import mlflow # Note: Ensure that the package 'google-search-results' is installed via pypi to run this example # and that you have a accounts with SerpAPI and OpenAI to use their APIs. # Ensuring necess...
37
1,463
mlflow
examples/groq/tracing.py
.py
""" This is an example for leveraging MLflow's auto tracing capabilities for Groq. For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html """ import groq import mlflow # Turn on auto tracing for Groq by calling mlflow.groq.autolog() mlflow.groq.autolog() client = gro...
28
631
mlflow
examples/sklearn_elasticnet_diabetes/osx/train_diabetes.py
.py
# # train_diabetes.py # # MLflow model using ElasticNet (sklearn) and Plots ElasticNet Descent Paths # # Uses the sklearn Diabetes dataset to predict diabetes progression using ElasticNet # The predicted "progression" column is a quantitative measure of disease progression one year after baseline # http...
126
4,087
mlflow
examples/tensorflow/train.py
.py
# tensorflow 2.x core api import tensorflow as tf from sklearn.datasets import load_diabetes import mlflow from mlflow.models import infer_signature class Normalize(tf.Module): """Data Normalization class""" def __init__(self, x): # Initialize the mean and standard deviation for normalization ...
168
5,925
mlflow
examples/docker/train.py
.py
# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality # P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. # Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009. import argparse import os i...
71
2,316
mlflow
examples/system_metrics/collect_system_metrics.py
.py
import time import mlflow if __name__ == "__main__": mlflow.enable_system_metrics_logging() with mlflow.start_run() as run: time.sleep(11) client = mlflow.MlflowClient() mlflow_run = client.get_run(run.info.run_id) print(mlflow_run.data.metrics)
13
277
mlflow
examples/mlflow_artifacts/example.py
.py
import os import tempfile from pprint import pprint import mlflow from mlflow.artifacts import download_artifacts from mlflow.tracking import MlflowClient def save_text(path, text): with open(path, "w") as f: f.write(text) def log_artifacts(): # Upload artifacts with mlflow.start_run() as run, ...
54
1,475
mlflow
examples/smolagents/tracing.py
.py
""" This is an example for leveraging MLflow's auto tracing capabilities for Smolagents. For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html """ from smolagents import CodeAgent, LiteLLMModel import mlflow # Turn on auto tracing for Smolagents by calling mlflow.smol...
19
591
mlflow
examples/lightgbm/lightgbm_sklearn/utils.py
.py
from mlflow.tracking import MlflowClient def yield_artifacts(run_id, path=None): """Yield all artifacts in the specified run""" client = MlflowClient() for item in client.list_artifacts(run_id, path): if item.is_dir: yield from yield_artifacts(run_id, item.path) else: ...
27
863
mlflow
examples/lightgbm/lightgbm_sklearn/train.py
.py
from pprint import pprint import lightgbm as lgb from sklearn.datasets import load_iris from sklearn.metrics import f1_score from sklearn.model_selection import train_test_split from utils import fetch_logged_data import mlflow import mlflow.lightgbm def main(): # prepare example dataset X, y = load_iris(re...
37
1,034
mlflow
examples/lightgbm/lightgbm_native/train.py
.py
import argparse import lightgbm as lgb import matplotlib as mpl from sklearn import datasets from sklearn.metrics import accuracy_score, log_loss from sklearn.model_selection import train_test_split import mlflow import mlflow.lightgbm mpl.use("Agg") def parse_args(): parser = argparse.ArgumentParser(descripti...
80
2,107
mlflow
examples/model_config/simple.py
.py
import mlflow with mlflow.start_run(): model_info = mlflow.pyfunc.log_model( name="model", python_model="model.py", model_config={"timeout": 10}, input_example=["hello"], ) # model = mlflow.pyfunc.load_model(model_info.model_uri, model_config={"timeout": 10}) # print(model.pre...
14
335
mlflow
examples/model_config/model.py
.py
from mlflow.models import ModelConfig, set_model def predict(model_input): model_config = ModelConfig() timeout = model_config.get("timeout") return [timeout] * len(model_input) set_model(predict)
11
213
mlflow
examples/mistral/tracing.py
.py
""" This is an example for leveraging MLflow's auto tracing capabilities for Mistral AI. For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html """ import os from mistralai import Mistral import mlflow # Turn on auto tracing for Mistral AI by calling mlflow.mistral.a...
30
762
mlflow
examples/haystack/tracing.py
.py
import os from getpass import getpass from haystack import Pipeline from haystack.components.builders import ChatPromptBuilder from haystack.components.generators.chat import OpenAIChatGenerator from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.components.routers import Condition...
150
5,807
mlflow
examples/deployments/databricks/databricks.py
.py
""" Usage ----- databricks secrets create-scope <scope> databricks secrets put-secret <scope> openai-api-key --string-value $OPENAI_API_KEY python examples/deployments/databricks.py --secret <scope>/openai-api-key ----- """ import argparse import uuid from mlflow.deployments import get_deploy_client def parse_args(...
113
3,165
mlflow
examples/rest_api/mlflow_tracking_rest_api.py
.py
""" This simple example shows how you could use MLflow REST API to create new runs inside an experiment to log parameters/metrics. Using MLflow REST API instead of MLflow library might be useful to embed in an application where you don't want to depend on the whole MLflow library, or to make your own HTTP requests in ...
142
4,353
mlflow
examples/auth/auth.py
.py
import os import uuid import mlflow.server class User: MLFLOW_TRACKING_USERNAME = "MLFLOW_TRACKING_USERNAME" MLFLOW_TRACKING_PASSWORD = "MLFLOW_TRACKING_PASSWORD" def __init__(self, username, password) -> None: self.username = username self.password = password self.env = {} ...
67
1,883
mlflow
examples/evaluation/evaluate_on_regressor.py
.py
from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import mlflow diabetes_dataset = load_diabetes() X_train, X_test, y_train, y_test = train_test_split( diabetes_dataset.data, diabetes_dataset.target, test_size=0.33, r...
29
848
mlflow
examples/evaluation/evaluate_with_qa_metrics.py
.py
import openai import pandas as pd import mlflow eval_df = pd.DataFrame({ "inputs": [ "What is MLflow?", "What is Spark?", "What is Python?", ], "ground_truth": [ "MLflow is an open-source platform for managing the end-to-end machine learning (ML) lifecycle. It was developed...
42
2,117
mlflow
examples/evaluation/evaluate_with_static_dataset.py
.py
import shap import xgboost from sklearn.model_selection import train_test_split import mlflow # Load the UCI Adult Dataset X, y = shap.datasets.adult() # Split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) # Fit an XGBoost binary clas...
34
908
mlflow
examples/evaluation/evaluate_with_llm_judge.py
.py
import os import openai import pandas as pd import mlflow from mlflow.metrics.genai import EvaluationExample, answer_similarity assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable." # testing with OpenAI gpt-4o-mini example = EvaluationExample( input="What is MLflow?", ...
68
3,304
mlflow
examples/evaluation/evaluate_with_custom_metrics.py
.py
import os import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import mlflow from mlflow.models import infer_signature, make_metric # loading the diabetes dataset diabetes_d...
86
2,699
mlflow
examples/evaluation/evaluate_with_model_validation.py
.py
import shap import xgboost from sklearn.dummy import DummyClassifier from sklearn.model_selection import train_test_split import mlflow from mlflow.models import MetricThreshold, infer_signature, make_metric # load UCI Adult Data Set; segment it into training and test sets X, y = shap.datasets.adult() X_train, X_test...
111
3,974
mlflow
examples/evaluation/evaluate_with_custom_metrics_comprehensive.py
.py
import numpy as np import pandas as pd from matplotlib.figure import Figure from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import mlflow from mlflow.models import infer_signature, make_metric # loading the diabetes data...
85
2,642
mlflow
examples/evaluation/evaluate_on_binary_classifier.py
.py
import shap import xgboost from sklearn.model_selection import train_test_split import mlflow from mlflow.models import infer_signature # Load the UCI Adult Dataset X, y = shap.datasets.adult() # Split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, rand...
42
1,169
mlflow
examples/evaluation/evaluate_with_function.py
.py
import shap import xgboost from sklearn.model_selection import train_test_split import mlflow # Load the UCI Adult Dataset X, y = shap.datasets.adult() # Split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) # Fit an XGBoost binary clas...
38
928
mlflow
examples/evaluation/evaluate_on_multiclass_classifier.py
.py
from sklearn.datasets import make_classification from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split import mlflow X, y = make_classification(n_samples=10000, n_classes=10, n_informative=5, random_state=1) X_train, X_test, y_train, y_test = train_test_split(X, y, ...
26
881
mlflow
examples/evaluation/evaluate_with_custom_code_metrics.py
.py
import os import openai import pandas as pd import mlflow from mlflow.metrics import make_metric from mlflow.metrics.base import MetricValue, standard_aggregations assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable." # Helper function to check if a string is valid python cod...
68
1,783