ML Pipeline Orchestration
Orchestrate ML workflows using Snowflake Task Graphs (DAGs). Use @remote for ML tasks (compute pool) — cheaper, ML dependencies included.
When to Use
- User wants to schedule ML training or inference
- User wants to orchestrate multiple ML steps (prep → train → evaluate → deploy)
- User wants to convert a notebook into a production pipeline
- User mentions: "DAG", "task graph", "pipeline", "schedule training", "productionize"
⚠️ CRITICAL: Environment Guide Check
Before proceeding, verify you have the environment guide from machine-learning/SKILL.md → Step 0.
Key Concepts
from snowflake.core.task.dagv1 import DAG, DAGTask, DAGTaskBranch, DAGOperation
from snowflake.core.task.context import TaskContext
from snowflake.core.task import Cron
from snowflake.ml.jobs import remote
- Compute pool tasks: Run on compute pool via
@remote or MLJobDefinition — cheaper, ML packages included
- Warehouse tasks: Run as stored procedures — use for lightweight orchestration, branching
TaskContext: Pass data between tasks via get_predecessor_return_value() / set_return_value()
- DAG
config: Pass shared settings via config={"key": "value"} on the DAG; tasks read via TaskContext.get_task_graph_config()
- Dependencies:
task_a >> task_b (sequential), task >> [a, b] (fan-out)
API Gotchas
| Wrong |
Correct |
DAGTask("T", my_remote_fn, warehouse=WH) |
DAGTask("T", definition=my_remote_fn) — no warehouse for @remote |
DAG(database=X, schema=Y) |
DAGOperation(schema_ref) — database/schema set via DAGOperation |
schedule="0 * * * *" |
schedule=Cron("0 * * * *", "UTC") or timedelta(hours=1) |
Branch returns "deploy" |
Branch returns "PROMOTE_MODEL" — must match task name exactly |
return result in @remote |
ctx.set_return_value(json.dumps(result)) — must use TaskContext |
TaskContext fails with ModuleNotFoundError |
Add snowflake.core to DAG packages=[] — snowflake-ml-python >=1.29 no longer includes it |
Pipeline Template
import json
from datetime import timedelta
from snowflake.core import Root
from snowflake.core.task.dagv1 import DAG, DAGTask, DAGTaskBranch, DAGOperation
from snowflake.core.task.context import TaskContext
from snowflake.core.task import Cron
from snowflake.ml.jobs import remote
from snowflake.snowpark import Session
# Configuration
DATABASE = "<DATABASE>"
SCHEMA = "<SCHEMA>"
WAREHOUSE = "<WAREHOUSE>"
COMPUTE_POOL = "<COMPUTE_POOL>"
DAG_STAGE = f"@{DATABASE}.{SCHEMA}.DAG_STAGE"
JOB_STAGE = f"@{DATABASE}.{SCHEMA}.JOB_STAGE"
# --- Warehouse task: lightweight data prep ---
def prepare_data(session: Session) -> str:
"""Prepare datasets, return info as JSON for downstream tasks."""
# ... data prep logic ...
return json.dumps({"train_table": "TRAIN_DATA", "test_table": "TEST_DATA"})
# --- @remote task: heavy ML training on compute pool ---
@remote(COMPUTE_POOL, stage_name=JOB_STAGE, database=DATABASE, schema=SCHEMA)
def train_model() -> None:
"""Train model on compute pool. Access predecessor data via TaskContext."""
session = Session.builder.getOrCreate()
ctx = TaskContext(session)
# Get data from predecessor task
data_info = json.loads(ctx.get_predecessor_return_value("PREPARE_DATA"))
# ... training logic using data_info ...
model_metrics = {"accuracy": 0.95, "model_path": "models/v1.pkl"}
# Pass results to successor tasks
ctx.set_return_value(json.dumps(model_metrics))
# --- Warehouse task: branching logic ---
def check_quality(session: Session) -> str:
"""Check model quality, return next task name."""
ctx = TaskContext(session)
cfg = ctx.get_task_graph_config()
metrics = json.loads(ctx.get_predecessor_return_value("TRAIN_MODEL"))
if metrics["accuracy"] >= float(cfg["threshold"]):
return "PROMOTE_MODEL" # Must match task name exactly (case-sensitive)
return "SEND_ALERT"
# --- Warehouse tasks: conditional paths ---
def promote_model(session: Session) -> str:
ctx = TaskContext(session)
metrics = json.loads(ctx.get_predecessor_return_value("TRAIN_MODEL"))
# ... register model to registry ...
return "Model promoted"
def send_alert(session: Session) -> None:
# ... send notification ...
pass
def cleanup(session: Session) -> None:
"""Finalizer: always runs regardless of success/failure."""
# ... cleanup temp artifacts ...
pass
# --- Build the DAG ---
with DAG(
name="ML_TRAINING_PIPELINE",
schedule=timedelta(days=1),
stage_location=DAG_STAGE,
use_func_return_value=True,
config={"threshold": "0.90", "model_name": "MY_MODEL"},
) as dag:
prep = DAGTask("PREPARE_DATA", prepare_data, warehouse=WAREHOUSE)
train = DAGTask("TRAIN_MODEL", definition=train_model) # @remote: no warehouse!
check = DAGTaskBranch("CHECK_QUALITY", check_quality, warehouse=WAREHOUSE)
promote = DAGTask("PROMOTE_MODEL", promote_model, warehouse=WAREHOUSE)
alert = DAGTask("SEND_ALERT", send_alert, warehouse=WAREHOUSE)
final = DAGTask("CLEANUP", cleanup, warehouse=WAREHOUSE, is_finalizer=True) # runs automatically
prep >> train >> check >> [promote, alert]
# --- Deploy (session setup per environment guide) ---
root = Root(session)
dag_op = DAGOperation(root.databases[DATABASE].schemas[SCHEMA])
dag_op.deploy(dag, mode="orReplace")
Key patterns:
@remote runs on compute pool — use definition= parameter, no warehouse
- Warehouse tasks for orchestration, branching, lightweight ops
TaskContext passes data between tasks via JSON
config={} on DAG → tasks read via ctx.get_task_graph_config() (all values must be strings)
- Branch return values must match task names exactly
Alternative: For file-based payloads, use MLJobDefinition.register():
from snowflake.ml.jobs import MLJobDefinition
job_def = MLJobDefinition.register("/path/to/script.py", compute_pool=POOL, stage_name=STAGE, session=session)
train_task = DAGTask("TRAIN", definition=job_def)
Workflows
Workflow 1: Create Pipeline
- Gather requirements — What does it do? How often? Which database.schema?
- Generate code — Use Pipeline Template above
- Deploy —
dag_op.deploy(dag, mode="orReplace")
- Ask about execution — Offer to run the DAG to test it —
dag_op.run(dag)
- Verify — Snowsight → Monitoring → Task History
⚠️ MANDATORY STOPPING POINT: Wait for user requirements before generating code.
Workflow 2: Add Task to Existing DAG
- Get structure —
SHOW TASKS LIKE '%DAG_NAME%' IN SCHEMA ...
- Add to DAG definition:
with DAG(...) as dag:
# ... existing tasks ...
new_ml_task = DAGTask("NEW_ML", definition=new_remote_fn) # @remote
new_orch_task = DAGTask("NEW_ORCH", new_warehouse_fn, warehouse=WH) # warehouse
existing >> new_ml_task >> new_orch_task
- Redeploy —
dag_op.deploy(dag, mode="orReplace")
⚠️ MANDATORY STOPPING POINT: Present changes and wait for approval before deploying.
Workflow 3: Convert Notebook
- Identify notebook — Confirm which notebook to convert
- Extract functions — Each cell group becomes a function (
@remote for ML, warehouse for orchestration)
- Deploy — Follow Pipeline Template above
⚠️ MANDATORY STOPPING POINT: Wait for user confirmation.
Quick Reference
| Pattern |
Use Case |
@remote + definition= |
ML tasks on compute pool |
warehouse= |
Orchestration, branching |
config={"key": "val"} on DAG |
Shared settings (all values must be strings) |
ctx.set_return_value() |
Pass data from task |
ctx.get_predecessor_return_value("TASK") |
Read data from predecessor |
ctx.get_task_graph_config() |
Read DAG config |
DAGTaskBranch |
Conditional paths |
is_finalizer=True |
Cleanup (always runs) |
Scheduling (in DAG())
DAG(name="MY_DAG", schedule=timedelta(days=1), ...) # Daily
DAG(name="MY_DAG", schedule=Cron("0 9 * * *", "America/Los_Angeles"), ...) # 9am PT
DAG(name="MY_DAG", schedule=None, ...) # Manual only
Required Privileges
GRANT EXECUTE TASK ON ACCOUNT TO ROLE <role>;
GRANT EXECUTE MANAGED TASK ON ACCOUNT TO ROLE <role>; -- if using managed schedules
Related Skills & References
ml-jobs/SKILL.md — Compute pools, @remote details, EAI setup
model-registry/SKILL.md — Model registration
references/operations.md — Scheduling, monitoring, error handling
External: Official e2e_task_graph sample | Task Graph Docs
1---2name: ml-pipeline-orchestration3description: "Create and deploy ML pipelines using Snowflake Task Graphs (DAGs). Use when: orchestrating ML workflows, scheduling training/inference, converting notebooks to production DAGs, automating model retraining, building task graphs. Triggers: pipeline, DAG, task graph, schedule training, orchestrate, productionize, automate retraining."4path: machine-learning/ml-pipeline-orchestration5parent_skill: machine-learning6metadata:7 source: https://skillmd.com/skills/s-14-h/ml-pipeline-orchestration8---910# ML Pipeline Orchestration1112Orchestrate ML workflows using Snowflake Task Graphs (DAGs). **Use `@remote` for ML tasks** (compute pool) — cheaper, ML dependencies included.1314## When to Use1516- User wants to **schedule** ML training or inference17- User wants to **orchestrate** multiple ML steps (prep → train → evaluate → deploy)18- User wants to **convert a notebook** into a production pipeline19- User mentions: "DAG", "task graph", "pipeline", "schedule training", "productionize"2021## ⚠️ CRITICAL: Environment Guide Check2223**Before proceeding**, verify you have the environment guide from `machine-learning/SKILL.md` → Step 0.2425---2627## Key Concepts2829```python30from snowflake.core.task.dagv1 import DAG, DAGTask, DAGTaskBranch, DAGOperation31from snowflake.core.task.context import TaskContext32from snowflake.core.task import Cron33from snowflake.ml.jobs import remote34```3536- **Compute pool tasks:** Run on compute pool via `@remote` or `MLJobDefinition` — cheaper, ML packages included37- **Warehouse tasks:** Run as stored procedures — use for lightweight orchestration, branching38- **`TaskContext`:** Pass data between tasks via `get_predecessor_return_value()` / `set_return_value()`39- **DAG `config`:** Pass shared settings via `config={"key": "value"}` on the DAG; tasks read via `TaskContext.get_task_graph_config()`40- **Dependencies:** `task_a >> task_b` (sequential), `task >> [a, b]` (fan-out)4142---4344## API Gotchas4546| Wrong | Correct |47|-------|---------|48| `DAGTask("T", my_remote_fn, warehouse=WH)` | `DAGTask("T", definition=my_remote_fn)` — no warehouse for `@remote` |49| `DAG(database=X, schema=Y)` | `DAGOperation(schema_ref)` — database/schema set via DAGOperation |50| `schedule="0 * * * *"` | `schedule=Cron("0 * * * *", "UTC")` or `timedelta(hours=1)` |51| Branch returns `"deploy"` | Branch returns `"PROMOTE_MODEL"` — must match task name exactly |52| `return result` in `@remote` | `ctx.set_return_value(json.dumps(result))` — must use TaskContext |53| `TaskContext` fails with `ModuleNotFoundError` | Add `snowflake.core` to DAG `packages=[]` — `snowflake-ml-python >=1.29` no longer includes it |5455---5657## Pipeline Template5859```python60import json61from datetime import timedelta62from snowflake.core import Root63from snowflake.core.task.dagv1 import DAG, DAGTask, DAGTaskBranch, DAGOperation64from snowflake.core.task.context import TaskContext65from snowflake.core.task import Cron66from snowflake.ml.jobs import remote67from snowflake.snowpark import Session6869# Configuration70DATABASE = "<DATABASE>"71SCHEMA = "<SCHEMA>"72WAREHOUSE = "<WAREHOUSE>"73COMPUTE_POOL = "<COMPUTE_POOL>"74DAG_STAGE = f"@{DATABASE}.{SCHEMA}.DAG_STAGE"75JOB_STAGE = f"@{DATABASE}.{SCHEMA}.JOB_STAGE"7677# --- Warehouse task: lightweight data prep ---78def prepare_data(session: Session) -> str:79 """Prepare datasets, return info as JSON for downstream tasks."""80 # ... data prep logic ...81 return json.dumps({"train_table": "TRAIN_DATA", "test_table": "TEST_DATA"})8283# --- @remote task: heavy ML training on compute pool ---84@remote(COMPUTE_POOL, stage_name=JOB_STAGE, database=DATABASE, schema=SCHEMA)85def train_model() -> None:86 """Train model on compute pool. Access predecessor data via TaskContext."""87 session = Session.builder.getOrCreate()88 ctx = TaskContext(session)8990 # Get data from predecessor task91 data_info = json.loads(ctx.get_predecessor_return_value("PREPARE_DATA"))9293 # ... training logic using data_info ...94 model_metrics = {"accuracy": 0.95, "model_path": "models/v1.pkl"}9596 # Pass results to successor tasks97 ctx.set_return_value(json.dumps(model_metrics))9899# --- Warehouse task: branching logic ---100def check_quality(session: Session) -> str:101 """Check model quality, return next task name."""102 ctx = TaskContext(session)103 cfg = ctx.get_task_graph_config()104 metrics = json.loads(ctx.get_predecessor_return_value("TRAIN_MODEL"))105106 if metrics["accuracy"] >= float(cfg["threshold"]):107 return "PROMOTE_MODEL" # Must match task name exactly (case-sensitive)108 return "SEND_ALERT"109110# --- Warehouse tasks: conditional paths ---111def promote_model(session: Session) -> str:112 ctx = TaskContext(session)113 metrics = json.loads(ctx.get_predecessor_return_value("TRAIN_MODEL"))114 # ... register model to registry ...115 return "Model promoted"116117def send_alert(session: Session) -> None:118 # ... send notification ...119 pass120121def cleanup(session: Session) -> None:122 """Finalizer: always runs regardless of success/failure."""123 # ... cleanup temp artifacts ...124 pass125126# --- Build the DAG ---127with DAG(128 name="ML_TRAINING_PIPELINE",129 schedule=timedelta(days=1),130 stage_location=DAG_STAGE,131 use_func_return_value=True,132 config={"threshold": "0.90", "model_name": "MY_MODEL"},133) as dag:134 prep = DAGTask("PREPARE_DATA", prepare_data, warehouse=WAREHOUSE)135 train = DAGTask("TRAIN_MODEL", definition=train_model) # @remote: no warehouse!136 check = DAGTaskBranch("CHECK_QUALITY", check_quality, warehouse=WAREHOUSE)137 promote = DAGTask("PROMOTE_MODEL", promote_model, warehouse=WAREHOUSE)138 alert = DAGTask("SEND_ALERT", send_alert, warehouse=WAREHOUSE)139 final = DAGTask("CLEANUP", cleanup, warehouse=WAREHOUSE, is_finalizer=True) # runs automatically140141 prep >> train >> check >> [promote, alert]142143# --- Deploy (session setup per environment guide) ---144root = Root(session)145dag_op = DAGOperation(root.databases[DATABASE].schemas[SCHEMA])146dag_op.deploy(dag, mode="orReplace")147```148149**Key patterns:**150- `@remote` runs on compute pool — use `definition=` parameter, no warehouse151- Warehouse tasks for orchestration, branching, lightweight ops152- `TaskContext` passes data between tasks via JSON153- `config={}` on DAG → tasks read via `ctx.get_task_graph_config()` (all values must be strings)154- Branch return values must match task names exactly155156**Alternative:** For file-based payloads, use `MLJobDefinition.register()`:157```python158from snowflake.ml.jobs import MLJobDefinition159job_def = MLJobDefinition.register("/path/to/script.py", compute_pool=POOL, stage_name=STAGE, session=session)160train_task = DAGTask("TRAIN", definition=job_def)161```162163---164165## Workflows166167### Workflow 1: Create Pipeline1681691. **Gather requirements** — What does it do? How often? Which database.schema?1702. **Generate code** — Use Pipeline Template above1713. **Deploy** — `dag_op.deploy(dag, mode="orReplace")`1724. **Ask about execution** — Offer to run the DAG to test it — `dag_op.run(dag)`1735. **Verify** — Snowsight → Monitoring → Task History174175**⚠️ MANDATORY STOPPING POINT**: Wait for user requirements before generating code.176177### Workflow 2: Add Task to Existing DAG1781791. **Get structure** — `SHOW TASKS LIKE '%DAG_NAME%' IN SCHEMA ...`1802. **Add to DAG definition:**181 ```python182 with DAG(...) as dag:183 # ... existing tasks ...184 new_ml_task = DAGTask("NEW_ML", definition=new_remote_fn) # @remote185 new_orch_task = DAGTask("NEW_ORCH", new_warehouse_fn, warehouse=WH) # warehouse186 existing >> new_ml_task >> new_orch_task187 ```1883. **Redeploy** — `dag_op.deploy(dag, mode="orReplace")`189190**⚠️ MANDATORY STOPPING POINT**: Present changes and wait for approval before deploying.191192### Workflow 3: Convert Notebook1931941. **Identify notebook** — Confirm which notebook to convert1952. **Extract functions** — Each cell group becomes a function (`@remote` for ML, warehouse for orchestration)1963. **Deploy** — Follow Pipeline Template above197198**⚠️ MANDATORY STOPPING POINT**: Wait for user confirmation.199200---201202## Quick Reference203204| Pattern | Use Case |205|---------|----------|206| `@remote` + `definition=` | ML tasks on compute pool |207| `warehouse=` | Orchestration, branching |208| `config={"key": "val"}` on DAG | Shared settings (all values must be strings) |209| `ctx.set_return_value()` | Pass data from task |210| `ctx.get_predecessor_return_value("TASK")` | Read data from predecessor |211| `ctx.get_task_graph_config()` | Read DAG config |212| `DAGTaskBranch` | Conditional paths |213| `is_finalizer=True` | Cleanup (always runs) |214215### Scheduling (in `DAG()`)216217```python218DAG(name="MY_DAG", schedule=timedelta(days=1), ...) # Daily219DAG(name="MY_DAG", schedule=Cron("0 9 * * *", "America/Los_Angeles"), ...) # 9am PT220DAG(name="MY_DAG", schedule=None, ...) # Manual only221```222223### Required Privileges224225```sql226GRANT EXECUTE TASK ON ACCOUNT TO ROLE <role>;227GRANT EXECUTE MANAGED TASK ON ACCOUNT TO ROLE <role>; -- if using managed schedules228```229230---231232## Related Skills & References233234- `ml-jobs/SKILL.md` — Compute pools, `@remote` details, EAI setup235- `model-registry/SKILL.md` — Model registration236- `references/operations.md` — Scheduling, monitoring, error handling237238**External:** [Official e2e_task_graph sample](https://github.com/Snowflake-Labs/sf-samples/tree/main/samples/ml/ml_jobs/e2e_task_graph) | [Task Graph Docs](https://docs.snowflake.com/en/developer-guide/snowflake-python-api/snowflake-python-managing-tasks)