Skip to content

ML functions

Igloo trains and scores predictive models in SQL, with the statements and methods of Snowflake’s ML classes, so the SQL that uses them on Snowflake runs on Igloo as written. A model is an object in a schema, like a table: it is created from a table, view or query, used by its owner and whoever they grant it to, and dropped.

CREATE SNOWFLAKE.ML.CLASSIFICATION demo.conversion(
INPUT_DATA => SYSTEM$REFERENCE('VIEW', 'demo.lead_features'),
TARGET_COLNAME => 'converted');
SELECT person_id,
demo.conversion!PREDICT(INPUT_DATA => {*}):probability:True::FLOAT AS p_convert
FROM demo.new_leads;
CALL demo.conversion!SHOW_GLOBAL_EVALUATION_METRICS();
Class What it does Methods
SNOWFLAKE.ML.FORECAST Forecasts one or many time series, with prediction intervals FORECAST, SHOW_EVALUATION_METRICS, EXPLAIN_FEATURE_IMPORTANCE, SHOW_TRAINING_LOGS
SNOWFLAKE.ML.ANOMALY_DETECTION Flags new points of time series that fall outside their forecast’s interval DETECT_ANOMALIES, SHOW_EVALUATION_METRICS, EXPLAIN_FEATURE_IMPORTANCE, SHOW_TRAINING_LOGS
SNOWFLAKE.ML.CLASSIFICATION Predicts a class (2 to 255) from a row’s columns PREDICT, SHOW_EVALUATION_METRICS, SHOW_GLOBAL_EVALUATION_METRICS, SHOW_CONFUSION_MATRIX, SHOW_THRESHOLD_METRICS, SHOW_FEATURE_IMPORTANCE, SHOW_TRAINING_LOGS
SNOWFLAKE.ML.TOP_INSIGHTS Finds the segments that drove a metric’s change between two groups GET_DRIVERS

Igloo has classes of its own too, IGLOO.ML.<class>, which bring BigQuery ML’s model types with the same statements (see Igloo’s classes), and IGLOO.ML.XGBOOST, which trains XGBoost’s own models.

Besides the classes, Databricks’ ai_predict_class and ai_predict_value train a model and score rows in one query, keeping no model (see below).

Time series can also be forecast by foundation models, pretrained on many series and run zero-shot from the model pack: Amazon’s Chronos-Bolt and Chronos-2 and Google’s TimesFM 2.5. FORECAST and ANOMALY_DETECTION take one as their method (below), and BigQuery’s AI.FORECAST and AI.DETECT_ANOMALIES and Databricks’ ai_forecast and ai_detect_anomalies forecast with them in a query (below).

Models are trained by Igloo’s own engine: gradient-boosted trees, as Snowflake’s classes use (see the engine). Training reads its input as the user who creates the model, through their grants and policies; scoring with PREDICT runs wherever the query runs, on workers too.

These are Snowflake’s statements, which Igloo reads in either SQL dialect. In the DuckDB dialect, too, their arguments and the queries in them are Snowflake’s SQL.

CREATE [ OR REPLACE ] SNOWFLAKE.ML.<class> [ IF NOT EXISTS ] name( <arguments> )
[ [ WITH ] TAG ( ... ) ] [ COMMENT = 'text' ]
DROP SNOWFLAKE.ML.<class> [ IF EXISTS ] name
SHOW SNOWFLAKE.ML.<class> [ INSTANCES ] [ LIKE 'pattern' ] [ IN ACCOUNT | DATABASE | SCHEMA [ name ] ]
CALL name!<method>( <arguments> )
SELECT ... FROM TABLE( name!<method>( <arguments> ) )
GRANT USAGE ON SNOWFLAKE.ML.<class> name TO [ ROLE | USER ] grantee
GRANT SNOWFLAKE.ML.<class> ROLE name!MLADMIN | MLCONSUMER TO [ ROLE | USER ] grantee
REVOKE ... FROM [ ROLE | USER ] grantee
  • Names. A model’s name is name, schema.name or database.schema.name, where the database is the catalog’s. A name alone is in the session’s current schema. Names are case-insensitive.
  • Arguments are named (TARGET_COLNAME => 'converted'), as in Snowflake’s documentation; they are literals, objects such as {'evaluate': FALSE}, and references to rows.
  • Training data. INPUT_DATA takes a table or view, TABLE(name) or SYSTEM$REFERENCE('TABLE' | 'VIEW', 'name'), or a query, SYSTEM$QUERY_REFERENCE('SELECT ...'). Every column but the target is a feature: numbers are continuous, strings and booleans categories, and timestamps and dates their seconds since 1970. Other types are refused: cast them.
  • CREATE OR REPLACE trains the model again, under the same name; its grants stay. Models never change otherwise: ALTER is refused, and COMMENT is set when a model is created. TAG is accepted and ignored, with a notice. A model’s row records the CREATE statement that trained it, its configuration and a summary of its metrics.
  • Methods that return rows run with CALL, or as a table in a query with TABLE(name!METHOD(...)), which can be filtered, joined and saved with CREATE TABLE ... AS. In Snowflake’s dialect their columns are named in upper case. name!PREDICT(...) is an expression.
  • SHOW lists the models of a class the user may use, with Snowflake’s columns: created_on, name, database_name, schema_name, current_version, comment and owner.
To Takes
Create a model in a schema What creating a table there takes: the writer role, or CREATE on the schema (GRANT CREATE ON SCHEMA demo TO …)
Replace, drop or grant a model Owning it (its creator), or the admin role
Call every method Owning it, admin, or USAGE (Snowflake’s MLADMIN instance role)
Predict: PREDICT, FORECAST, DETECT_ANOMALIES, GET_DRIVERS, and Igloo’s classes’ EXPLAIN_PREDICT, RECOMMEND and RECONSTRUCTION_LOSS Any of those, or Snowflake’s MLCONSUMER instance role

A user who may not use a model is told it does not exist. A model answers from what its creator could read when it was trained; whoever may use it gets its predictions, not its training rows. They read the rows they score through their own grants and policies, as in any query. Snowflake’s GRANT CREATE SNOWFLAKE.ML.<class> ON SCHEMA is refused: grant CREATE on the schema.

When a user is dropped, their models are marked as a dropped user’s: SHOW gives their owner as ana (dropped), as for their alerts and tasks. A user created later with the same name, by an admin or by signing in with single sign-on, does not own them; admins may use, grant and drop them, or CREATE OR REPLACE them as their own, and an erasure request cannot train them again until one does. Dropping a user or a role also takes back the models granted to it, so that a user or role created later with the same name does not get them. Grants to others stay.

Earlier versions did neither. What users and roles dropped then left behind is dealt with as each replica starts: a model whose owner is no user, or a user created after the model was last trained (so an earlier user of that name was dropped), is marked as a dropped user’s; and a model grant to a user or role that does not exist, or that was created after the grant, is taken back. A model trained again after the new user was created, by them with CREATE OR REPLACE or by an erasure request, counts as theirs. Granting a model again to the new user or role changed nothing then, as the old grant was still there, so it is taken back with the old grant: grant it once more.

