|
| 1 | +# Copyright 2018 Iguazio |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# |
| 15 | +import tempfile |
| 16 | +import shutil |
| 17 | +import lightgbm as lgb |
| 18 | +import mlflow |
| 19 | +import mlflow.environment_variables |
| 20 | +import mlflow.xgboost |
| 21 | +import pytest |
| 22 | +import xgboost as xgb |
| 23 | +from sklearn import datasets |
| 24 | +from sklearn.metrics import accuracy_score, log_loss |
| 25 | +from sklearn.model_selection import train_test_split |
| 26 | + |
| 27 | +import os |
| 28 | +# os.environ["MLRUN_IGNORE_ENV_FILE"] = "True" #TODO remove before push |
| 29 | + |
| 30 | +import mlrun |
| 31 | +import mlrun.launcher.local |
| 32 | +# Important: |
| 33 | +# unlike mlconf which resets back to default after each test run, the mlflow configurations |
| 34 | +# and env vars don't, so at the end of each test we need to redo anything we set in that test. |
| 35 | +# what we cover in these tests: logging "regular" runs with, experiment name, run id and context |
| 36 | +# name (last two using mlconf), failing run mid-way, and a run with no handler. |
| 37 | +# we also test here importing of runs, artifacts and models from a previous run. |
| 38 | + |
| 39 | +# simple mlflow example of lgb logging |
| 40 | +def lgb_run(): |
| 41 | + # prepare train and test data |
| 42 | + iris = datasets.load_iris() |
| 43 | + X = iris.data |
| 44 | + y = iris.target |
| 45 | + X_train, X_test, y_train, y_test = train_test_split( |
| 46 | + X, y, test_size=0.2, random_state=42 |
| 47 | + ) |
| 48 | + |
| 49 | + # enable auto logging |
| 50 | + mlflow.lightgbm.autolog() |
| 51 | + |
| 52 | + train_set = lgb.Dataset(X_train, label=y_train) |
| 53 | + |
| 54 | + with mlflow.start_run(): |
| 55 | + # train model |
| 56 | + params = { |
| 57 | + "objective": "multiclass", |
| 58 | + "num_class": 3, |
| 59 | + "learning_rate": 0.1, |
| 60 | + "metric": "multi_logloss", |
| 61 | + "colsample_bytree": 1.0, |
| 62 | + "subsample": 1.0, |
| 63 | + "seed": 42, |
| 64 | + } |
| 65 | + # model and training data are being logged automatically |
| 66 | + model = lgb.train( |
| 67 | + params, |
| 68 | + train_set, |
| 69 | + num_boost_round=10, |
| 70 | + valid_sets=[train_set], |
| 71 | + valid_names=["train"], |
| 72 | + ) |
| 73 | + |
| 74 | + # evaluate model |
| 75 | + y_proba = model.predict(X_test) |
| 76 | + y_pred = y_proba.argmax(axis=1) |
| 77 | + loss = log_loss(y_test, y_proba) |
| 78 | + acc = accuracy_score(y_test, y_pred) |
| 79 | + |
| 80 | + # log metrics |
| 81 | + mlflow.log_metrics({"log_loss": loss, "accuracy": acc}) |
| 82 | + |
| 83 | + |
| 84 | +# simple mlflow example of xgb logging |
| 85 | +def xgb_run(): |
| 86 | + # prepare train and test data |
| 87 | + iris = datasets.load_iris() |
| 88 | + x = iris.data |
| 89 | + y = iris.target |
| 90 | + x_train, x_test, y_train, y_test = train_test_split( |
| 91 | + x, y, test_size=0.2, random_state=42 |
| 92 | + ) |
| 93 | + |
| 94 | + # enable auto logging |
| 95 | + mlflow.xgboost.autolog() |
| 96 | + |
| 97 | + dtrain = xgb.DMatrix(x_train, label=y_train) |
| 98 | + dtest = xgb.DMatrix(x_test, label=y_test) |
| 99 | + |
| 100 | + with mlflow.start_run(): |
| 101 | + # train model |
| 102 | + params = { |
| 103 | + "objective": "multi:softprob", |
| 104 | + "num_class": 3, |
| 105 | + "learning_rate": 0.3, |
| 106 | + "eval_metric": "mlogloss", |
| 107 | + "colsample_bytree": 1.0, |
| 108 | + "subsample": 1.0, |
| 109 | + "seed": 42, |
| 110 | + } |
| 111 | + # model and training data are being logged automatically |
| 112 | + model = xgb.train(params, dtrain, evals=[(dtrain, "train")]) |
| 113 | + # evaluate model |
| 114 | + y_proba = model.predict(dtest) |
| 115 | + y_pred = y_proba.argmax(axis=1) |
| 116 | + loss = log_loss(y_test, y_proba) |
| 117 | + acc = accuracy_score(y_test, y_pred) |
| 118 | + # log metrics |
| 119 | + mlflow.log_metrics({"log_loss": loss, "accuracy": acc}) |
| 120 | + |
| 121 | + |
| 122 | +@pytest.mark.parametrize("handler", ["xgb_run", "lgb_run"]) |
| 123 | +def test_track_run_with_experiment_name(handler): |
| 124 | + """ |
| 125 | + This test is for tracking a run logged by mlflow into mlrun while it's running using the experiment name. |
| 126 | + first activate the tracking option in mlconf, then we name the mlflow experiment, |
| 127 | + then we run some code that is being logged by mlflow using mlrun, |
| 128 | + and finally compare the mlrun we tracked with the original mlflow run using the validate func |
| 129 | + """ |
| 130 | + # Enable general tracking |
| 131 | + mlrun.mlconf.external_platform_tracking.enabled = True |
| 132 | + # Set the mlflow experiment name |
| 133 | + mlflow.environment_variables.MLFLOW_EXPERIMENT_NAME.set(f"{handler}_test_track") |
| 134 | + with tempfile.TemporaryDirectory() as test_directory: |
| 135 | + # Use SQLite backend instead of filesystem (filesystem will be deprecated in Feb 2026) |
| 136 | + db_uri = f"sqlite:///{os.path.join(test_directory, 'mlflow.db')}" |
| 137 | + mlflow.set_tracking_uri(db_uri) # Tell mlflow where to save logged data |
| 138 | + |
| 139 | + # Create a project for this tester: |
| 140 | + project = mlrun.get_or_create_project(name="default", context=test_directory) |
| 141 | + |
| 142 | + # Create a MLRun function using the tester source file (all the functions must be located in it): |
| 143 | + func = project.set_function( |
| 144 | + func=__file__, |
| 145 | + name=f"{handler}-test", |
| 146 | + kind="job", |
| 147 | + image="mlrun/mlrun", |
| 148 | + requirements=["mlflow"], |
| 149 | + ) |
| 150 | + # mlflow creates a dir to log the run, this makes it in the tmpdir we create |
| 151 | + trainer_run = func.run( |
| 152 | + local=True, |
| 153 | + handler=handler, |
| 154 | + output_path=test_directory, |
| 155 | + ) |
| 156 | + |
| 157 | + # Find the MLflow logged model and prepare it for serving |
| 158 | + # Note: In MLflow 2.24+, we must dynamically discover model paths since MLflow changed |
| 159 | + # its directory structure from predictable paths (e.g., experiment_name/0/model/) to |
| 160 | + # UUID-based paths (e.g., experiment_id/run_uuid/artifacts/model/). |
| 161 | + |
| 162 | + # Create MLflow client to query the tracking server |
| 163 | + mlflow_client = mlflow.tracking.MlflowClient(tracking_uri=db_uri) |
| 164 | + |
| 165 | + # Get the experiment by name to obtain its ID |
| 166 | + experiment = mlflow_client.get_experiment_by_name(f"{handler}_test_track") |
| 167 | + |
| 168 | + # Search for runs in this experiment and get the run ID |
| 169 | + # (There should only be one run from our training above) |
| 170 | + run_id = mlflow_client.search_runs(experiment_ids=[experiment.experiment_id])[0].info.run_id |
| 171 | + |
| 172 | + # Find all models logged in this run |
| 173 | + logged_models = mlflow.search_logged_models(filter_string=f"source_run_id = '{run_id}'") |
| 174 | + |
| 175 | + # Extract the artifact location and remove the "file://" prefix |
| 176 | + model_artifacts_dir = logged_models["artifact_location"].tolist()[0].replace("file://", "") |
| 177 | + |
| 178 | + # Package the model artifacts as a zip file for MLFlowModelServer |
| 179 | + # Note: MLFlowModelServer requires models to be packaged as zip archives |
| 180 | + # rather than loose directories for deployment |
| 181 | + model_path = os.path.join(test_directory, f"{handler}-model-serving") |
| 182 | + os.makedirs(model_path, exist_ok=True) |
| 183 | + shutil.make_archive(os.path.join(model_path, "model"), 'zip', model_artifacts_dir) |
| 184 | + |
| 185 | + serving_func = project.set_function( |
| 186 | + func=os.path.abspath("function.yaml"), |
| 187 | + name=f"{handler}-server", |
| 188 | + ) |
| 189 | + model_name = f"{handler}-model" |
| 190 | + # Add the model |
| 191 | + serving_func.add_model( |
| 192 | + model_name, |
| 193 | + class_name="MLFlowModelServer", |
| 194 | + model_path=model_path, |
| 195 | + ) |
| 196 | + |
| 197 | + # Create a mock server |
| 198 | + server = serving_func.to_mock_server() |
| 199 | + |
| 200 | + # An example taken randomly |
| 201 | + result = server.test(f"/v2/models/{model_name}/predict", {"inputs": [[5.1, 3.5, 1.4, 0.2]]}) |
| 202 | + print(result) |
| 203 | + assert result |
| 204 | + # unset mlflow experiment name to default |
| 205 | + mlflow.environment_variables.MLFLOW_EXPERIMENT_NAME.unset() |
| 206 | + |
| 207 | + |
0 commit comments