Design the Input Payload for the Unified Endpoint:
Your unified endpoint will need a way to know which model to route to. The input JSON could look something like this:
{
"model_identifier": "model_a_champion", // Or "model_b_v2", or just "model_a"
"model_input_data": {
// ... actual features for the target model ...
}
}
Or, you might have specific routing logic based on the content of model_input_data.
Create the Custom Router mlflow.pyfunc.PythonModel:
import mlflow
import pandas as pd
class UnifiedInferenceRouter(mlflow.pyfunc.PythonModel):
def load_context(self, context):
"""
This method is called when the model is loaded by the serving environment.
You can pre-load frequently used models or configurations here,
but be mindful of memory and load times.
For many models, on-demand loading in predict() might be better.
"""
self.loaded_models = {} # Cache for loaded models
# Example: Pre-load a default or very common model if desired
# self.loaded_models['default_model'] = mlflow.pyfunc.load_model("models:/your_catalog.your_schema.default_model@champion")
print("UnifiedInferenceRouter context loaded.")
def _get_model(self, model_identifier_from_request):
"""
Loads a model from Unity Catalog based on the identifier.
Uses a simple cache to avoid reloading.
"""
# Define your mapping from request identifier to UC model URI
# This is crucial and specific to your setup.
model_uri_map = {
"model_a_champion": "models:/your_catalog.your_schema.model_a@champion",
"model_b_prod": "models:/your_catalog.your_schema.model_b@production",
"model_c_specific_version": "models:/your_catalog.your_schema.model_c/1",
# Add more mappings as needed
}
if model_identifier_from_request not in model_uri_map:
raise ValueError(f"Unknown model identifier: {model_identifier_from_request}")
model_uri = model_uri_map[model_identifier_from_request]
if model_uri not in self.loaded_models:
print(f"Loading model: {model_uri}")
# The service principal backing the Model Serving endpoint
# will need USAGE privilege on the catalog, schema, and model.
self.loaded_models[model_uri] = mlflow.pyfunc.load_model(model_uri)
print(f"Model {model_uri} loaded and cached.")
else:
print(f"Using cached model: {model_uri}")
return self.loaded_models[model_uri]
def predict(self, context, model_input):
"""
model_input is expected to be a pandas DataFrame.
Each row in the DataFrame should represent one request.
"""
predictions = []
if not isinstance(model_input, pd.DataFrame):
raise ValueError("Input must be a pandas DataFrame.")
for index, row in model_input.iterrows():
try:
# --- Routing Logic ---
# Option 1: Explicit model_identifier in input
if 'model_identifier' not in row:
raise ValueError("Request missing 'model_identifier' field.")
model_id = row['model_identifier']
# Option 2: Infer model based on input data (more complex)
# if 'feature_x' in row['model_input_data'] and row['model_input_data']['feature_x'] > 10:
# model_id = "model_a_champion"
# else:
# model_id = "model_b_prod"
target_model_instance = self._get_model(model_id)
# Prepare input for the target model
# The `model_input_data` field should contain a dict or DataFrame
# compatible with the target model's expected input schema.
if 'model_input_data' not in row:
raise ValueError("Request missing 'model_input_data' field.")
target_model_payload = row['model_input_data']
# If target_model_payload is a dict and target model expects DataFrame:
if isinstance(target_model_payload, dict):
target_model_payload_df = pd.DataFrame([target_model_payload])
else: # Assuming it's already in a suitable format (e.g. DataFrame if model expects it)
target_model_payload_df = target_model_payload
# Make prediction using the loaded target model
prediction = target_model_instance.predict(target_model_payload_df)
# The prediction could be a DataFrame, Series, numpy array, or list.
# Standardize the output format if needed.
# For simplicity, assuming it returns something easily serializable.
predictions.append({"status": "success", "prediction": prediction.tolist() if hasattr(prediction, 'tolist') else prediction})
except Exception as e:
predictions.append({"status": "error", "message": str(e)})
return pd.DataFrame(predictions) # Model Serving expects a DataFrame, list, or numpy array
# --- Example of how to log this router model ---
# (Typically run this in a Databricks notebook)
# import mlflow
# from mlflow.models.signature import infer_signature
#
# router_model_name_uc = "your_catalog.your_schema.unified_router_model"
#
# # Dummy input for signature inference
# # This should match the structure your endpoint will receive
# dummy_input_df = pd.DataFrame([{
# "model_identifier": "model_a_champion",
# "model_input_data": {"feature1": 0.5, "feature2": 1.2} # Example features for model_a
# }])
#
# # For the output signature, it's often a list of dicts or a DataFrame
# # Let's assume a simple output for signature purposes
# dummy_output_df = pd.DataFrame([{"status": "success", "prediction": [0.95]}])
#
# signature = infer_signature(dummy_input_df, dummy_output_df)
#
# with mlflow.start_run(run_name="Unified Router Registration") as run:
# mlflow.pyfunc.log_model(
# artifact_path="router_model", # Subdirectory in MLflow run artifacts
# python_model=UnifiedInferenceRouter(),
# # Add conda_env or pip_requirements if your router or sub-models have specific deps
# # conda_env={
# # 'channels': ['defaults', 'conda-forge'],
# # 'dependencies': [
# # 'python=3.9',
# # 'pip',
# # {
# # 'pip': [
# # 'mlflow>={}'.format(mlflow.__version__),
# # 'pandas',
# # 'scikit-learn==<your_sklearn_version_if_needed_by_any_model>',
# # # Add other common dependencies here
# # ],
# # },
# # ],
# # 'name': 'router_env'
# # },
# input_example=dummy_input_df,
# signature=signature,
# registered_model_name=router_model_name_uc # Register in Unity Catalog
# )
# print(f"Router model registered as {router_model_name_uc}")
Test the Endpoint:
Once the endpoint is "Ready", you can send requests to it using the provided URL and a token.
The request body (for the standard Databricks format) would look like:
{
"dataframe_records": [
{
"model_identifier": "model_a_champion",
"model_input_data": {"feature1": 0.5, "feature2": 1.2, "feature3": ...}
},
{
"model_identifier": "model_b_prod",
"model_input_data": {"input_field_x": "abc", "input_field_y": 123, ...}
}
]
}
Or, if you enable "Arrow format" or use the MLflow Deployments SDK, the format might vary slightly (e.g., direct JSON object for single requests). For the dataframe_records format, your model_input in the predict function will be a DataFrame with columns model_identifier and model_input_data.