CREATE [ OR REPLACE ] SNOWFLAKE.ML.FORECAST [ IF NOT EXISTS ] name(
INPUT_DATA => <table, view or query>,
[ SERIES_COLNAME => '<column>', ]
TIMESTAMP_COLNAME => '<column>',
TARGET_COLNAME => '<column>',
[ CONFIG_OBJECT => { ... } ]
)
CALL name!FORECAST( FORECASTING_PERIODS => n [, SERIES_VALUE => 'series' ] [, CONFIG_OBJECT => { 'prediction_interval': 0.95 } ] )
CALL name!FORECAST( INPUT_DATA => <future rows>, TIMESTAMP_COLNAME => '<column>' [, SERIES_COLNAME => '<column>' ] [, CONFIG_OBJECT => ... ] )
CREATE SNOWFLAKE.ML.FORECAST demo.spend_forecast(
INPUT_DATA => TABLE(demo.daily_spend),
SERIES_COLNAME => 'campaign', TIMESTAMP_COLNAME => 'day', TARGET_COLNAME => 'spend');
CREATE TABLE demo.spend_next_week AS
SELECT * FROM TABLE(demo.spend_forecast!FORECAST(FORECASTING_PERIODS => 7));
  • The method is Snowflake’s fast one, whether method says 'fast' or 'best' (Snowflake’s default, which ensembles models Igloo does not have), unless it names a foundation model (below): gradient-boosted trees on lags and rolling means of the target, calendar features of the timestamp (day of week, month and the like, by the series’ frequency), the other columns of the input (exogenous variables) and the series. Each series is scaled to its mean, and a series with a trend has its linear trend taken out first, which the forecast carries on. One model serves every series of a model. Forecasts are made a step at a time, each on the ones before.
  • Series. SERIES_COLNAME names a column whose values identify series: a model forecasts each. A series needs at least 2 points; one of 2 to 11 points forecasts its last value (a naive forecast), and fewer than 60 training points in all train a linear model rather than trees, as in Snowflake. FORECAST forecasts every series, or SERIES_VALUE’s.
  • Timestamps are timestamps or dates. The frequency is the most common gap between them, or 'frequency', such as '1 day' or '15 minutes' (seconds, minutes, hours, days, weeks, months, quarters and years). Several rows at one step are aggregated: the target and other numbers by their mean, categories by their most common value, unless aggregation_target, aggregation_numeric, aggregation_categorical or aggregation_column ({'promo': 'MAX'}) say otherwise (MEAN, MEDIAN, MODE, MIN, MAX, SUM, FIRST, LAST). Steps without a row are filled in from their neighbours for the lags, and do not train.
  • Exogenous columns. A model trained with columns besides the series, timestamp and target forecasts with their future values: INPUT_DATA holds a row for each future timestamp (and series), and FORECAST returns a forecast for each. Without them it is refused.
  • Prediction intervals come from cross-validation: models trained on each series but its last steps forecast them, and the spread of their errors, by how many steps ahead, sets an interval around each forecast (normal, at prediction_interval, 0.95 by default). They widen with the horizon. lower_bound and upper_bound clamp forecasts and intervals.
  • Evaluation follows scikit-learn’s TimeSeriesSplit, as Snowflake’s: evaluation_config‘s n_splits (default 1), test_size (default each series’ length divided by n_splits + 1), gap and max_train_size. 'evaluate': FALSE keeps no metrics; the intervals still come from cross-validation.
  • on_error: 'skip' leaves out series that cannot be trained (fewer than two points) rather than failing; SHOW_TRAINING_LOGS says which.
Method Columns
FORECAST(…) SERIES (NULL for one series), TS, FORECAST, LOWER_BOUND, UPPER_BOUND
SHOW_EVALUATION_METRICS() SERIES, ERROR_METRIC (MAE, MAPE, MDA, MSE, SMAPE, WINKLER_ALPHA=0.05, COVERAGE_INTERVAL=0.95), METRIC_VALUE, STANDARD_DEVIATION (over the splits; NULL for one), LOGS
SHOW_EVALUATION_METRICS(INPUT_DATA => …, TIMESTAMP_COLNAME => …, TARGET_COLNAME => … [, SERIES_COLNAME => …] [, CONFIG_OBJECT => {‘prediction_interval’: …}]) The same, of forecasts of new data, after the training data
EXPLAIN_FEATURE_IMPORTANCE() SERIES, RANK, FEATURE_NAME, IMPORTANCE_SCORE (shares of the mean absolute SHAP value, adding up to 1 per series), FEATURE_TYPE: derived_from_endogenous for aggregated_endogenous_features (the target’s lags and rolling means together), derived_from_timestamp for calendar features, user_provided for exogenous columns
SHOW_TRAINING_LOGS() SERIES, LOGS

CONFIG_OBJECT’s method may name a forecasting model of the model pack, installed, in place of 'fast' or 'best': an Igloo extension of Snowflake’s options.

CREATE SNOWFLAKE.ML.FORECAST demo.spend_forecast(
INPUT_DATA => TABLE(demo.daily_spend),
SERIES_COLNAME => 'campaign', TIMESTAMP_COLNAME => 'day', TARGET_COLNAME => 'spend',
CONFIG_OBJECT => {'method': 'chronos-2', 'context_window': 512});
  • Names. 'chronos-bolt-tiny', 'chronos-bolt-mini', 'chronos-bolt-small', 'chronos-bolt-base', 'chronos-2', 'chronos-2-small' and 'timesfm-2.5', or a model installed from a manifest; case, spaces and underscores aside ('TimesFM 2.5' is timesfm-2.5). A model the pack lacks is refused when the model is created, saying how to install it.
  • Nothing is trained. The model object keeps each series’ last context_window steps (2,048 by default, at most what the model reads), and FORECAST forecasts from them, zero-shot. Create the model again to forecast from newer data.
  • Intervals are the model’s own quantiles at prediction_interval, interpolated between them; beyond its outermost ones (the 0.1 and 0.9 quantiles for most), they are extended as a normal distribution would be.
  • Evaluation forecasts each split’s test steps from the steps before them, as evaluation_config splits them, with the same metrics. EXPLAIN_FEATURE_IMPORTANCE returns no rows: the models have no features.
  • The input holds the timestamp, the target and the series column alone: the models forecast from the target’s values, and other columns are refused. Several rows at one step are aggregated as for 'fast', and steps without a row are gaps, which the models read as missing.
  • ANOMALY_DETECTION takes a method too: DETECT_ANOMALIES forecasts the new points from the kept steps and flags those outside the interval. PERCENTILE is where the point falls in the model’s forecast distribution, and DISTANCE its z-score, with half the spread of the forecast’s 0.16 to 0.84 quantiles for the standard deviation.
  • Where they run, and how fast: see the model pack.
CREATE [ OR REPLACE ] SNOWFLAKE.ML.ANOMALY_DETECTION [ IF NOT EXISTS ] name(
INPUT_DATA => <table, view or query>,
[ SERIES_COLNAME => '<column>', ]
TIMESTAMP_COLNAME => '<column>',
TARGET_COLNAME => '<column>',
LABEL_COLNAME => '<column>' | '',
[ CONFIG_OBJECT => { ... } ]
)
CALL name!DETECT_ANOMALIES(
INPUT_DATA => <new rows>, TIMESTAMP_COLNAME => '<column>', TARGET_COLNAME => '<column>'
[, SERIES_COLNAME => '<column>' ] [, CONFIG_OBJECT => { 'prediction_interval': 0.99 } ] )
  • An anomaly model is a forecast model: DETECT_ANOMALIES forecasts the new points’ timestamps, which must come after the training data’s, and flags those outside their prediction interval (0.99 by default), as Snowflake’s does. CONFIG_OBJECT takes what FORECAST’s does; its evaluation has 5 splits by default.
  • LABEL_COLNAME names a boolean column of known anomalies, which do not train the model; '' means none. Unlabeled anomalies in the training data are left out too: points far outside a first fit (five times its typical error) are dropped and the model trained again.
Method Columns
DETECT_ANOMALIES(…) SERIES, TS, Y, FORECAST, LOWER_BOUND, UPPER_BOUND, IS_ANOMALY, PERCENTILE (where Y falls in the forecast’s distribution), DISTANCE (its z-score)
SHOW_EVALUATION_METRICS, EXPLAIN_FEATURE_IMPORTANCE, SHOW_TRAINING_LOGS As FORECAST’s
CREATE [ OR REPLACE ] SNOWFLAKE.ML.CLASSIFICATION [ IF NOT EXISTS ] name(
INPUT_DATA => <table, view or query>,
TARGET_COLNAME => '<column>',
[ CONFIG_OBJECT => { 'evaluate': TRUE | FALSE,
'evaluation_config': { 'test_fraction': <fraction> },
'on_error': 'ABORT' | 'SKIP' } ]
)
  • The target is a boolean, number or string column with 2 to 255 distinct values. Rows whose target is NULL are left out, and SHOW_TRAINING_LOGS says how many. Two classes train a binary model, more a multiclass one.

  • Evaluation. Unless 'evaluate': FALSE, a sample of each class is held out, the model trained on the rest is measured on it, and the model is then trained again on every row. The sample is Snowflake’s default, enough for 500 rows of the rarest class but at most 20% of each, or test_fraction of each class.

  • PREDICT takes INPUT_DATA, an object of the row’s features: {*} (every column of the query’s FROM), {* EXCLUDE (id, label)}, {t.*}, OBJECT_CONSTRUCT(*), or keys and values such as {'region': region, 'spend': spend} or OBJECT_CONSTRUCT('region', region). Features it does not give are missing. It returns Snowflake’s object:

    {"class": "True", "logs": null, "probability": {"False": 0.0118, "True": 0.9882}}

    Booleans’ classes are True and False, numbers’ as they read (0, 1, 2.5), strings as they are. Read the class with :class::STRING and a probability with :probability:True::FLOAT.

