Skip to main content

Build

Databricks Ml Training

DatabricksOfficialCertified

Train ML models on Databricks. Use for: classification/regression/deep-learning (XGBoost, scikit-learn, LightGBM, PyTorch) with Optuna, @prod/@challenger aliases, batch scoring (spark_udf for plain models, fe.score_batch for Feature Views-backed), custom PyFunc, custom ResponsesAgent (LangGraph + UC Function/Vector Search); feature engineering with Feature Views (Feature, create_feature, DeltaTableSource/SdpSource/StreamSource/RequestSource, RollingWindow/SawtoothWindow/SlidingWindow/TumblingWindow, compute_features, point-in-time create_training_set, materialize_features to offline Delta + Lakebase online store, streaming features, Feature Serving). NOT for: endpoint ops (databricks-model-serving), MLflow evaluation (databricks-mlflow-evaluation).

  • New
  • v1.0.5
  • Reviewed Jul 21
  • No reviews yet

Capabilities

  • Default Canonical flow

    This flow assumes the feature columns already exist in a silver table

  • Train and register (the 90% case)

    Always mlflow.set_registry_uri("databricks-uc") — without it, models…

  • Consume: batch scoring over Delta

    The cheap, default path for models NOT backed by Feature Views

  • Real-time serving (when required)

    After registering a model to UC, deploy it behind a Model Serving…

Getting started

Full instructions

Install the skill, then ask your AI tool for the task in plain words. The full SKILL.md below shows what it covers.

Instructions: SKILL.mdv1.0.5

ML Training on Databricks

FIRST: Use the parent databricks-core skill for CLI basics, authentication, and profile selection.

Train with MLflow → register to Unity Catalog → consume the same artifact as either a batch Spark UDF over Delta or (when low-latency is required) a real-time serving endpoint.

Always train on Databricks (serverless job or notebook), never in the local Python process the agent is running in. Local training has no access to the silver tables, no MLflow tracking server, no UC registry path, and dies if the chat session drops — submit databricks jobs submit --no-wait (see "Train + deploy as a serverless job" below). Only fall back to local execution if the user explicitly asks for it.

If you need to deploy a real time model serving endpoint after the model is registered (creating endpoints, traffic config, version-swapping, querying, Foundation Model API endpoints), see databricks-model-serving.

Consumption When How
Batch UDF Dashboards, daily/hourly scores, predictions read by Genie/Dashboards or an app (often synced to a Lakebase table) mlflow.pyfunc.spark_udf(...) → INSERT INTO gold_predictions. If the model was logged with fe.log_model(training_set=...), use fe.score_batch() instead (not for models with StreamSource features) — see the Feature Engineering section below.
Real-time endpoint Score on a user action (fraud at authorization, rec at page load) — sub-100ms mlflow.deployments.get_deploy_client() (classical) / agents.deploy() (agents). Endpoint lifecycle: see databricks-model-serving.

Default Canonical flow

text
silver_<features>  +  silver_<labels>
        ▼
   notebook (as a serverless job):
   ├── train with mlflow.autolog (XGBoost / sklearn / etc.)
   ├── mlflow.register_model → UC: {catalog}.{schema}.{model}
   ├── set_registered_model_alias(name, "prod", version)
   └── spark_udf(@prod) over latest features → MERGE into gold_predictions
        ▼
gold_<entity>_predictions   ◄── dashboards, apps, Genie read this

This flow assumes the feature columns already exist in a silver table. When the model needs engineered features (windowed aggregations, point-in-time joins, online lookup), define them with Feature Views — see Feature Engineering.

Feature Views-backed models diverge here. If training used fe.log_model(training_set=...), replace spark_udf(@prod) with fe.score_batch(model_uri, df=...), passing the entity keys, timeseries column, and any request-time columns — it computes the features from the model's registered feature lineage. Models with StreamSource features can't use score_batch; serve them from an endpoint. See the Feature Engineering section below.

One notebook, one artifact. Re-running = retraining. Gold is where truth lives — read paths never call the model directly. Keep label-window logic (failure occurred within 7 days) in the notebook during dev; once stable, promote to a silver materialized view in SDP.


Train and register (the 90% case)

mlflow.autolog() captures params, metrics, code, and the model artifact for every run; registered_model_name=... auto-registers the best run to UC (auto-incremented version). Wrap training with Optuna so each trial is a child run and the best one is what gets registered.

