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_convertFROM demo.new_leads;
CALL demo.conversion!SHOW_GLOBAL_EVALUATION_METRICS();| Class | What it does | Methods |
|---|---|---|
SNOWFLAKE. |
Forecasts one or many time series, with prediction intervals | FORECAST, SHOW_, EXPLAIN_, SHOW_ |
SNOWFLAKE. |
Flags new points of time series that fall outside their forecast’s interval | DETECT_, SHOW_, EXPLAIN_, SHOW_ |
SNOWFLAKE. |
Predicts a class (2 to 255) from a row’s columns | PREDICT, SHOW_, SHOW_, SHOW_, SHOW_, SHOW_, SHOW_ |
SNOWFLAKE. |
Finds the segments that drove a metric’s change between two groups | GET_ |
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.
Statements
Section titled “Statements”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 ] nameSHOW 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 ] granteeGRANT SNOWFLAKE.ML.<class> ROLE name!MLADMIN | MLCONSUMER TO [ ROLE | USER ] granteeREVOKE ... FROM [ ROLE | USER ] grantee- Names. A model’s name is
name,schema.nameordatabase.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_DATAtakes a table or view,TABLE(name)orSYSTEM$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 REPLACEtrains the model again, under the same name; its grants stay. Models never change otherwise:ALTERis refused, andCOMMENTis set when a model is created.TAGis accepted and ignored, with a notice. A model’s row records theCREATEstatement 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 withTABLE(name!METHOD(...)), which can be filtered, joined and saved withCREATE TABLE ... AS. In Snowflake’s dialect their columns are named in upper case.name!PREDICT(...)is an expression. SHOWlists the models of a class the user may use, with Snowflake’s columns:created_on,name,database_name,schema_name,current_version,commentandowner.
Privileges
Section titled “Privileges”| 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_, GET_, and Igloo’s classes’ EXPLAIN_, RECOMMEND and RECONSTRUCTION_ |
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.
FORECAST
Section titled “FORECAST”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
fastone, whethermethodsays'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_COLNAMEnames 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.FORECASTforecasts every series, orSERIES_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, unlessaggregation_target,aggregation_numeric,aggregation_categoricaloraggregation_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_DATAholds a row for each future timestamp (and series), andFORECASTreturns 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_boundandupper_boundclamp forecasts and intervals. - Evaluation follows scikit-learn’s
TimeSeriesSplit, as Snowflake’s:evaluation_config‘sn_splits(default 1),test_size(default each series’ length divided byn_splits+ 1),gapandmax_train_size.'evaluate': FALSEkeeps 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_LOGSsays which.
| Method | Columns |
|---|---|
FORECAST(… |
SERIES (NULL for one series), TS, FORECAST, LOWER_, UPPER_ |
SHOW_ |
SERIES, ERROR_ (MAE, MAPE, MDA, MSE, SMAPE, WINKLER_, COVERAGE_), METRIC_, STANDARD_ (over the splits; NULL for one), LOGS |
SHOW_ |
The same, of forecasts of new data, after the training data |
EXPLAIN_ |
SERIES, RANK, FEATURE_, IMPORTANCE_ (shares of the mean absolute SHAP value, adding up to 1 per series), FEATURE_: derived_ for aggregated_ (the target’s lags and rolling means together), derived_ for calendar features, user_ for exogenous columns |
SHOW_ |
SERIES, LOGS |
Foundation models
Section titled “Foundation models”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'istimesfm-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_windowsteps (2,048 by default, at most what the model reads), andFORECASTforecasts 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_configsplits them, with the same metrics.EXPLAIN_FEATURE_IMPORTANCEreturns 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_DETECTIONtakes amethodtoo:DETECT_ANOMALIESforecasts the new points from the kept steps and flags those outside the interval.PERCENTILEis where the point falls in the model’s forecast distribution, andDISTANCEits 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.
ANOMALY_DETECTION
Section titled “ANOMALY_DETECTION”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_ANOMALIESforecasts 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_OBJECTtakes whatFORECAST’s does; its evaluation has 5 splits by default. LABEL_COLNAMEnames 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_ |
SERIES, TS, Y, FORECAST, LOWER_, UPPER_, IS_, PERCENTILE (where Y falls in the forecast’s distribution), DISTANCE (its z-score) |
SHOW_, EXPLAIN_, SHOW_ |
As FORECAST’s |
CLASSIFICATION
Section titled “CLASSIFICATION”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
NULLare left out, andSHOW_TRAINING_LOGSsays 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, ortest_fractionof each class. -
PREDICTtakesINPUT_DATA, an object of the row’s features:{*}(every column of the query’sFROM),{* EXCLUDE (id, label)},{t.*},OBJECT_CONSTRUCT(*), or keys and values such as{'region': region, 'spend': spend}orOBJECT_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
TrueandFalse, numbers’ as they read (0,1,2.5), strings as they are. Read the class with:class::STRINGand a probability with:probability:True::FLOAT.
| Method | Columns |
|---|---|
SHOW_ |
DATASET_ (EVAL), CLASS, ERROR_ (precision, recall, f1, support), METRIC_, LOGS |
SHOW_ |
DATASET_, AVERAGE_ (macro, weighted, or NULL for log_), ERROR_ (precision, recall, f1, auc, log_), METRIC_, LOGS |
SHOW_ |
DATASET_, ACTUAL_, PREDICTED_, COUNT, LOGS |
SHOW_ |
DATASET_, CLASS, THRESHOLD (0 to 1 by 0.01), PRECISION, RECALL, F1, TPR, FPR, TP, FP, TN, FN, ACCURACY, SUPPORT, LOGS |
SHOW_ |
RANK, FEATURE, SCORE (each feature’s share of the mean absolute SHAP value, adding up to 1), FEATURE_ (user_) |
SHOW_ |
LOGS |
The evaluation methods fail for a model trained with 'evaluate': FALSE.
TOP_INSIGHTS
Section titled “TOP_INSIGHTS”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 = usandnot COUNTRY = us) or a threshold (AGE <= 30.5andAGE > 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,
Overallfirst, then by contribution:
| Column | Is |
|---|---|
CONTRIBUTOR |
The segment’s conditions, an array such as [“COUNTRY = us”,; ["Overall"] for all the rows. Dimensions are named in upper case, as Snowflake names them, unless their name has upper-case letters |
METRIC_, METRIC_ |
The segment’s metric totals in the control and test rows |
CONTRIBUTION |
METRIC_ |
RELATIVE_ |
Its share of the overall change |
GROWTH_ |
CONTRIBUTION / |
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_ |
Igloo class | CONFIG_ |
|---|---|---|
LINEAR_ |
IGLOO. |
'algorithm': 'linear' |
BOOSTED_ |
IGLOO. |
‘algorithm’: ‘boosted_ (the default) |
RANDOM_ |
IGLOO. |
‘algorithm’: ‘random_ |
LOGISTIC_ |
IGLOO. |
'algorithm': 'logistic' |
BOOSTED_ |
IGLOO. |
‘algorithm’: ‘boosted_ (the default) |
RANDOM_ |
IGLOO. |
‘algorithm’: ‘random_ |
DNN_, DNN_ |
IGLOO., IGLOO. |
‘hidden_, 'dropout' and the like |
AUTOML_, AUTOML_ |
IGLOO., IGLOO. |
‘budget_, ‘optimization_ |
KMEANS |
IGLOO. |
‘num_, or none to pick one |
PCA |
IGLOO. |
‘num_ or ‘pca_ |
MATRIX_ |
IGLOO. |
USER_, ITEM_, RATING_ arguments; ‘feedback_ |
AUTOENCODER |
IGLOO. |
‘hidden_, the narrowest the latent space |
XGBOOST imports |
IGLOO. trains XGBoost’s own models |
XGBoost’s parameters by their names |
ARIMA_, ARIMA_ |
SNOWFLAKE. |
a different method, with intervals |
CONTRIBUTION_ |
SNOWFLAKE. |
|
DNN_, TENSORFLOW, ONNX, remote models, TRANSFORM |
not supported | train from a query that computes the features |
| BigQuery function | Igloo method | Classes |
|---|---|---|
ML. |
PREDICT |
all |
ML. |
EXPLAIN_ |
REGRESSION, CLASSIFICATION, XGBOOST, and the AUTOML classes but for a network |
ML. |
DETECT_ |
KMEANS, PCA, AUTOENCODER |
ML. |
RECONSTRUCTION_ |
AUTOENCODER |
ML. |
CENTROIDS |
KMEANS |
ML., ML. |
PRINCIPAL_, PRINCIPAL_ |
PCA |
ML. |
RECOMMEND |
MATRIX_ |
ML. |
EVALUATE |
all |
ML., ML. |
CONFUSION_, ROC_ |
the classifiers |
ML. |
GLOBAL_ |
the regressions and classifiers |
ML. |
FEATURE_ |
tree models |
ML., ML. |
WEIGHTS |
linear and logistic models |
ML. |
TRAINING_ |
boosted trees (XGBOOST too), networks (AUTOENCODER too), KMEANS, MATRIX_ |
ML. |
TRIAL_ |
the AUTOML classes |
Row methods and table methods
Section titled “Row methods and table methods”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.
Training
Section titled “Training”- 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 backdata_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 failsCREATE. The model’s metrics recordinput_rowsandsampled_rows. seed(default 0) seeds sampling and training: models are the same for the same rows and seed.- Unknown
CONFIG_OBJECTkeys are refused, so that a misspelled option does not go unnoticed.
REGRESSION and CLASSIFICATION
Section titled “REGRESSION and CLASSIFICATION”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_probsFROM TABLE(demo.converts!PREDICT(INPUT_DATA => TABLE(demo.new_leads)));
SELECT person_id, top_feature_attributionsFROM 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_ |
max_ (rounds, default 500, stopped early on a tenth of the training rows unless ‘early_), learn_ (0.1), max_ (12), num_ (31), subsample, colsample_, colsample_ (1), l2_ (1), min_, min_ (20) |
‘random_ |
num_ (trees, default 100), subsample (0.8), colsample_ (0.8), colsample_ (1), max_ (12), num_ (127), l2_, min_ (2) |
'linear', 'logistic' |
l2_ (a ridge penalty on standardized features, default 0); fit exactly by iteratively reweighted least squares, so optimize_ and learn_ 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,; as a table, predicted_ (and predicted_, JSON) |
EXPLAIN_ |
the prediction with top_ ([{“feature”,, the top_ largest, default 5), baseline_, prediction_ and approximation_ (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_, mean_, mean_ (NULL with negative values), median_, r2_, explained_; classification: precision, recall, accuracy, f1_ (the second class’s at a threshold of 0.5 for two classes, macro averages for more), log_, roc_ |
CONFUSION_ |
expected_, predicted_, count, on the held-out rows |
ROC_ |
two classes: threshold (0 to 1 by 0.01), recall, false_, true_, false_, true_, false_ |
GLOBAL_ |
feature, attribution: the mean absolute attribution, largest first |
FEATURE_ |
trees: feature, importance_ (splits), importance_, importance_ (rows per split) |
WEIGHTS |
linear and logistic models: class (for three classes or more), processed_ (the feature, or ), category, weight, standard_, p_ (BigQuery’s ML.) |
TRAINING_ |
boosted trees: iteration, loss, eval_ (on the early-stopping rows), learning_ |
DNN_REGRESSOR and DNN_CLASSIFIER
Section titled “DNN_REGRESSOR and DNN_CLASSIFIER”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_ |
[64, |
activation_ |
'relu'; or 'tanh', 'sigmoid', 'linear' |
dropout |
0 |
batch_ |
about a thirty-second of the training rows, from 32 to 1,024 |
learn_ |
0.001 |
max_ |
epochs: enough for some 3,000 steps, from 5 to 500 |
early_ |
TRUE |
l2_ |
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.
AUTOML_REGRESSOR and AUTOML_CLASSIFIER
Section titled “AUTOML_REGRESSOR and AUTOML_CLASSIFIER”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.
KMEANS
Section titled “KMEANS”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_ (from 1) and nearest_, every centroid’s distance, nearest first, as JSON |
DETECT_ |
is_, normalized_ (the distance to the nearest centroid divided by the mean distance of its training rows) and centroid_; CONFIG_ (more than 0, at most 0.5) is the share of training rows that would be anomalies, which sets the threshold |
EVALUATE |
davies_ and mean_ (in standardized units), on the training rows or on INPUT_ |
CENTROIDS |
centroid_, feature, numerical_ (in the feature’s own units), and for categories category and categorical_, the share of the cluster’s rows in it |
TRAINING_ |
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_2FROM 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_, principal_, …: the row’s coordinates |
DETECT_ |
is_ and mean_, the row’s distance from its projection, against the training rows’ errors by CONFIG_ |
EVALUATE |
total_, of the training rows or of INPUT_ |
PRINCIPAL_ |
principal_, feature, numerical_ (a number’s loading), and for categories category and categorical_ |
PRINCIPAL_ |
principal_, eigenvalue, explained_, cumulative_ |
MATRIX_FACTORIZATION
Section titled “MATRIX_FACTORIZATION”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_confidenceFROM 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 penaltyl2_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 by1 + wals_alpha × rating(wals_alphadefault 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_), or confidence for implicit feedback (predicted_), from INPUT’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_ (its user column), the top_ items (default 10), best first, as rows of the input’s columns, the item column and the prediction; ‘exclude_ 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_, it recommends to every user the model knows |
EVALUATE |
on the held-out interactions or INPUT_’s: a regression’s metrics for explicit ratings; for implicit feedback, over up to 1,000 users, mean_ and normalized_ of the held-out items among those each user did not rate in training, average_ (their mean percentile rank, 0 at the top) and mean_ |
TRAINING_ |
each iteration’s training loss: explicit ratings’ root mean squared error, implicit feedback’s weighted squared error per user |
AUTOENCODER
Section titled “AUTOENCODER”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_, latent_, …: the row in the latent space |
RECONSTRUCTION_ |
the row’s mean_, mean_ and mean_ (negative values’ logs taken as 0’s), over its encoded columns |
DETECT_ |
is_ and mean_, against the training rows’ errors by CONFIG_ |
EVALUATE |
the three errors’ means, on the held-out rows (or the training rows without them) or on INPUT_ |
TRAINING_ |
each epoch’s training and validation loss |
XGBOOST
Section titled “XGBOOST”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_convertFROM 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_daysFROM 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,etaorlearning_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: aneval_metricarray as several metrics,monotone_constraints’ array as(1,0,-1). Defaults are XGBoost’s (reg:squarederror, anetaof 0.3, amax_depthof 6). XGBoost refuses a value it does not take, and Igloo refuses a parameter XGBoost does not use, such asn_estimators, whichxgboost.trainignores, both with XGBoost’s message. - Training options, which are not XGBoost’s:
num_boost_round(default 10, asxgboost.train‘s);early_stopping_rounds, which stops training once the validation rows’ last metric (the lasteval_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, bydata_split_method:'no_split'(the default: every row trains, as inxgboost.train),'random'and'auto_split'as for the other classes (above), or'custom'withdata_split_col, a boolean column that isTRUEfor 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’sbest_iterationandbest_score, and its methods use the trees up to it. - Labels.
TARGET_COLNAMEis a number, or a boolean (1 and 0), which XGBoost takes as it is: 0 and 1 for thebinary:objectives, 0 tonum_class- 1 for themulti:ones. Rows whose target isNULLare left out; text is refused (map classes to numbers in the query). Forsurvival:aft,LABEL_LOWER_BOUND_COLNAMEandLABEL_UPPER_BOUND_COLNAMEgive 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 aNULLbound is refused.WEIGHT_COLNAMEweighs each row. - Features are every other column, as XGBoost’s float32s: numbers,
booleans as 1 and 0, timestamps and dates as seconds since 1970,
NULLas 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 inINPUT_DATA’s query (region = 'south' AS south). - Training runs on the replica that runs
CREATE, on every core (XGBoost’snthreadto 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,, booleans’ as False and True) for the classification objectives (binary:hinge has no probability); CONFIG_ adds margin, the raw score before the objective’s transformation. As a table, predicted_ (a classifier’s class, of the target’s type) and predicted_ (JSON), and predicted with output; an interval label’s model names them after label |
EXPLAIN_ |
the prediction with top_ (the top_ largest, default 5), baseline_ and prediction_: XGBoost’s SHAP values (pred_), in margin space, which with the bias, the baseline, add up to the margin, prediction_; approximation_ 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_’s, or the objective’s) on the validation rows at the best iteration, or on INPUT_’s rows, which hold the label’s columns |
TRAINING_ |
iteration (XGBoost’s, from 0), metric, training_, validation_, is_: each metric of each round, as XGBoost measured it |
FEATURE_ |
feature, importance_ (splits), importance_, importance_: 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.
Differences from BigQuery
Section titled “Differences from BigQuery”- The statements are Snowflake’s, not
CREATE MODEL ... OPTIONS (...) AS SELECTandML.<function>(MODEL m, ...): the tables above map one to the other.TRANSFORM,input_label_cols(useTARGET_COLNAME),data_split_coland the'custom'and'seq'splits,l1_reg,auto_class_weights,warm_start, hyperparameter tuning inCREATE(num_trials; theAUTOMLclasses 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_iterationsrounds, andRECOMMENDreturnstop_kitems rather than every item. - Tables BigQuery returns with a column per class or category, or arrays
of structures, are rows here:
CONFUSION_MATRIXhas a row per pair of classes,CENTROIDSandPRINCIPAL_COMPONENTSa 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_PREDICTattributes a class’s raw score (log-odds for boosted trees and logistic models), and networks have none; theirGLOBAL_EXPLAINis by permutation.
Train and score in one query
Section titled “Train and score in one query”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_confidenceFROM 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: forai_predict_classthe class, of the target’s type, and<target>_confidence, its probability; forai_predict_valueaDOUBLE. - 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. |
the input, TABLE name or (query); data_, timestamp_; model (default ‘TimesFM 2.); id_; horizon (default 10) or forecast_, the last step’s; confidence_ (0.95); output_; context_ |
the id_, forecast_, forecast_, confidence_, prediction_, prediction_, ai_; with the history, time_ ('history' or 'forecast'), time_ and time_ for the timestamp and value |
AI. |
the history; the target, a second TABLE or (query), or target_ or target_ of the history; data_, timestamp_; model; id_; anomaly_ (0.95); context_ |
the id_, time_, time_, is_, lower_, upper_, anomaly_, ai_ |
ai_ |
observed, TABLE(name) or TABLE(SELECT …; horizon, the first time not forecast; time_; value_, a column or an array of them; group_, a column or an array; prediction_ (0.95); frequency (pandas’ 'D', 'H', '15min', 'W', 'MS', or '1 day'; inferred by default); positive_; version ('1' or '2'); model (an Igloo extension; default 'chronos-2') |
time_, the groups, and for each value column <v>, <v> and <v>_ |
ai_ |
observed; time_; value_; group_; anomaly_ (0.95); only_, a number of points or a timestamp; smoothing (accepted, no effect); model (default 'chronos-2') |
time_, the groups, the value column, expected, lower_, upper_, anomaly_, is_ |
- Models.
modelnames a model of the pack asmethoddoes (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’stimesfm-2.5. Databricks names no model; Igloo forecasts withchronos-2unlessmodelsays 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; abigqueryintegration 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 inai_forecast_status(ai_detect_anomalies_status), and the others are forecast;ai_forecastleaves it out. - Detection. A point is anomalous when its
anomaly_probability,|2F(y) - 1|whereFis the model’s forecast distribution at that step (0 at the median, near 1 far in either tail), is above the threshold;lower_boundandupper_boundare the interval at the threshold.AI.DETECT_ANOMALIESforecasts the target points (the last 1,024 of each series) from the history before them.ai_detect_anomaliesscores 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_windowof 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’starget_colsand future covariates),holiday_region, and version 1’s prophet-likeparametersare 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. Withoutid_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.
Hosted models
Section titled “Hosted models”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 /, at https:// or BASE_ (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_) |
a Vertex AI endpoint of TimesFM from Model Garden: its ID, endpoints/ or projects/ (shared public endpoints) |
the endpoint’s predict |
bigquery |
a model AI. takes: ‘TimesFM 3. or ‘TimesFM 2. |
BigQuery’s AI., 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’sai_integrationchooses among several). Users needUSAGEon the integration, as for AI functions. - Which one.
EXPLAINof a statement that forecasts adds aforecast modelrow 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_windowpoints (2,048 by default), from its first value, with gaps filled in between their neighbours, its start and its step. With abigqueryintegration the series’ timestamps and values leave for BigQuery, which runsAI.FORECASTover 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; setPRICESfor 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.
Where models live
Section titled “Where models live”- A model’s row is in the metadata database (
IGLOO_METADATA_DATABASE_URL), shared by every replica: its name, class, owner, comment, theCREATEstatement, 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
CREATEthat 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_FACTORIZATIONmodel is the exception: it keeps every user’s and item’s identifier, a vector of factors for each, and, forexclude_seen, which items each user rated. A model row keeps itsCREATEstatement. - 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
CREATEstatement, as its owner, with the search path and dialect it was created with, asCREATE OR REPLACEwould, 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. ACREATEthat 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 requestblocked, 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.
The engine
Section titled “The engine”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 aCLASSIFICATIONmodel on such a table, holdout metrics included, takes about 15 seconds on 18 cores (BenchmarkClassifier1Mininternal/models, run withIGLOO_ML_BENCH=1). - Scoring with
PREDICTruns 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’sDETECT_ANOMALIES, theSHOW_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.XGBOOSTtrains 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_, DNN_ ([64,) |
19 and 15 s |
AUTOML_: 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_: ten million interactions of 100,000 users with 10,000 items, explicit and implicit |
12 and 15 s |
Differences from Snowflake
Section titled “Differences from Snowflake”- 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!PREDICTorTABLE(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;methodmay 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_IMPORTANCEand 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 domainisDOMAIN). ALTERof models, Snowflake’s other ML classes (CUSTOM_CLASSIFIERand the like), the Model Registry (MODEL(...)!method) andGRANT CREATE SNOWFLAKE.ML.<class>are refused.