Method Columns
SHOW_EVALUATION_METRICS() DATASET_TYPE (EVAL), CLASS, ERROR_METRIC (precision, recall, f1, support), METRIC_VALUE, LOGS
SHOW_GLOBAL_EVALUATION_METRICS() DATASET_TYPE, AVERAGE_TYPE (macro, weighted, or NULL for log_loss), ERROR_METRIC (precision, recall, f1, auc, log_loss), METRIC_VALUE, LOGS
SHOW_CONFUSION_MATRIX() DATASET_TYPE, ACTUAL_CLASS, PREDICTED_CLASS, COUNT, LOGS
SHOW_THRESHOLD_METRICS() DATASET_TYPE, CLASS, THRESHOLD (0 to 1 by 0.01), PRECISION, RECALL, F1, TPR, FPR, TP, FP, TN, FN, ACCURACY, SUPPORT, LOGS
SHOW_FEATURE_IMPORTANCE() RANK, FEATURE, SCORE (each feature’s share of the mean absolute SHAP value, adding up to 1), FEATURE_TYPE (user_provided)
SHOW_TRAINING_LOGS() LOGS

The evaluation methods fail for a model trained with 'evaluate': FALSE.

CREATE [ OR REPLACE ] SNOWFLAKE.ML.TOP_INSIGHTS [ IF NOT EXISTS ] name();
CALL name!GET_DRIVERS(
INPUT_DATA => <table, view or query>,
LABEL_COLNAME => '<boolean column: TRUE for test rows, FALSE for control>',
METRIC_COLNAME => '<number column>' );
CREATE SNOWFLAKE.ML.TOP_INSIGHTS demo.spend_drivers();
SELECT * FROM TABLE(demo.spend_drivers!GET_DRIVERS(
INPUT_DATA => SYSTEM$QUERY_REFERENCE($$
SELECT country, device, channel, day >= '2026-10-01' AS is_test, spend
FROM demo.daily_spend WHERE day >= '2026-09-01'$$),
LABEL_COLNAME => 'is_test', METRIC_COLNAME => 'spend'));
  • Every column but the label and the metric is a dimension: strings and booleans are categories, numbers (and timestamps) continuous. A dimension’s 25 most influential categories are considered.
  • A tree splits the rows, at each segment by the condition whose rows’ change departs most from the segment’s own rate of change (|test - control * test/control| of the rows that meet it): a category (COUNTRY = us and not COUNTRY = us) or a threshold (AGE <= 30.5 and AGE > 30.5). It goes three conditions deep, and splits only where that accounts for at least a twentieth of the change.
  • Every segment of the tree is a row, Overall first, then by contribution:
Column Is
CONTRIBUTOR The segment’s conditions, an array such as [“COUNTRY = us”,“DEVICE = mobile”]; ["Overall"] for all the rows. Dimensions are named in upper case, as Snowflake names them, unless their name has upper-case letters
METRIC_CONTROL, METRIC_TEST The segment’s metric totals in the control and test rows
CONTRIBUTION METRIC_TEST - METRIC_CONTROL
RELATIVE_CONTRIBUTION Its share of the overall change
GROWTH_RATE CONTRIBUTION / METRIC_CONTROL

An instance keeps nothing: GET_DRIVERS analyses what it is given, as its caller reads it.

Igloo’s classes: BigQuery ML’s model types

Section titled “Igloo’s classes: BigQuery ML’s model types”

IGLOO.ML.<class> classes are Igloo’s own, on its engine: BigQuery ML’s model types, with the statements, privileges and storage of Snowflake’s classes above (SNOWFLAKE.ML has no classes for these, and Igloo invents none there). A BigQuery CREATE MODEL becomes a CREATE IGLOO.ML.<class> whose CONFIG_OBJECT takes BigQuery’s options by their names, in lower case, and its ML. functions become the model’s methods:

-- BigQuery:
-- CREATE MODEL demo.value_model OPTIONS (model_type = 'boosted_tree_regressor',
-- input_label_cols = ['value'], learn_rate = 0.2) AS SELECT region, spend, visits, value FROM demo.campaigns;
-- SELECT * FROM ML.PREDICT(MODEL demo.value_model, TABLE demo.new_campaigns);
CREATE IGLOO.ML.REGRESSION demo.value_model(
INPUT_DATA => SYSTEM$QUERY_REFERENCE('SELECT region, spend, visits, value FROM demo.campaigns'),
TARGET_COLNAME => 'value',
CONFIG_OBJECT => {'algorithm': 'boosted_trees', 'learn_rate': 0.2});
SELECT * FROM TABLE(demo.value_model!PREDICT(INPUT_DATA => TABLE(demo.new_campaigns)));
SELECT * FROM TABLE(demo.value_model!EVALUATE());
BigQuery model_type Igloo class CONFIG_OBJECT
LINEAR_REG IGLOO.ML.REGRESSION 'algorithm': 'linear'
BOOSTED_TREE_REGRESSOR IGLOO.ML.REGRESSION ‘algorithm’: ‘boosted_trees’ (the default)
RANDOM_FOREST_REGRESSOR IGLOO.ML.REGRESSION ‘algorithm’: ‘random_forest’
LOGISTIC_REG IGLOO.ML.CLASSIFICATION 'algorithm': 'logistic'
BOOSTED_TREE_CLASSIFIER IGLOO.ML.CLASSIFICATION ‘algorithm’: ‘boosted_trees’ (the default)
RANDOM_FOREST_CLASSIFIER IGLOO.ML.CLASSIFICATION ‘algorithm’: ‘random_forest’
DNN_REGRESSOR, DNN_CLASSIFIER IGLOO.ML.DNN_REGRESSOR, IGLOO.ML.DNN_CLASSIFIER ‘hidden_units’, 'dropout' and the like
AUTOML_REGRESSOR, AUTOML_CLASSIFIER IGLOO.ML.AUTOML_REGRESSOR, IGLOO.ML.AUTOML_CLASSIFIER ‘budget_hours’, ‘optimization_objective’
KMEANS IGLOO.ML.KMEANS ‘num_clusters’, or none to pick one
PCA IGLOO.ML.PCA ‘num_principal_components’ or ‘pca_explained_variance_ratio’
MATRIX_FACTORIZATION IGLOO.ML.MATRIX_FACTORIZATION USER_COLNAME, ITEM_COLNAME, RATING_COLNAME arguments; ‘feedback_type’
AUTOENCODER IGLOO.ML.AUTOENCODER ‘hidden_units’, the narrowest the latent space
XGBOOST imports IGLOO.ML.XGBOOST trains XGBoost’s own models XGBoost’s parameters by their names
ARIMA_PLUS, ARIMA_PLUS_XREG SNOWFLAKE.ML.FORECAST a different method, with intervals
CONTRIBUTION_ANALYSIS SNOWFLAKE.ML.TOP_INSIGHTS
DNN_LINEAR_COMBINED_*, TENSORFLOW, ONNX, remote models, TRANSFORM not supported train from a query that computes the features
BigQuery function Igloo method Classes
ML.PREDICT PREDICT all
ML.EXPLAIN_PREDICT EXPLAIN_PREDICT REGRESSION, CLASSIFICATION, XGBOOST, and the AUTOML classes but for a network
ML.DETECT_ANOMALIES DETECT_ANOMALIES KMEANS, PCA, AUTOENCODER
ML.RECONSTRUCTION_LOSS RECONSTRUCTION_LOSS AUTOENCODER
ML.CENTROIDS CENTROIDS KMEANS
ML.PRINCIPAL_COMPONENTS, ML.PRINCIPAL_COMPONENT_INFO PRINCIPAL_COMPONENTS, PRINCIPAL_COMPONENT_INFO PCA
ML.RECOMMEND RECOMMEND MATRIX_FACTORIZATION
ML.EVALUATE EVALUATE all
ML.CONFUSION_MATRIX, ML.ROC_CURVE CONFUSION_MATRIX, ROC_CURVE the classifiers
ML.GLOBAL_EXPLAIN GLOBAL_EXPLAIN the regressions and classifiers
ML.FEATURE_IMPORTANCE FEATURE_IMPORTANCE tree models
ML.WEIGHTS, ML.ADVANCED_WEIGHTS WEIGHTS linear and logistic models
ML.TRAINING_INFO TRAINING_INFO boosted trees (XGBOOST too), networks (AUTOENCODER too), KMEANS, MATRIX_FACTORIZATION
ML.TRIAL_INFO TRIAL_INFO the AUTOML classes