Always mlflow.set_registry_uri("databricks-uc") — without it, models land in the deprecated workspace registry. The experiment's parent folder must exist — set_experiment does NOT auto-create it (fails with NOT_FOUND: Parent directory does not exist). Pre-create it once with databricks workspace mkdirs before the job runs.

bash
# Once per project — create the parent folder for the MLflow experiment.
databricks workspace mkdirs /Users/[email protected]/turbine_project

Use the Databricks notebook source format (# Databricks notebook source header, # COMMAND ---------- separators, # MAGIC %md/%sql magics for markdown/SQL cells):

python
# Databricks notebook source
# MAGIC %md
# MAGIC # Turbine failure prediction
# MAGIC
# MAGIC Train an XGBoost classifier on engineered turbine telemetry features.
# MAGIC ## Data exploration

# COMMAND ----------

# (basic data exploration — class balance, schema sanity, etc.)

# COMMAND ----------
# MAGIC %md
# MAGIC ## Training the model

# COMMAND ----------

import mlflow, mlflow.xgboost, optuna
from mlflow.tracking import MlflowClient
from xgboost import XGBClassifier
from sklearn.metrics import roc_auc_score

mlflow.set_registry_uri("databricks-uc")
mlflow.set_experiment("/Users/[email protected]/turbine_project/mlflow_experiment")

CATALOG, SCHEMA, NAME = "ai_demo_gen", "wind_farm", "turbine_failure"
FULL_NAME = f"{CATALOG}.{SCHEMA}.{NAME}"

# Autolog WITHOUT registered_model_name — otherwise every Optuna trial registers a new UC
# version, and a max-by-version pick lands on the last trial to finish, not the best one.
mlflow.xgboost.autolog(log_input_examples=True)

# For imbalanced labels: stratify the split, set scale_pos_weight = neg/pos.
def objective(trial):
    params = {
        "n_estimators":  trial.suggest_int("n_estimators", 100, 400),
        "max_depth":     trial.suggest_int("max_depth", 3, 10),
        "learning_rate": trial.suggest_float("learning_rate", 0.01, 0.3, log=True),
    }
    with mlflow.start_run(nested=True):
        m = XGBClassifier(**params).fit(X_train, y_train)
        return roc_auc_score(y_test, m.predict_proba(X_test)[:, 1])

with mlflow.start_run(run_name="hpo") as parent:
    study = optuna.create_study(direction="maximize")
    study.optimize(objective, n_trials=20)

# COMMAND ----------
# MAGIC %md
# MAGIC ## Retrain best params and register

# COMMAND ----------
# Retrain on the winning trial's params explicitly, then register that single model.
with mlflow.start_run(run_name="best"):
    best = XGBClassifier(**study.best_params).fit(X_train, y_train)
    mlflow.log_metric("val_auc", study.best_value)
    info = mlflow.xgboost.log_model(best, name="model", registered_model_name=FULL_NAME)

# Stages are deprecated — UC uses movable aliases. Repoint @prod at the version we just registered.
client = MlflowClient(registry_uri="databricks-uc")
client.set_registered_model_alias(FULL_NAME, "prod", info.registered_model_version)

Framework autolog: mlflow.{sklearn,xgboost,lightgbm,pytorch,tensorflow,spark}.autolog().

Aliases, not stages: UC dropped Staging/Production. Use movable @prod/@challenger; load with models:/{full_name}@prod. Promoting a new version is one set_registered_model_alias call.


Consume: batch scoring over Delta

The cheap, default path for models NOT backed by Feature Views. Load the registered model as a Spark UDF and score a Delta table; write predictions to a gold table that downstream consumers read. For Feature Views-backed models (logged with fe.log_model(training_set=...)), skip spark_udf entirely and use fe.score_batch(), except for models with StreamSource features, which score_batch rejects — see the Feature Engineering section.

python
# COMMAND ----------
# MAGIC %md
# MAGIC ## Score and save to a gold predictions table

# COMMAND ----------
import mlflow
from pyspark.sql import functions as F

# env_manager rules:
#   "local"     → same runtime as training (same notebook/job). Fastest, default in dev/demo.
#   "virtualenv"→ different runtime than training; rebuilds the model's env.
#   "uv"        → same as virtualenv but faster (MLflow ≥ 2.22).
predict = mlflow.pyfunc.spark_udf(
    spark,
    model_uri=f"models:/{FULL_NAME}@prod",
    env_manager="local",
)

features = spark.table(f"{CATALOG}.{SCHEMA}.silver_turbine_features_latest")
feature_cols = [c for c in features.columns if c != "turbine_id"]   # exclude the join key
scored = features.withColumn("risk_score", predict(*[features[c] for c in feature_cols]))

# Overwrite-per-run pattern for "latest score per entity":
scored.select("turbine_id", "risk_score", F.current_timestamp().alias("scored_at")) \
    .write.mode("overwrite").saveAsTable(f"{CATALOG}.{SCHEMA}.gold_turbine_predictions")

For incremental scoring with history, MERGE into the predictions table instead of overwrite.


Real-time serving (when required)

After registering a model to UC, deploy it behind a Model Serving endpoint. The dev-side call is mlflow.deployments.get_deploy_client("databricks").create_endpoint(...) for classical ML or agents.deploy(...) for ResponsesAgents. First deploy is ~5 min for classical ML.

For endpoint create / update / version-swap, traffic config, AI Gateway, querying, the state.ready + state.config_update two-field readiness check, and Foundation Model API endpoints, see databricks-model-serving.


Train + deploy as a serverless job

Training notebooks run a few minutes (Optuna + UC register; endpoint warmup adds 5–15 min if you also deploy). Submit as a serverless one-time run so the CLI doesn't block. The notebook ends with dbutils.notebook.exit(json.dumps({...})) so the structured result (model_version, val_auc, endpoint_name) reaches .notebook_output.result.

bash
# 1. Upload the training notebook
databricks workspace import /Workspace/Users/[email protected]/turbine_project/train \
  --file ./train_notebook.py --format SOURCE --language PYTHON --overwrite

# 2. Submit as serverless one-time run (returns {"run_id": N} immediately with --no-wait)
RUN_ID=$(databricks jobs submit --no-wait --json '{
  "run_name": "turbine-train-and-deploy",
  "tasks": [{
    "task_key": "train",
    "notebook_task": {"notebook_path": "/Workspace/Users/[email protected]/turbine_project/train"},
    "environment_key": "ml_env"
  }],
  "environments": [{
    "environment_key": "ml_env",
    "spec": {
      "client": "4",
      "dependencies": ["mlflow==3.1.0", "xgboost==2.1.3", "optuna==4.1.0", "scikit-learn==1.5.2"]
    }
  }]
}' | jq -r .run_id)

# 3. Poll until a terminal life_cycle_state.
for _ in $(seq 60); do
  STATE=$(databricks jobs get-run "$RUN_ID" | jq -r '.state.life_cycle_state // "UNKNOWN"')
  echo "$(date +%H:%M:%S) $STATE"
  [[ "$STATE" =~ ^(TERMINATED|SKIPPED|INTERNAL_ERROR)$ ]] && break
  sleep 30
done
[[ "$STATE" =~ ^(TERMINATED|SKIPPED|INTERNAL_ERROR)$ ]] || { databricks jobs cancel-run "$RUN_ID"; exit 1; }

# life_cycle_state TERMINATED only means "the run ended" — check result_state.
RESULT=$(databricks jobs get-run "$RUN_ID" | jq -r '.state.result_state // "UNKNOWN"')
echo "result_state=$RESULT"
[[ "$RESULT" == "SUCCESS" ]] || { echo "Run did not succeed"; exit 1; }

# 4. Pull structured output via the TASK run_id (NOT the submit run_id).
TASK_RUN_ID=$(databricks jobs get-run "$RUN_ID" | jq -r '.tasks[0].run_id')
databricks jobs get-run-output "$TASK_RUN_ID" | jq '.notebook_output.result'
# → '{"model_version":"3","val_auc":0.91,"rows_scored":124,"endpoint":"turbine-risk-endpoint"}'

Common jobs submit traps to be aware of: environments[].spec.client: "4" is required on serverless notebook tasks; use the TASK run_id (tasks[0].run_id) — NOT the submit run_id — for get-run-output; print() is unreliable on serverless one-time runs (use dbutils.notebook.exit(json.dumps(...))); jobs submit rejects tags. For the broader databricks-jobs skill, see databricks-jobs.


Custom pyfunc

When sklearn/XGBoost autolog isn't enough — custom preprocessing, multiple sub-models, external API calls, ensemble logic. See references/custom-pyfunc.md for a full worked example. Two non-obvious things:

  • python_model="path/to/file.py" (file path, not class instance) + mlflow.models.set_model(MyModel()) at the end of that file. This is the "Models from Code" pattern — the file is logged verbatim, no pickling of the class.
  • mlflow.models.predict(model_uri=..., input_data=..., env_manager="uv") before deploying. Catches missing deps before the endpoint does.

Custom GenAI agents

Hand-rolled ResponsesAgent (LangGraph + UC Function tools + Vector Search retrieval) — see references/genai-agents.md.

Prefer no-code authoring via databricks-genie-agents (tables + documents in UC volumes; replaces the legacy Knowledge Assistant / Supervisor Agent) unless the user explicitly needs a custom LangGraph agent.


Feature Engineering with Feature Views

Default to using Feature Views for feature engineering, unless the user specifies otherwise or the features are more complex than the framework supports. Read references/feature-views.md before writing feature-engineering code; it lists the supported sources, windows, and aggregation functions.

When a batch feature needs logic beyond one source table and the aggregation functions references/feature-views.md lists, try these in order:

  1. transformation_sql on the DeltaTableSource for renames, casts, and derived columns of one table.
  2. SdpSource for joins, multi-step transforms, or custom windowing: write the logic in a triggered Spark Declarative Pipeline (databricks-pipelines) and point Feature Views at its output table. Feature Store runs the pipeline before each materialization and backfill.
  3. DeltaTableSource on the pipeline's output table when the pipeline is continuous or scheduled outside Feature Store.

Whichever route you take, the output table must keep an event timestamp for timeseries_column. A current-snapshot table joined onto historical labels leaks future values into training.

When a streaming feature needs a stream-stream join, a stream-static join, a multi-step aggregation, or an aggregation function references/feature-views.md doesn't list for streaming sources, compute it in a Spark Declarative Pipeline that writes a Delta table with change data feed enabled, and materialize a DeltaTableSource feature on it with StreamingMode() (online only, freshness in tens of seconds). Route the pipeline through Kafka (fe.create_stream + StreamSource) only when the feature needs sub-second freshness or a SawtoothWindow; ingestion then starts at the latest offset, so seed history with backfill_source.

Use feature tables and FeatureLookup only when the user explicitly asks for them; see references/feature-tables.md. When a project already has feature tables, keep them and define Feature Views over them rather than rewriting the tables.

Train/score path with Feature Views: create_training_set(features=[...]) → fe.log_model(training_set=...) → fe.score_batch, or a model serving endpoint when any feature is on a StreamSource.


Gotchas (the ones that cost time)

Trap Fix
Model lands in workspace registry, not UC mlflow.set_registry_uri("databricks-uc") before logging
Endpoint returns PERMISSION_DENIED at first query Pass resources=[...] to log_model (covers UC functions, VS indexes, other endpoints, Lakebase) — see references/genai-agents.md#resources-that-need-passthrough-auth for the full list
Used transition_model_version_stage Stages are deprecated in UC. Use client.set_registered_model_alias(name, "prod", version)
spark_udf rebuilds a virtualenv on every call Pass env_manager="local" when training+scoring share a runtime
pip_requirements mismatch crashes endpoint at load Pin exact versions; or pull live with f"mlflow=={get_distribution('mlflow').version}"
agents.deploy() produced a weirdly-named endpoint Pass endpoint_name=... explicitly. Auto-derived name is agents_<catalog>-<schema>-<model>

Endpoint-lifecycle gotchas (readiness two-state, version-swap, Serving-UI SP filter) live in databricks-model-serving.


Reference files

File Contents
references/custom-pyfunc.md Single end-to-end custom pyfunc example: artifacts, signature, code_paths, log → register → deploy → query.
references/genai-agents.md Custom LangGraph ResponsesAgent with UC Function + Vector Search tools. create_text_output_item gotcha and the resources=[...] passthrough-auth list. For no-code agents prefer databricks-genie-agents.
references/feature-views.md Feature Engineering with Feature Views (GA): choosing entities and windows, the Feature object, Delta/Stream/Request sources, create_stream, streaming windows and destinations, window ↔ operator compatibility, compute_features, point-in-time create_training_set and holdout eval, register_feature, materialize_features triggers, teardown order, and batch / online model / Feature Serving patterns. Requires databricks-feature-engineering>=0.18.3.
references/feature-tables.md Feature tables with FeatureLookup, for when the user asks for them: create_table with primary keys, time series tables and timestamp_lookup_key, score_batch, publish_table to an online store, and Feature Views over existing feature tables.
  • databricks-model-serving — serving-endpoint lifecycle (create, query, update-config, version-swap, AI Gateway, Foundation Model API endpoints).
  • databricks-genie-agents: no-code agents over tables + documents (replaces legacy Knowledge Assistants / Supervisor Agents). Prefer this over hand-rolling agents.
  • databricks-mlflow-evaluation — evaluate model/agent quality before promoting @prod.
  • databricks-vector-search — vector indexes used as retrieval tools in agents.
  • databricks-jobs — async deploy pattern (--no-wait, TASK run_id trap).
  • databricks-unity-catalog — UC governs the registered model: permissions, lineage, audit.

Explore more skills

Browse all
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

More from Databricks

View source →
databricks-data-discoveryDiscover, explore, and query Databricks data via Genie — the CLI equivalent of the Genie One MCP. MUST be invoked whenever the user asks to find or locate data ('what tables are in X', 'where does X live', 'which catalog/schema has Y'),…2 installsspark-python-data-sourceBuild custom Python data sources for Apache Spark using the PySpark DataSource API — batch and streaming readers/writers for external systems. Use this skill whenever someone wants to connect Spark to an external system (database, API,…1 installsdatabricks-python-sdkDatabricks development guidance including Python SDK, Databricks Connect, CLI, and REST API. Use when working with databricks-sdk, databricks-connect, or Databricks APIs.1 installsdatabricks-execution-computeExecute code and manage compute on Databricks: run Python/Scala/SQL/R via serverless, classic, or interactive clusters, and create/resize/delete clusters and SQL warehouses.1 installsdatabricks-setup-localPreviews, provisions, or diagnoses a uv-managed local Python .venv with `databricks environments setup-local`. Use when the user wants to set up or fix one for Databricks Connect, cluster or serverless compute, `--job-task`, or a bundle…1 installsdatabricks-serverless-migration-apiMigrate Databricks jobs to serverless through the Compute Migrations API and CLI, then track, review, and approve each migration. Use for automated job migrations managed by this service, scripts that start and track migrations, requests…0 installs

Frequently asked questions about databricks-ml-training

What does the databricks-ml-training skill do?

Train ML models on Databricks. Use for: classification/regression/deep-learning (XGBoost, scikit-learn, LightGBM, PyTorch) with Optuna, @prod/@challenger aliases, batch scoring (spark_udf for plain models, fe.score_batch for Feature Views-backed), custom PyFunc, custom ResponsesAgent (LangGraph + UC Function/Vector Search); feature engineering with Feature Views (Feature, create_feature, DeltaTableSource/SdpSource/StreamSource/RequestSource, RollingWindow/SawtoothWindow/SlidingWindow/TumblingWindow, compute_features, point-in-time create_training_set, materialize_features to offline Delta + Lakebase online store, streaming features, Feature Serving). NOT for: endpoint ops (databricks-model-serving), MLflow evaluation (databricks-mlflow-evaluation). It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the databricks-ml-training skill?

Run `npx @skills-hub-ai/cli install databricks-ml-training` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/databricks-ml-training/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does databricks-ml-training work with?

databricks-ml-training runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the databricks-ml-training skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use databricks-ml-training after installing it?

In Claude Code, type `/databricks-ml-training` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the databricks-ml-training skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.

Badge for your README

Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.

Install on Skills Hub badge preview
Markdown
[![Install on Skills Hub](https://skills-hub.ai/api/badges/skill/databricks-ml-training)](https://skills-hub.ai/skills/databricks-ml-training)
HTML
<a href="https://skills-hub.ai/skills/databricks-ml-training"><img src="https://skills-hub.ai/api/badges/skill/databricks-ml-training" alt="Install on Skills Hub"></a>

More options in the badge docs.