|
| 1 | +# `BatchInferencePipeline` |
| 2 | + |
| 3 | +Source: `ds_platform_utils.metaflow.batch_inference_pipeline.BatchInferencePipeline` |
| 4 | + |
| 5 | +Utility class to orchestrate batch inference with Snowflake + S3 in Metaflow steps. |
| 6 | + |
| 7 | +## Main methods |
| 8 | + |
| 9 | +- `query_and_batch(...)`: export source data to S3 and create worker batches. |
| 10 | +- `process_batch(...)`: run download → inference → upload for one worker. |
| 11 | +- `publish_results(...)`: copy prediction outputs from S3 to Snowflake. |
| 12 | +- `run(...)`: convenience method to execute full flow sequentially. |
| 13 | + |
| 14 | +## Detailed example (Metaflow foreach) |
| 15 | + |
| 16 | +This example shows the intended 3-step pattern in a Metaflow `FlowSpec`: |
| 17 | + |
| 18 | +1. `query_and_batch()` in `start` |
| 19 | +2. `process_batch()` in `foreach` |
| 20 | +3. `publish_results()` in `join` |
| 21 | + |
| 22 | +```python |
| 23 | +from metaflow import FlowSpec, step |
| 24 | +import pandas as pd |
| 25 | + |
| 26 | +from ds_platform_utils.metaflow import BatchInferencePipeline |
| 27 | + |
| 28 | + |
| 29 | +def predict_fn(df: pd.DataFrame) -> pd.DataFrame: |
| 30 | + # Example model logic |
| 31 | + out = pd.DataFrame() |
| 32 | + out["id"] = df["id"] |
| 33 | + out["score"] = (df["feature_1"].fillna(0) * 0.7 + df["feature_2"].fillna(0) * 0.3).round(6) |
| 34 | + out["label"] = (out["score"] >= 0.5).astype(int) |
| 35 | + return out |
| 36 | + |
| 37 | + |
| 38 | +class BatchPredictFlow(FlowSpec): |
| 39 | + |
| 40 | + @step |
| 41 | + def start(self): |
| 42 | + self.next(self.query_and_batch) |
| 43 | + |
| 44 | + @step |
| 45 | + def query_and_batch(self): |
| 46 | + self.pipeline = BatchInferencePipeline() |
| 47 | + |
| 48 | + # Query can be inline SQL or a file path. |
| 49 | + # {schema} is provided by ds_platform_utils (DEV/PROD selection). |
| 50 | + self.worker_ids = self.pipeline.query_and_batch( |
| 51 | + input_query=""" |
| 52 | + SELECT |
| 53 | + id, |
| 54 | + feature_1, |
| 55 | + feature_2 |
| 56 | + FROM {{schema}}.model_features |
| 57 | + WHERE ds = '2026-02-26' |
| 58 | + """, |
| 59 | + parallel_workers=8, |
| 60 | + warehouse="MED", |
| 61 | + use_utc=True, |
| 62 | + ) |
| 63 | + |
| 64 | + self.next(self.process_batch, foreach="worker_ids") |
| 65 | + |
| 66 | + @step |
| 67 | + def process_batch(self): |
| 68 | + # In a foreach step, self.input contains one worker_id. |
| 69 | + self.pipeline.process_batch( |
| 70 | + worker_id=self.input, |
| 71 | + predict_fn=predict_fn, |
| 72 | + batch_size_in_mb=256, |
| 73 | + timeout_per_batch=300, |
| 74 | + ) |
| 75 | + self.next(self.publish_results) |
| 76 | + |
| 77 | + @step |
| 78 | + def publish_results(self, inputs): |
| 79 | + # Reuse one pipeline object from foreach branches. |
| 80 | + self.pipeline = inputs[0].pipeline |
| 81 | + |
| 82 | + self.pipeline.publish_results( |
| 83 | + output_table_name="MODEL_PREDICTIONS_DAILY", |
| 84 | + output_table_definition=[ |
| 85 | + ("id", "NUMBER"), |
| 86 | + ("score", "FLOAT"), |
| 87 | + ("label", "NUMBER"), |
| 88 | + ], |
| 89 | + auto_create_table=True, |
| 90 | + overwrite=True, |
| 91 | + warehouse="MED", |
| 92 | + use_utc=True, |
| 93 | + ) |
| 94 | + self.next(self.end) |
| 95 | + |
| 96 | + @step |
| 97 | + def end(self): |
| 98 | + print("Batch inference complete") |
| 99 | +``` |
| 100 | + |
| 101 | +## Detailed example (single-step convenience) |
| 102 | + |
| 103 | +Use `run()` when you do not need Metaflow foreach parallelization: |
| 104 | + |
| 105 | +```python |
| 106 | +from ds_platform_utils.metaflow import BatchInferencePipeline |
| 107 | +import pandas as pd |
| 108 | + |
| 109 | + |
| 110 | +@step |
| 111 | +def batch_inference_step(self): |
| 112 | + def predict_fn(df: pd.DataFrame) -> pd.DataFrame: |
| 113 | + return pd.DataFrame( |
| 114 | + { |
| 115 | + "id": df["id"], |
| 116 | + "score": (df["feature_1"] * 0.9).fillna(0), |
| 117 | + } |
| 118 | + ) |
| 119 | + |
| 120 | + pipeline = BatchInferencePipeline() |
| 121 | + pipeline.run( |
| 122 | + input_query=""" |
| 123 | + SELECT id, feature_1 |
| 124 | + FROM {{schema}}.model_features |
| 125 | + WHERE ds = '2026-02-26' |
| 126 | + """, |
| 127 | + output_table_name="MODEL_PREDICTIONS_DAILY", |
| 128 | + predict_fn=predict_fn, |
| 129 | + output_table_definition=[("id", "NUMBER"), ("score", "FLOAT")], |
| 130 | + warehouse="XL", |
| 131 | + ) |
| 132 | + |
| 133 | + self.next(self.end) |
| 134 | +``` |
| 135 | + |
| 136 | +## Parameters |
| 137 | + |
| 138 | +### `query_and_batch(...)` |
| 139 | + |
| 140 | +| Parameter | Type | Required | Description | |
| 141 | +| ------------------ | ------------- | -------: | ----------------------------------------------------------------------------------------------------------------------- | |
| 142 | +| `input_query` | `str \| Path` | Yes | SQL query string or SQL file path used to fetch source rows. `{schema}` placeholder is resolved by `ds_platform_utils`. | |
| 143 | +| `ctx` | `dict` | No | Optional substitution map for templated SQL; merged with the internal `{"schema": ...}` mapping before query execution. | |
| 144 | +| `warehouse` | `str` | No | Snowflake warehouse used to execute the source query/export. | |
| 145 | +| `use_utc` | `bool` | No | If `True`, uses UTC timestamps/paths for partitioning and run metadata. | |
| 146 | +| `parallel_workers` | `int` | No | Number of worker partitions to create for downstream processing. | |
| 147 | + |
| 148 | +**Returns:** `list[int]` of `worker_id` values for Metaflow `foreach`. |
| 149 | + |
| 150 | +--- |
| 151 | + |
| 152 | +### `process_batch(...)` |
| 153 | + |
| 154 | +| Parameter | Type | Required | Description | |
| 155 | +| ------------------- | ---------------------------------------- | -------: | -------------------------------------------------------------------------------------------------------- | |
| 156 | +| `worker_id` | `int` | Yes | Worker partition identifier generated by `query_and_batch()`. | |
| 157 | +| `predict_fn` | `Callable[[pd.DataFrame], pd.DataFrame]` | Yes | Inference function applied to each input chunk. Must return a DataFrame matching expected output schema. | |
| 158 | +| `batch_size_in_mb` | `int` | No | Target chunk size for reading/processing batch files. | |
| 159 | +| `timeout_per_batch` | `int` | No | Processing time for each batch in seconds. (Used for Queuing operations) | |
| 160 | + |
| 161 | +**Returns:** `None` |
| 162 | + |
| 163 | +**Recommended**: Tune `batch_size_in_mb` for Outerbounds Small tasks (3 CPU, 15 GB memory), which are about 6x more cost-effective than Medium tasks. |
| 164 | + |
| 165 | +## Limitations |
| 166 | + |
| 167 | +- The pipeline uses Snowflake ↔ S3 stage copy operations, so some column data types may be inferred differently than expected. |
| 168 | +- For predictable output types, provide an explicit `output_table_definition` in `publish_results(...)` / `run(...)` and cast columns in `predict_fn` as needed. |
| 169 | + |
| 170 | +### `publish_results(...)` |
| 171 | + |
| 172 | +| Parameter | Type | Required | Description | |
| 173 | +| ------------------------- | ------------------------------- | -------: | ----------------------------------------------------------------- | |
| 174 | +| `output_table_name` | `str` | Yes | Destination Snowflake table for predictions. | |
| 175 | +| `output_table_definition` | `list[tuple[str, str]] \| None` | No | Optional output schema as `(column_name, snowflake_type)` tuples. | |
| 176 | +| `auto_create_table` | `bool` | No | If `True`, creates destination table when missing. | |
| 177 | +| `overwrite` | `bool` | No | If `True`, replaces existing table data before loading results. | |
| 178 | +| `warehouse` | `str` | No | Snowflake warehouse used for load/publish operations. | |
| 179 | +| `use_utc` | `bool` | No | If `True`, uses UTC for load metadata/time handling. | |
| 180 | + |
| 181 | +**Returns:** `None` |
| 182 | + |
| 183 | +--- |
| 184 | + |
| 185 | +### `run(...)` (convenience method) |
| 186 | + |
| 187 | +Runs `query_and_batch()` → `process_batch()` → `publish_results()` in a single sequential call. |
| 188 | + |
| 189 | +| Parameter | Type | Required | Description | |
| 190 | +| ------------------------- | ---------------------------------------- | -------: | ----------------------------------------------------------------------------------------------------------------------- | |
| 191 | +| `input_query` | `str \| Path` | Yes | SQL query string or SQL file path used to fetch source rows. `{schema}` placeholder is resolved by `ds_platform_utils`. | |
| 192 | +| `output_table_name` | `str` | Yes | Destination Snowflake table for predictions. | |
| 193 | +| `predict_fn` | `Callable[[pd.DataFrame], pd.DataFrame]` | Yes | Inference function applied to each input chunk. Must return a DataFrame matching expected output schema. | |
| 194 | +| `ctx` | `dict` | No | Optional substitution map for templated SQL; merged with the internal `{"schema": ...}` mapping before query execution. | |
| 195 | +| `output_table_definition` | `list[tuple[str, str]] \| None` | No | Optional output schema as `(column_name, snowflake_type)` tuples. | |
| 196 | +| `batch_size_in_mb` | `int` | No | Target chunk size for reading/processing batch files. | |
| 197 | +| `timeout_per_batch` | `int` | No | Processing time for each batch in seconds. (Used for Queuing operations) | |
| 198 | +| `auto_create_table` | `bool` | No | If `True`, creates destination table when missing. | |
| 199 | +| `overwrite` | `bool` | No | If `True`, replaces existing table data before loading results. | |
| 200 | +| `warehouse` | `str` | No | Snowflake warehouse used for load/publish operations. | |
| 201 | +| `use_utc` | `bool` | No | If `True`, uses UTC for load metadata/time handling. | |
| 202 | + |
| 203 | +**Returns:** `None` |
| 204 | + |
| 205 | +**Recommended**: Tune `batch_size_in_mb` for Outerbounds Small tasks (3 CPU, 15 GB memory), which are about 6x more cost-effective than Medium tasks. |
0 commit comments