Row methods (PREDICT, EXPLAIN_PREDICT, DETECT_ANOMALIES, RECOMMEND, RECONSTRUCTION_LOSS) give a value per row. In a query, m!PREDICT(INPUT_DATA => {*}) is a JSON object, as Snowflake’s PREDICT is; called as a table, as BigQuery’s functions are, TABLE(m!PREDICT(INPUT_DATA => TABLE(t))) returns the input’s rows and columns with the method’s columns after them. Both are scored as the rows are read, on workers too, so they scale with the input. INPUT_DATA takes what training’s does (TABLE(name), SYSTEM$REFERENCE, SYSTEM$QUERY_REFERENCE, TABLE(SELECT ...)), and a row method’s options go in its own CONFIG_OBJECT. The input must have the model’s features, by their names; other columns are kept and ignored. CALL refuses row methods: call them as tables.

Table methods (EVALUATE, WEIGHTS and the rest) return rows about the model, with CALL or TABLE(m!METHOD()). EVALUATE() measures the rows held out of training; EVALUATE(INPUT_DATA => TABLE(t)) measures t’s rows, which must hold the target.

  • Features are every column but the target, as for Snowflake’s classes. Linear and logistic models standardize numbers and give a categorical feature’s 100 most frequent categories (of at least five rows) indicators against the most frequent; trees bin numbers and keep categories as they are.
  • Evaluation split, BigQuery’s data_split_method: 'auto_split' (the default) holds back no rows of fewer than 500, a fifth of up to 50,000, and 10,000 rows of more; 'random' holds back data_split_eval_fraction (default 0.2); 'no_split', or Snowflake’s 'evaluate': FALSE, none. A classifier’s held-out rows keep its classes’ shares. Models train on the rest, as BigQuery’s do.
  • Large inputs. Igloo’s classes train on at most 10 million rows and 200 million values (rows times columns). Above that they train on a sample of a little fewer rows. Each row is kept or not by a hash of its values, its place among the rows equal to it, and seed: rows that repeat are sampled like any others, each copy on its own, and the same rows and seed give the same sample and the same model. A sample that comes out empty fails CREATE. The model’s metrics record input_rows and sampled_rows.
  • seed (default 0) seeds sampling and training: models are the same for the same rows and seed.
  • Unknown CONFIG_OBJECT keys are refused, so that a misspelled option does not go unnoticed.
CREATE IGLOO.ML.CLASSIFICATION demo.converts(
INPUT_DATA => TABLE(demo.lead_features),
TARGET_COLNAME => 'converted',
CONFIG_OBJECT => {'algorithm': 'random_forest', 'num_parallel_tree': 200});
SELECT person_id, predicted_converted, predicted_converted_probs
FROM TABLE(demo.converts!PREDICT(INPUT_DATA => TABLE(demo.new_leads)));
SELECT person_id, top_feature_attributions
FROM TABLE(demo.converts!EXPLAIN_PREDICT(INPUT_DATA => TABLE(demo.new_leads),
CONFIG_OBJECT => {'top_k_features': 3}));

REGRESSION predicts a number; CLASSIFICATION a class (2 to 255), as Snowflake’s does, booleans as True and False. 'algorithm' picks the model:

algorithm Options (BigQuery’s names)
‘boosted_trees’ max_iterations (rounds, default 500, stopped early on a tenth of the training rows unless ‘early_stop’: FALSE), learn_rate (0.1), max_tree_depth (12), num_leaves (31), subsample, colsample_bytree, colsample_bynode (1), l2_reg (1), min_tree_child_weight, min_data_in_leaf (20)
‘random_forest’ num_parallel_tree (trees, default 100), subsample (0.8), colsample_bynode (0.8), colsample_bytree (1), max_tree_depth (12), num_leaves (127), l2_reg, min_data_in_leaf (2)
'linear', 'logistic' l2_reg (a ridge penalty on standardized features, default 0); fit exactly by iteratively reweighted least squares, so optimize_strategy and learn_rate are accepted and ignored. Three classes or more are one logistic model per class against the rest.

l1_reg is refused. Methods:

Method Returns
PREDICT {"value": v}, or {“class”: c, “probability”: {class: p, …}}; as a table, predicted_<target> (and predicted_<target>_probs, JSON)
EXPLAIN_PREDICT the prediction with top_feature_attributions ([{“feature”, “attribution”}, …], the top_k_features largest, default 5), baseline_prediction_value, prediction_value and approximation_error (0): attributions are SHAP values for trees and coefficients times distances from the means for linear models, and with the baseline add up to the prediction (for classes, the predicted class’s raw score: log-odds for boosted trees and logistic models, a probability for forests); a table adds probability for classes
EVALUATE regression: mean_absolute_error, mean_squared_error, mean_squared_log_error (NULL with negative values), median_absolute_error, r2_score, explained_variance; classification: precision, recall, accuracy, f1_score (the second class’s at a threshold of 0.5 for two classes, macro averages for more), log_loss, roc_auc
CONFUSION_MATRIX expected_label, predicted_label, count, on the held-out rows
ROC_CURVE two classes: threshold (0 to 1 by 0.01), recall, false_positive_rate, true_positives, false_positives, true_negatives, false_negatives
GLOBAL_EXPLAIN feature, attribution: the mean absolute attribution, largest first
FEATURE_IMPORTANCE trees: feature, importance_weight (splits), importance_gain, importance_cover (rows per split)
WEIGHTS linear and logistic models: class (for three classes or more), processed_input (the feature, or INTERCEPT), category, weight, standard_error, p_value (BigQuery’s ML.ADVANCED_WEIGHTS)
TRAINING_INFO boosted trees: iteration, loss, eval_loss (on the early-stopping rows), learning_rate
CREATE IGLOO.ML.DNN_CLASSIFIER demo.converts_net(
INPUT_DATA => TABLE(demo.lead_features),
TARGET_COLNAME => 'converted',
CONFIG_OBJECT => {'hidden_units': [64, 32], 'dropout': 0.1});

A feed-forward network on the features, numbers standardized and each category one hot (a feature’s 100 most frequent categories of at least five rows), trained by Adam on mini-batches and stopped early when the loss on a tenth of the training rows has not improved for 5 epochs, keeping the best epoch’s weights. A regression’s target is standardized for training; a classifier ends in a sigmoid (two classes) or softmax. Options, BigQuery’s names:

Option Default
hidden_units [64, 32]
activation_fn 'relu'; or 'tanh', 'sigmoid', 'linear'
dropout 0
batch_size about a thirty-second of the training rows, from 32 to 1,024
learn_rate 0.001
max_iterations epochs: enough for some 3,000 steps, from 5 to 500
early_stop TRUE
l2_reg 0
optimizer 'adam', the only one

Methods are the regressions’ and classifiers’ above but EXPLAIN_PREDICT, FEATURE_IMPORTANCE and WEIGHTS. GLOBAL_EXPLAIN’s attribution is how much the model’s loss on up to 5,000 training rows grows when the feature’s values are shuffled among them. TRAINING_INFO shows each epoch’s training and validation loss, up to the one kept. A batch’s gradient is added up in fixed parts of 32 rows, so networks are as repeatable as the other models.

CREATE IGLOO.ML.AUTOML_CLASSIFIER demo.converts_auto(
INPUT_DATA => TABLE(demo.lead_features),
TARGET_COLNAME => 'converted',
CONFIG_OBJECT => {'budget_hours': 0.25, 'optimization_objective': 'maximize_au_roc'});
SELECT * FROM TABLE(demo.converts_auto!TRIAL_INFO()) ORDER BY objective DESC;

A search over the classes above: linear or logistic regressions, boosted trees, random forests and networks, with a dozen settings of their hyperparameters, the quick ones first. Each is cross-validated on the training rows (up to 100,000 of them) in cv_folds folds (default 3, of the classes’ shares for a classifier), and scored by optimization_objective: 'minimize_log_loss' (the default) or 'maximize_au_roc' for a classifier, 'minimize_rmse' (the default), 'minimize_mae' or 'minimize_rmsle' for a regression. The search stops starting trials when budget_hours (default 1, at most 72; fractions are fine) has passed, or after max_trials. The best trial’s algorithm and settings are then trained on every training row, and the model is that one, with its class’s methods (WEIGHTS for a linear winner, FEATURE_IMPORTANCE for trees, no EXPLAIN_PREDICT for a network) and TRIAL_INFO: trial_id, algorithm, hyperparameters (the options it set, as JSON), status (SUCCEEDED or FAILED), objective (its cross-validated value, as the objective names it) and is_optimal. Within its budget a search tries the same trials in the same order, so the same rows give the same model unless the budget cuts the search short.

