What you will be able to do
- Write a vectorized Python UDF and explain how it differs from row-by-row scalar UDFs
- Upload files to an internal stage with PUT
- Score data with a pre-built Snowflake ML Function and store the predictions in a table
- Explain how an external function reaches a model hosted outside Snowflake, and its limits
1.Scalar and vectorized Python UDFs
You can also deploy a model inside Snowflake as your own Python user-defined function. By default, a Python UDF processes one row at a time. A vectorized UDF receives a batch of input rows as a pandas DataFrame and returns a pandas array or Series. This can perform better when your code works efficiently on batches, and it fits naturally with libraries that already take DataFrames, which most model predict calls do. Queries don't change: you call a vectorized UDF exactly as you would a scalar one, and the UDF framework handles the batching.
A UDF can also depend on files that its handler reads, such as a serialized model or a configuration file. Upload the file to a stage, then reference it with the IMPORTS clause when you create the function. The function owner needs the READ privilege on the stage.
CREATE FUNCTION add_one_to_inputs(x NUMBER(10, 0), y NUMBER(10, 0))
RETURNS NUMBER(10, 0)
LANGUAGE PYTHON
RUNTIME_VERSION = 3.12
PACKAGES = ('pandas')
HANDLER = 'add_one_to_inputs'
AS $$
import pandas
from _snowflake import vectorized
@vectorized(input=pandas.DataFrame)
def add_one_to_inputs(df):
return df[0] + df[1] + 1
$$;Inside the handler, arguments are accessed by position: df[0] is the first argument and df[1] the second. The array you return must be the same length as the input DataFrame. Instead of the decorator, you can set _sf_vectorized_input = pandas.DataFrame on the handler. Each handler call has a 180-second limit. If your code can only process a limited number of rows, cap the batch with max_batch_size, or _sf_max_batch_size as an attribute. If it can handle batches of any size, leave the setting unset. Setting it doesn't request larger batches.
Checkpoint 1 of 5· Check yourself
A vectorized scoring UDF works fine on batches of any size. What should the team do with max_batch_size?
max_batch_size only limits batches for handlers that can't cope with large ones. It is not a way to request larger batches.
“If the UDF is able to process batches of any size, it is recommended to leave this parameter unset.”Source: docs.snowflake.com
2.Moving files with stage commands
Model artifacts and data files reach Snowflake through stages. PUT uploads one or more files from a local file system to an internal stage: a named stage (@name), a table stage (@%table) or your user stage (@~). The related commands are GET, LIST and REMOVE. Use LIST to see which files are on a stage.
To make a staged file available to a UDF or stored procedure, follow three steps: choose or create a stage, upload the file, and reference it with the IMPORTS clause when you create the function or procedure. PUT compresses files by default. If you omit AUTO_COMPRESS = FALSE, the staged file gets a .gz extension, and you must use that name in IMPORTS. PUT cannot target an external stage, so use the cloud provider's utilities there.
PUT file://<absolute_path_to_file>/<filename> internalStage
[ PARALLEL = <integer> ]
[ AUTO_COMPRESS = TRUE | FALSE ]
[ SOURCE_COMPRESSION = AUTO_DETECT | GZIP | BZ2 | BROTLI | ZSTD | DEFLATE | RAW_DEFLATE | NONE ]
[ OVERWRITE = TRUE | FALSE ]LIST @my_stage;Checkpoint 2 of 5· Check yourself
An engineer wants to run PUT to copy a serialized model from a laptop to an external S3 stage. What happens?
PUT can only target internal stages. For an external stage, use your cloud provider's utilities.
“PUT does not support uploading files onto an external stage.”Source: docs.snowflake.com
3.Pre-built ML Functions and storing predictions
You don't always need to deploy your own model. Snowflake ML Functions, such as Classification, are pre-built in Snowflake. You train one and call its PREDICT method in SQL. These models are separate from the Model Registry, and those trained with ML Functions do not appear in it. Some model types, such as Cortex Fine-Tuned LLMs, appear in the registry's Snowsight UI but are not managed by the registry API.
You can use PREDICT output directly in a query. To store it, wrap the call in CREATE TABLE ... AS SELECT. The prediction column holds structured values, so later queries can pull out fields such as predictions:class and per-class probabilities.
CREATE OR REPLACE TABLE my_predictions AS
SELECT *, model_multiclass!PREDICT(INPUT_DATA => {*}) AS predictions FROM prediction_purchase_data;Predictions from a model you logged in the Model Registry can be stored too. mv.run returns a DataFrame of the same type you passed in, so you can persist the result from Snowpark. One option is a dynamic table that applies the model to incoming rows and keeps the predictions refreshed, as in the example below. For large jobs, run_batch runs batch inference on Snowpark Container Services and writes its results to an output stage, which you then read from there.
CREATE OR REPLACE DYNAMIC TABLE logins_with_predictions
WAREHOUSE = my_wh
TARGET_LAG = '20 minutes'
REFRESH_MODE = INCREMENTAL
INITIALIZE = on_create
COMMENT = 'Dynamic table with continuously updated model predictions'
AS
SELECT
login_id,
user_id,
location,
event_time,
MODEL(ml.registry.mymodel)!predict(l.user_id, l.location) AS prediction_result
FROM logins_raw;Checkpoint 3 of 5· Check yourself
A team trained a Snowflake ML Functions classification model and looks for it in the Model Registry. What will they find?
Models trained with Snowflake ML Functions are separate from the registry. You call their PREDICT method directly.
“Models trained using Snowflake ML Functions (for example, FORECAST) do not appear in the model registry.”Source: docs.snowflake.com
4.External functions for externally hosted models
If a model is hosted outside Snowflake, an external function lets SQL call it. An external function is a UDF with no code of its own. Its database object stores the proxy service URL, and an API integration (created with CREATE API INTEGRATION) holds the security details. The remote service must expose an HTTPS endpoint, accept JSON input and return JSON output. Examples are an AWS Lambda function, an Azure Function, or an HTTPS server on EC2. To SQL users, an external function looks like any other UDF.
Because the remote service is opaque code outside Snowflake, it can use libraries that internal UDFs can't reach, such as commercial third-party machine-learning scoring libraries, and it can be written in languages such as Go or C#. The same service can also be called from other software that uses the same interface. Separately, the Model Registry lets you import a model from an external provider into Snowflake instead of calling it remotely.
Checkpoint 4 of 5· Put it in order
Put the steps of an external function call in order.
- 1.The proxy service forwards the request to the remote service
- 2.Snowflake sends an HTTP POST with JSON data to the proxy service
- 3.The result returns through the chain to the SQL statement
- 4.A client program sends Snowflake a SQL statement that calls the external function
- 5.Snowflake reads the external function definition and its API integration
The definition and integration supply the proxy URL and credentials. The proxy relays the request, and the result travels back the same way.
“The proxy service receives the POST and then processes and forwards the request to the actual remote service.”Source: docs.snowflake.com
External functions have limits. They must be scalar, returning one value per input row, and they can't be stored procedures. Large inputs are sent in batches of rows, each with its own ID, and each batch's response can be at most 10MB. External functions carry more overhead than internal UDFs and usually run more slowly. They can't be shared through Secure Data Sharing or used in a COPY transformation. Data also leaves Snowflake: a third-party provider could keep copies of what you send. On top of warehouse and data-transfer costs, the remote service provider may charge you.
Checkpoint 5 of 5· Exam question
A bank must not send customer rows outside its cloud account. Select TWO characteristics of external functions that make them a poor fit for this requirement or for large-batch scoring.(Select 2)
Correct answers: D, E — Each batch of rows travels over HTTPS through a cloud proxy service to the remote endpoint, adding network latency and moving data out of Snowflake; An external function must return exactly one scalar value per input row, so multi-row table outputs for each input row are not available to the caller
- A. The remote service is hosted outside Snowflake, so it is not executed on a warehouse. Warehouse credits only cover the calling query.
- B. External functions are SQL functions and work in any SQL context, so this restriction does not exist.
- C. External functions have no connection to the Model Registry, and no re-registration step is part of invoking them.
- D. Rows are serialized and sent to a remote service through a proxy, so latency is added and data leaves the Snowflake boundary, which conflicts with the bank's constraint.
- E. External functions are scalar, which limits the shapes of output that can be returned compared with in-Snowflake table functions.
Exam traps
Each one states something that sounds right. Open it to see what is actually true.
1.An external function can wrap a remote model as a table function or a stored procedure.Why is that wrong?
External functions are currently scalar only: one value per input row. Stored procedures cannot be written with the feature.
2.An external function performs about the same as an internal Python UDF.Why is that wrong?
External functions add overhead and are opaque to the optimizer, so they usually run more slowly than internal UDFs.
Sources
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Vectorized Python UDFs let you define Python functions that receive batches of input rows as Pandas DataFrames”
↩︎ Scalar and vectorized Python UDFs“You call vectorized Python UDFs the same way you call other Python UDFs.”
↩︎ Scalar and vectorized Python UDFs“The Pandas array or Series that the UDF handler returns must have the same length as that of the input DataFrame.”
↩︎ Scalar and vectorized Python UDFs“If the UDF is able to process batches of any size, it is recommended to leave this parameter unset.”
↩︎ Checkpoint - 2.
“Reference the dependency with IMPORTS when you create the function or procedure.”
↩︎ Scalar and vectorized Python UDFs“Reference the dependency with IMPORTS when you create the function or procedure.”
↩︎ Moving files with stage commands - 3.https://docs.snowflake.com/en/sql-reference/sql/putOfficial docs
“Uploads one or more data files from a local file system onto an internal stage.”
↩︎ Moving files with stage commands“PUT does not support uploading files onto an external stage.”
↩︎ Checkpoint - 4.
“To see files that have been uploaded to a Snowflake stage, use the LIST command:”
↩︎ Moving files with stage commands - 5.
“saving the results to a table allows you to conveniently explore predictions.”
↩︎ Pre-built ML Functions and storing predictions - 6.https://docs.snowflake.com/en/developer-guide/snowflake-ml/inference/native-batch-inference-sqlOfficial docs
“The code sample above will run inference using MYMODEL on new data in LOGINS_RAW every 20 minutes automatically.”
↩︎ Pre-built ML Functions and storing predictions - 7.
“Some model types, such as Cortex Fine-Tuned LLMs, appear in the model registry’s Snowsight UI, but are not managed by the model registry API.”
↩︎ Pre-built ML Functions and storing predictions“You can also import a model from an external provider to Snowflake.”
↩︎ External functions for externally hosted models“Models trained using Snowflake ML Functions (for example, FORECAST) do not appear in the model registry.”
↩︎ Checkpoint - 8.
“Snowflake stores security-related external function information in an API integration.”
↩︎ External functions for externally hosted models“remote services can interface with commercially available third-party libraries, such as machine-learning scoring libraries.”
↩︎ External functions for externally hosted models“Currently, external functions must be scalar functions.”
↩︎ External functions for externally hosted models“Only functions, not stored procedures, can be written using the external functions feature.”
↩︎ Exam trap 1“External functions have more overhead than functions (both built-in functions and internal UDFs) and usually execute more slowly.”
↩︎ Exam trap 2“Snowflake does not call a remote service directly. Instead, Snowflake calls a proxy service, which relays the data to the remote service.”
↩︎ Prediction“The proxy service receives the POST and then processes and forwards the request to the actual remote service.”
↩︎ Checkpoint