CREATE IGLOO.ML.KMEANS demo.segments(
INPUT_DATA => SYSTEM$QUERY_REFERENCE('SELECT spend, visits, region FROM demo.people'),
CONFIG_OBJECT => {'num_clusters': 4});
SELECT person_id, centroid_id FROM TABLE(demo.segments!PREDICT(INPUT_DATA => TABLE(demo.people)));
SELECT * FROM TABLE(demo.segments!DETECT_ANOMALIES(INPUT_DATA => TABLE(demo.people),
CONFIG_OBJECT => {'contamination': 0.01}))
WHERE is_anomaly;

k-means clustering of every column, numbers standardized ('standardize_features', default TRUE) and categories one hot, trained by e-means: mini-batch k-means whose centroids are exponentially decayed means of the rows assigned to them, for max_iterations epochs (default 5). It starts from k-means++ centroids, or with 'kmeans_init_method': 'random' from rows drawn at random, as the paper does; with few clusters a random start can put two centroids in one group. early_stop and min_rel_progress are accepted and change nothing: e-means runs every epoch on its schedule. Without num_clusters (2 to 100), Igloo clusters up to 20,000 of the rows into 2 to 10 clusters and keeps the number whose Davies-Bouldin index is lowest; the model’s hyperparameters record each. distance_type is 'euclidean'; others are refused.

Method Returns
PREDICT centroid_id (from 1) and nearest_centroids_distance, every centroid’s distance, nearest first, as JSON
DETECT_ANOMALIES is_anomaly, normalized_distance (the distance to the nearest centroid divided by the mean distance of its training rows) and centroid_id; CONFIG_OBJECT => {‘contamination’: x} (more than 0, at most 0.5) is the share of training rows that would be anomalies, which sets the threshold
EVALUATE davies_bouldin_index and mean_squared_distance (in standardized units), on the training rows or on INPUT_DATA
CENTROIDS centroid_id, feature, numerical_value (in the feature’s own units), and for categories category and categorical_value, the share of the cluster’s rows in it
TRAINING_INFO each epoch’s mean squared distance, as loss, then the final centroids’
CREATE IGLOO.ML.PCA demo.channel_factors(
INPUT_DATA => SYSTEM$QUERY_REFERENCE('SELECT impressions, clicks, spend, visits FROM demo.daily_channels'),
CONFIG_OBJECT => {'pca_explained_variance_ratio': 0.9});
SELECT day, principal_component_1, principal_component_2
FROM TABLE(demo.channel_factors!PREDICT(INPUT_DATA => TABLE(demo.daily_channels)));

Principal components of every column, numbers standardized ('scale_features', default TRUE) and categories one hot (at most 1,000 columns so encoded): num_principal_components of them, or as many as explain pca_explained_variance_ratio of the variance; one of the two is required. The components are the covariance matrix’s exact eigenvectors, so pca_solver is accepted and changes nothing.

Method Returns
PREDICT principal_component_1, principal_component_2, …: the row’s coordinates
DETECT_ANOMALIES is_anomaly and mean_squared_error, the row’s distance from its projection, against the training rows’ errors by CONFIG_OBJECT => {‘contamination’: x}
EVALUATE total_explained_variance_ratio, of the training rows or of INPUT_DATA
PRINCIPAL_COMPONENTS principal_component_id, feature, numerical_value (a number’s loading), and for categories category and categorical_value
PRINCIPAL_COMPONENT_INFO principal_component_id, eigenvalue, explained_variance_ratio, cumulative_explained_variance_ratio
CREATE IGLOO.ML.MATRIX_FACTORIZATION demo.campaign_tastes(
INPUT_DATA => TABLE(demo.campaign_clicks),
USER_COLNAME => 'person_id', ITEM_COLNAME => 'campaign', RATING_COLNAME => 'clicks',
CONFIG_OBJECT => {'feedback_type': 'implicit', 'num_factors': 32});
SELECT person_id, campaign, predicted_clicks_confidence
FROM TABLE(demo.campaign_tastes!RECOMMEND(INPUT_DATA => TABLE(demo.audience),
CONFIG_OBJECT => {'top_k': 5, 'exclude_seen': TRUE}));

Users’ ratings of items factorized by alternating least squares, as BigQuery’s: users and items are read as text, and a user’s ratings of an item add up (implicit feedback) or are averaged (explicit).

  • 'feedback_type': 'explicit' (the default) predicts ratings as the mean rating plus a user’s and an item’s bias plus their factors’ product, with the L2 penalty l2_reg (default 1) scaled by each user’s and item’s ratings.
  • 'implicit' treats any positive rating as a preference of 1 and every pair not rated as one of 0, trusted by 1 + wals_alpha × rating (wals_alpha default 40), as Hu, Koren and Volinsky’s method.
  • num_factors (default 16, at most 256), max_iterations (15), seed. Users and items seen only in held-out rows get no factors.
Method Returns
PREDICT a user’s and an item’s predicted rating (predicted_<rating>), or confidence for implicit feedback (predicted_<rating>confidence), from INPUTDATA’s user and item columns; an explicit model predicts unknown users and items from the biases it has, an implicit one gives NULL
RECOMMEND for each row of INPUT_DATA (its user column), the top_k items (default 10), best first, as rows of the input’s columns, the item column and the prediction; ‘exclude_seen’: TRUE leaves out the items the user rated in the training data (Igloo keeps them for inputs of up to 50 million interactions). A user the model never saw gets the items of highest bias (explicit) or none (implicit). Without INPUT_DATA, it recommends to every user the model knows
EVALUATE on the held-out interactions or INPUT_DATA’s: a regression’s metrics for explicit ratings; for implicit feedback, over up to 1,000 users, mean_average_precision and normalized_discounted_cumulative_gain of the held-out items among those each user did not rate in training, average_rank (their mean percentile rank, 0 at the top) and mean_squared_error
TRAINING_INFO each iteration’s training loss: explicit ratings’ root mean squared error, implicit feedback’s weighted squared error per user
CREATE IGLOO.ML.AUTOENCODER demo.session_shapes(
INPUT_DATA => SYSTEM$QUERY_REFERENCE('SELECT pages, seconds, clicks, spend, channel FROM demo.sessions'),
CONFIG_OBJECT => {'hidden_units': [32, 4, 32]});
SELECT * FROM TABLE(demo.session_shapes!DETECT_ANOMALIES(INPUT_DATA => TABLE(demo.sessions_today),
CONFIG_OBJECT => {'contamination': 0.005}))
WHERE is_anomaly;

A network that rebuilds every column, standardized and one hot, through its narrowest hidden layer, the latent space (the middle one if several are as narrow), which is linear; the other layers take activation_fn. hidden_units defaults to half the encoded columns (4 to 64), a quarter of them (2 to 16), and half again; the other options and the training are the DNN classes’. Rows held out by data_split_method measure it.

Method Returns
PREDICT latent_col_1, latent_col_2, …: the row in the latent space
RECONSTRUCTION_LOSS the row’s mean_absolute_error, mean_squared_error and mean_squared_log_error (negative values’ logs taken as 0’s), over its encoded columns
DETECT_ANOMALIES is_anomaly and mean_squared_error, against the training rows’ errors by CONFIG_OBJECT => {‘contamination’: x}
EVALUATE the three errors’ means, on the held-out rows (or the training rows without them) or on INPUT_DATA
TRAINING_INFO each epoch’s training and validation loss
CREATE [ OR REPLACE ] IGLOO.ML.XGBOOST [ IF NOT EXISTS ] name(
INPUT_DATA => <table, view or query>,
TARGET_COLNAME => '<column>'
| LABEL_LOWER_BOUND_COLNAME => '<column>', LABEL_UPPER_BOUND_COLNAME => '<column>',
[ WEIGHT_COLNAME => '<column>', ]
[ CONFIG_OBJECT => { <XGBoost's parameters>, 'num_boost_round': n, 'early_stopping_rounds': n,
'data_split_method': ..., ... } ]
)

A model trained by XGBoost itself. Igloo links XGBoost’s library, release 3.4.2, and gives it CONFIG_OBJECT’s parameters as they are written, so the model is the one XGBoost’s Python package trains with xgboost.train on the same rows in the same order, with the same parameters. Built for the same platform, the two save the same model byte for byte, with the same predictions, metrics and SHAP values. Across platforms, as between XGBoost’s own builds, compilers round a float otherwise now and then (predictions agree within about 1e-7), and subsample and the colsample_ parameters draw other rows and columns: XGBoost draws them with the C++ standard library, which macOS and Linux implement differently. Give INPUT_DATA’s query an ORDER BY for a model that does not depend on how the rows are stored.

A binary classifier, with early stopping on rows a column marks:

CREATE IGLOO.ML.XGBOOST demo.converts_xgb(
INPUT_DATA => SYSTEM$QUERY_REFERENCE('SELECT spend, visits, returning, converted, holdout
FROM demo.lead_features ORDER BY person_id'),
TARGET_COLNAME => 'converted',
CONFIG_OBJECT => {'objective': 'binary:logistic', 'eval_metric': ['logloss', 'auc'],
'eta': 0.1, 'max_depth': 4, 'subsample': 0.8, 'seed': 7,
'num_boost_round': 500, 'early_stopping_rounds': 20,
'data_split_method': 'custom', 'data_split_col': 'holdout'});
SELECT person_id, demo.converts_xgb!PREDICT(INPUT_DATA => {*}):probability:True::FLOAT AS p_convert
FROM demo.new_leads;
SELECT * FROM TABLE(demo.converts_xgb!EVALUATE());

Survival times, of which some are right-censored, by accelerated failure time:

CREATE IGLOO.ML.XGBOOST demo.churn_time(
INPUT_DATA => SYSTEM$QUERY_REFERENCE($$
SELECT tenure_months, seats, support_tickets,
days_active AS days_lower,
CASE WHEN churned THEN days_active ELSE 'Infinity'::DOUBLE END AS days_upper
FROM demo.accounts ORDER BY account_id$$),
LABEL_LOWER_BOUND_COLNAME => 'days_lower', LABEL_UPPER_BOUND_COLNAME => 'days_upper',
CONFIG_OBJECT => {'objective': 'survival:aft', 'eval_metric': 'aft-nloglik',
'aft_loss_distribution': 'normal', 'aft_loss_distribution_scale': 1.0,
'tree_method': 'hist', 'learning_rate': 0.05, 'max_depth': 3, 'num_boost_round': 200});
SELECT account_id, predicted_label AS expected_days
FROM TABLE(demo.churn_time!PREDICT(INPUT_DATA => TABLE(demo.accounts)));
  • Parameters. CONFIG_OBJECT‘s keys are XGBoost’s parameters, by XGBoost’s names (objective, eval_metric, eta or learning_rate, max_depth, lambda, alpha, min_child_weight, subsample, colsample_bytree, scale_pos_weight, base_score, seed, tree_method, aft_loss_distribution, and any other XGBoost takes), passed to XGBoost as its Python package passes them: an eval_metric array as several metrics, monotone_constraints’ array as (1,0,-1). Defaults are XGBoost’s (reg:squarederror, an eta of 0.3, a max_depth of 6). XGBoost refuses a value it does not take, and Igloo refuses a parameter XGBoost does not use, such as n_estimators, which xgboost.train ignores, both with XGBoost’s message.
  • Training options, which are not XGBoost’s: num_boost_round (default 10, as xgboost.train‘s); early_stopping_rounds, which stops training once the validation rows’ last metric (the last eval_metric, or the objective’s) has not improved for that many rounds, as the Python package’s early stopping does, maximizing AUC, NDCG, MAP and precision and minimizing the rest; and the validation rows, by data_split_method: 'no_split' (the default: every row trains, as in xgboost.train), 'random' and 'auto_split' as for the other classes (above), or 'custom' with data_split_col, a boolean column that is TRUE for the validation rows and is not a feature. Validation rows do not train. With early stopping, the model keeps the rounds after the best, as XGBoost does, records the best as XGBoost’s best_iteration and best_score, and its methods use the trees up to it.
  • Labels. TARGET_COLNAME is a number, or a boolean (1 and 0), which XGBoost takes as it is: 0 and 1 for the binary: objectives, 0 to num_class - 1 for the multi: ones. Rows whose target is NULL are left out; text is refused (map classes to numbers in the query). For survival:aft, LABEL_LOWER_BOUND_COLNAME and LABEL_UPPER_BOUND_COLNAME give each row’s interval instead: an uncensored row’s bounds are equal, a right-censored row’s upper bound is 'Infinity'::DOUBLE, a left-censored row’s lower bound 0, and a NULL bound is refused. WEIGHT_COLNAME weighs each row.
  • Features are every other column, as XGBoost’s float32s: numbers, booleans as 1 and 0, timestamps and dates as seconds since 1970, NULL as missing. Text is refused rather than encoded: XGBoost’s own categorical support is what the same model in XGBoost would use, and Igloo’s encodings would make another model. Encode categories as numbers in INPUT_DATA’s query (region = 'south' AS south).
  • Training runs on the replica that runs CREATE, on every core (XGBoost’s nthread to use fewer), and scoring a row at a time as the query reads rows, on workers too, as for the other classes. Inputs are sampled as theirs are (see Training).
Method Returns
PREDICT {"value": v}, XGBoost’s prediction (a probability, a value, a class’s number, or an array of them for an objective with several), with class and probability ({“0”: p, “1”: p, …}, booleans’ as False and True) for the classification objectives (binary:hinge has no probability); CONFIG_OBJECT => {‘output_margin’: TRUE} adds margin, the raw score before the objective’s transformation. As a table, predicted_<target> (a classifier’s class, of the target’s type) and predicted_<target>probs (JSON), and predicted<target>margin with outputmargin; an interval label’s model names them after label
EXPLAIN_PREDICT the prediction with top_feature_attributions (the top_k_features largest, default 5), baseline_prediction_value and prediction_value: XGBoost’s SHAP values (pred_contribs), in margin space, which with the bias, the baseline, add up to the margin, prediction_value; approximation_error is how far they miss it, by float32 rounding. A binary objective’s attributions are those of class 1’s log-odds, whichever class a row is predicted; a multiclass model’s are its predicted class’s. A table adds probability for classes
EVALUATE metric and value: XGBoost’s metrics (eval_metric’s, or the objective’s) on the validation rows at the best iteration, or on INPUT_DATA’s rows, which hold the label’s columns
TRAINING_INFO iteration (XGBoost’s, from 0), metric, training_value, validation_value, is_best_iteration: each metric of each round, as XGBoost measured it
FEATURE_IMPORTANCE feature, importance_weight (splits), importance_gain, importance_cover: XGBoost’s weight, gain and cover (averages over a feature’s splits) of the trees the model predicts with, every feature, largest gain first

The model’s blob holds the booster as XGBoost saves it (Universal Binary JSON, which xgboost.Booster(model_file=...) loads), with the features in their order, the label’s columns, the best iteration and the parameters.

  • The statements are Snowflake’s, not CREATE MODEL ... OPTIONS (...) AS SELECT and ML.<function>(MODEL m, ...): the tables above map one to the other. TRANSFORM, input_label_cols (use TARGET_COLNAME), data_split_col and the 'custom' and 'seq' splits, l1_reg, auto_class_weights, warm_start, hyperparameter tuning in CREATE (num_trials; the AUTOML classes search instead), other k-means initializations and distances, and model export are not supported.
  • Models come from Igloo’s engine, so their metrics and predictions differ from BigQuery’s for the same data, and their defaults are Igloo’s: for example, boosted trees stop early on a tenth of the training rows rather than running max_iterations rounds, and RECOMMEND returns top_k items rather than every item.
  • Tables BigQuery returns with a column per class or category, or arrays of structures, are rows here: CONFUSION_MATRIX has a row per pair of classes, CENTROIDS and PRINCIPAL_COMPONENTS a row per category, and JSON stands in for arrays (nearest_centroids_distance, top_feature_attributions, a class’s probabilities). ROC_CURVE’s thresholds are 0 to 1 by 0.01.
  • EXPLAIN_PREDICT attributes a class’s raw score (log-odds for boosted trees and logistic models), and networks have none; their GLOBAL_EXPLAIN is by permutation.

Databricks’ predictive functions train a model on the rows whose target is known and score the rows whose target is NULL, in one query, and keep no model: the simplest way to score propensity or find lookalikes, with the known converters as 1, a sample of non-converters as 0, and everyone else NULL. Igloo has them in both dialects:

SELECT person_id, converted_prediction, converted_confidence
FROM ai_predict_class(
input => TABLE(demo.lead_features), -- or TABLE(SELECT ...)
target_col => 'converted',
feature_cols => ARRAY_CONSTRUCT('region', 'spend', 'visits'), -- ['region', 'spend', 'visits'] in DuckDB's dialect
seed => 7);
SELECT * FROM ai_predict_value(input => TABLE(demo.accounts), target_col => 'next_month_spend',
feature_cols => ['segment', 'spend', 'tenure']);
  • They return the input’s rows whose target is NULL, with every column, and <target>_prediction: for ai_predict_class the class, of the target’s type, and <target>_confidence, its probability; for ai_predict_value a DOUBLE.
  • The model is trained as CLASSIFICATION’s (2 to 255 classes) or as a regression, on the rows whose target is set, without held-out metrics; seed (default 0) seeds it. It is kept in memory for the session while the statement may run again, and never stored. An erasure request has every replica drop it: a statement prepared before then fails with a message to prepare it again, which trains it again on the rows there are then.
  • They read their input as the user, policies applied, as the rest of the query does, and score on the replica that runs the query.

BigQuery’s and Databricks’ forecasting functions

Section titled “BigQuery’s and Databricks’ forecasting functions”

BigQuery’s AI.FORECAST and AI.DETECT_ANOMALIES and Databricks’ ai_forecast and ai_detect_anomalies forecast series with a foundation model of the model pack in a query, with no model object. Igloo reads them in both SQL dialects, with their arguments and output columns. They are table functions: use them in FROM.

SELECT * FROM AI.FORECAST(
TABLE demo.daily_spend, -- or (SELECT ...)
data_col => 'spend', timestamp_col => 'day', id_cols => ['campaign'],
model => 'TimesFM 2.5', horizon => 14, confidence_level => 0.9);
SELECT * FROM ai_forecast(
observed => TABLE(demo.daily_spend), horizon => '2026-12-01',
time_col => 'day', value_col => 'spend', group_col => 'campaign');
Function Arguments Columns
AI.FORECAST the input, TABLE name or (query); data_col, timestamp_col; model (default ‘TimesFM 2.5’); id_cols; horizon (default 10) or forecast_end_timestamp, the last step’s; confidence_level (0.95); output_historical_time_series; context_window the id_cols, forecast_timestamp, forecast_value, confidence_level, prediction_interval_lower_bound, prediction_interval_upper_bound, ai_forecast_status; with the history, time_series_type ('history' or 'forecast'), time_series_timestamp and time_series_data for the timestamp and value
AI.DETECT_ANOMALIES the history; the target, a second TABLE or (query), or target_last_n_points or target_start_timestamp of the history; data_col, timestamp_col; model; id_cols; anomaly_prob_threshold (0.95); context_window the id_cols, time_series_timestamp, time_series_data, is_anomaly, lower_bound, upper_bound, anomaly_probability, ai_detect_anomalies_status
ai_forecast observed, TABLE(name) or TABLE(SELECT …); horizon, the first time not forecast; time_col; value_col, a column or an array of them; group_col, a column or an array; prediction_interval_width (0.95); frequency (pandas’ 'D', 'H', '15min', 'W', 'MS', or '1 day'; inferred by default); positive_only; version ('1' or '2'); model (an Igloo extension; default 'chronos-2') time_col, the groups, and for each value column <v>forecast, <v>upper and <v>_lower
ai_detect_anomalies observed; time_col; value_col; group_col; anomaly_threshold (0.95); only_last_n, a number of points or a timestamp; smoothing (accepted, no effect); model (default 'chronos-2') time_col, the groups, the value column, expected, lower_bound, upper_bound, anomaly_score, is_anomaly
  • Models. model names a model of the pack as method does (above), or a hosted one an AI integration maps (below), which a name the pack has never means unless it says 'integration/name': BigQuery’s 'TimesFM 2.5' is the pack’s timesfm-2.5. Databricks names no model; Igloo forecasts with chronos-2 unless model says otherwise. A model the pack lacks is refused, saying how to install it. 'TimesFM 3.0', which BigQuery offers in preview, is only hosted: its weights are licensed for non-commercial use only, so the pack does not hold them; a bigquery integration that maps it runs it in BigQuery.
  • Series. Each combination of id_cols (group_col) values is a series, forecast on its own. Its frequency is the most common gap between its timestamps; several rows at one step are averaged, and steps without one are gaps. A series that cannot be forecast, such as one with fewer than 3 points for BigQuery’s functions, has a row saying why in ai_forecast_status (ai_detect_anomalies_status), and the others are forecast; ai_forecast leaves it out.
  • Detection. A point is anomalous when its anomaly_probability, |2F(y) - 1| where F is the model’s forecast distribution at that step (0 at the median, near 1 far in either tail), is above the threshold; lower_bound and upper_bound are the interval at the threshold. AI.DETECT_ANOMALIES forecasts the target points (the last 1,024 of each series) from the history before them. ai_detect_anomalies scores every point of a series from the points before it, 64 steps at a time, and leaves the first 8, which have too little before them, unscored.
  • Context. A model reads at most context_window of a series’ last points: for TimesFM 2.5, BigQuery’s 64, 128, …, 8,192 or 15,360, and by default the smallest of those that holds the series; for the others, up to what they read.
  • Covariates (covariate_col, BigQuery’s target_cols and future covariates), holiday_region, and version 1’s prophet-like parameters are refused: the models forecast from the values alone.
  • Rows and policies. The input is read as the user reads it, through their grants, row access and masking policies, as the rest of the query is. A view cannot call them; create a table from the query, or a task that does so on a schedule.
  • Where they run. On workers, when the statement runs there: workers read the input and gather each series’ points, and a stage of workers that holds whole series, partitioned by id_cols, forecasts them. Without id_cols, and in statements that do not run on workers, the replica forecasts. Workers forecast with their own copy of the model pack (see where the pack lives). A hosted model (below) is called by the replica that runs the statement.

model may also name a model an AI integration maps: a provider’s model, called with your own credentials, for the models the pack cannot hold or that you already run.

-- Admins: TimeGPT, with your Nixtla key.
CREATE AI INTEGRATION timeseries PROVIDER = nixtla API_KEY = '...'
MODELS = ('timegpt' = 'timegpt-1', 'timegpt-long' = 'timegpt-1-long-horizon');
GRANT USAGE ON INTEGRATION timeseries TO ROLE analysts;
-- TimesFM 3.0, run by BigQuery in your Google Cloud project.
CREATE AI INTEGRATION bigquery_ml PROVIDER = bigquery SERVICE_ACCOUNT = '{...}' PROJECT = 'demo-project' REGION = 'US'
MODELS = ('TimesFM 3.0' = 'TimesFM 3.0');
SELECT * FROM AI.FORECAST(TABLE demo.daily_spend, data_col => 'spend', timestamp_col => 'day',
id_cols => ['campaign'], model => 'timegpt', horizon => 14);
Integration MODELS maps a name to What it calls
nixtla a TimeGPT model: timegpt-1, timegpt-1-long-horizon, or another your Nixtla account has Nixtla’s /v2/forecast, at https://api.nixtla.io or BASE_URL (a Microsoft Foundry deployment of TimeGPT)
sagemaker a SageMaker endpoint’s name, of Chronos-2 or Chronos-Bolt deployed from JumpStart the endpoint’s invocations
bedrock a Bedrock Marketplace endpoint’s ARN, of Chronos-Bolt Bedrock’s InvokeModel
vertex (with a SERVICE_ACCOUNT) a Vertex AI endpoint of TimesFM from Model Garden: its ID, endpoints/ID or projects/P/locations/L/endpoints/ID (shared public endpoints) the endpoint’s predict
bigquery a model AI.FORECAST takes: ‘TimesFM 3.0’ or ‘TimesFM 2.5’ BigQuery’s AI.FORECAST, as a query in PROJECT
  • Names. A name the pack has (its catalog’s, installed or not, or one installed from a manifest) always means the pack’s model, run by Igloo, even where an integration maps the same name: no series leaves Igloo unless the call names a hosted model. 'integration/name', such as 'timeseries/timegpt' or 'sagemaker_chronos/chronos-2', names the model that integration maps; a name the pack does not have, such as 'timegpt' or 'TimesFM 3.0', means the model an integration the user may use maps, if one does (the session’s ai_integration chooses among several). Users need USAGE on the integration, as for AI functions.
  • Which one. EXPLAIN of a statement that forecasts adds a forecast model row for each name: the pack’s model, whose series stay in Igloo, or the integration, its provider, the provider’s model and the address the series are sent to. It sends nothing. A call of a pack model that is not installed, which an integration maps too, fails with a hint naming the hosted one.
  • What is sent. Each series’ last context_window points (2,048 by default), from its first value, with gaps filled in between their neighbours, its start and its step. With a bigquery integration the series’ timestamps and values leave for BigQuery, which runs AI.FORECAST over them in your project and bills that query; Google’s terms for BigQuery then apply to them. TimesFM 3.0’s weights are licensed for non-commercial use only; Google permits its commercial use through BigQuery, which is why Igloo reaches it there.
  • Intervals. Igloo asks for the deciles and the interval’s bounds where the provider takes quantiles (Nixtla, as levels; Chronos, within 0.1 and 0.9; TimesFM’s endpoint answers deciles), and reads intervals and anomaly probabilities from them as for the pack’s models. BigQuery answers one interval, at confidence_level (the detection threshold for detection): beyond it, quantiles are extended as a normal distribution would be.
  • Calls are AI functions’ calls: made only by the replica that runs the statement (workers may still read and gather the series), a batch of series a request, kept to the statement’s caps, counted in the query history and igloo.usage (Nixtla reports tokens; set PRICES for its cost), and kept in the cache: the same series forecast the same way again is answered from it. A series the provider refuses has a status row saying why.

A task’s statement may call models’ methods: the model is the one the name means when the task runs, checked against the task owner’s privileges then. A task runs in its owner’s default schema, so name models by their schema there.

  • A model’s row is in the metadata database (IGLOO_METADATA_DATABASE_URL), shared by every replica: its name, class, owner, comment, the CREATE statement, its configuration and metrics, and the SHA-256 of its blob. Without a metadata database, models are kept in memory and lost on restart.
  • Its blob, the trained model, is a file in the warehouse’s object storage under .igloo/models/, among Igloo’s own files, named by its SHA-256. Workers read blobs there with the access to the warehouse they already have, and every process keeps the models it has used in memory. Users other than admins cannot read the warehouse’s files from SQL. Without a warehouse, blobs are in memory.
  • Dropping or replacing a model deletes its blob once no model uses it. Models trained the same way share a blob: a CREATE that writes one holds it, on every replica, until its model is stored, so dropping another model with that blob meanwhile does not delete it. A statement prepared before a model was replaced fails with a message to run it again.
  • Personal data. A model keeps no training rows, but it keeps what it learned from them: the categories it splits on or encodes, and a time series model’s series values and its series’ last steps (a foundation model’s context window of each series among them). Categories that fewer than five training rows have are never kept: they share one bin (or none, in the models that encode them). A MATRIX_FACTORIZATION model is the exception: it keeps every user’s and item’s identifier, a vector of factors for each, and, for exclude_seen, which items each user rated. A model row keeps its CREATE statement.
  • Erasure. A model records the catalog’s tables its training read: those its input names, those the views it reads read, and those the models whose predictions it reads had read; what Igloo cannot name, such as a file, counts as every table. An erasure request on any of them trains the model again, after the person’s rows are gone and before the request completes: from its CREATE statement, as its owner, with the search path and dialect it was created with, as CREATE OR REPLACE would, grants kept. Then the blob it had is deleted, and every replica drops the models and methods’ results it holds in memory, so a statement prepared before fails with a message to prepare it again. A CREATE that read its rows before the request moved on stores nothing, and fails with SQLSTATE 40001, asking to be run again. A model the request cannot train again, because its owner is gone or may no longer create models in its schema or read its input, keeps the request blocked, with an alert, until it can be trained again, is dropped, or an admin closes the request, which records it as left. A model created before Igloo recorded the tables models read counts as trained from every table, until a request trains it again. Training a model again takes as long as creating it did, and a model trained from a time-travel query (AT (...)) of a snapshot the request expired cannot be: drop or create it again.

Models are trained by Igloo’s engine, in Go: gradient-boosted trees (binary, multiclass, regression and quantile objectives), with LightGBM’s methods for speed and accuracy, and SHAP values to explain them; random forests, linear and logistic regressions, networks, k-means, PCA and alternating least squares for Igloo’s classes. It is Igloo’s own Apache-2.0 code and needs nothing besides Igloo. IGLOO.ML.XGBOOST is the one class trained by another engine, XGBoost’s own library (Apache-2.0), which the binary links (above).

  • Training happens on the replica that runs CREATE, from the rows of its input in memory: up to 200 million values (rows times columns), which take a few gigabytes besides DuckDB’s memory while it trains. Snowflake’s classes refuse larger inputs (train on a sample); Igloo’s sample them (see Training). A statement’s timeout and cancelling it stop training. Boosting stops when a held-out tenth of the training rows stops improving, after at most 500 rounds. On one machine, 100 rounds over a million rows of 50 features take about 7 seconds on 18 cores and 13 on 2; training a CLASSIFICATION model on such a table, holdout metrics included, takes about 15 seconds on 18 cores (BenchmarkClassifier1M in internal/models, run with IGLOO_ML_BENCH=1).
  • Scoring with PREDICT runs as the query runs: a statement that scores a large table runs in parts on workers like any other, each scoring its share; so do Igloo’s classes’ row methods, in a query or as tables. Methods that return tables (FORECAST, Snowflake’s DETECT_ANOMALIES, the SHOW_ methods, and Igloo’s classes’ table methods) are computed on the replica, from the data they are given, before the statement that reads them runs.
  • Igloo’s classes add random forests (each tree on its own sample of rows and, at each split, of features, their leaves averaged), and linear and logistic regressions with standard errors.
  • Models are repeatable. The same rows, in any order, train the same model, with the same blob and SHA-256: the engine puts rows in an order of their own before training, and adds in a fixed order whatever the threads. IGLOO.ML.XGBOOST trains on the rows in the order its input gives them, as XGBoost does: the same rows in the same order train the same model.

On one machine (18 cores), creating each of Igloo’s classes on a million rows of 50 features (40 numbers, and 10 categories of 20 to 110 values, some 680 columns one hot), holdout metrics and explanations included, took (BenchmarkIgloo1M in internal/models, run with IGLOO_ML_BENCH=1):

Class Time
REGRESSION: boosted trees, random forest, linear 16, 22 and 8 s
CLASSIFICATION: boosted trees, random forest, logistic 11, 24 and 17 s
DNN_CLASSIFIER, DNN_REGRESSOR ([64, 32]) 19 and 15 s
AUTOML_CLASSIFIER: twelve trials, cross-validated on 100,000 rows, and the best trained on all 1 min 46 s
KMEANS: 8 clusters, or picking among 2 to 10 10 and 13 s
PCA: 228 components, for 90% of the variance 9 s
AUTOENCODER, latent space of 16 58 s
MATRIX_FACTORIZATION: ten million interactions of 100,000 users with 10,000 items, explicit and implicit 12 and 15 s
  • Models are objects of Igloo’s metadata database, not of the Iceberg catalog: other engines reading Igloo’s tables do not see them, and dropping a schema leaves its models.
  • A view cannot call a model’s methods (m!PREDICT or TABLE(m!...)), nor can a macro or a materialized view: a model is resolved, and its use checked, as each statement is prepared, which a view’s stored SQL is not. Create a table from the query instead, or a task that does so on a schedule. A task’s statement is resolved each time it runs, with the model as it is then.
  • Forecasts, intervals, feature importance and metrics come from Igloo’s engine, so their values differ from Snowflake’s for the same data. FORECAST‘s 'best' method is its 'fast' one; method may also name a foundation model of the model pack, which Snowflake’s does not. A time series model’s series train together on one replica, not split among workers. SHOW_FEATURE_IMPORTANCE and the model’s features keep their columns’ names as Igloo has them: in lower case for a table’s columns, in upper case for a Snowflake query’s aliases (AS domain is DOMAIN).
  • ALTER of models, Snowflake’s other ML classes (CUSTOM_CLASSIFIER and the like), the Model Registry (MODEL(...)!method) and GRANT CREATE SNOWFLAKE.ML.<class> are refused.