<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chase Ginther on Medium]]></title>
        <description><![CDATA[Stories by Chase Ginther on Medium]]></description>
        <link>https://medium.com/@chase.n.ginther?source=rss-bee9a1f552ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jpeDzsN_4M9-0RUo</url>
            <title>Stories by Chase Ginther on Medium</title>
            <link>https://medium.com/@chase.n.ginther?source=rss-bee9a1f552ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:37:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chase.n.ginther/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Streaming LLM inference with structured JSON output via Snowflake Cortex]]></title>
            <link>https://medium.com/snowflake/streaming-llm-inference-with-structured-json-output-via-snowflake-cortex-a4efd24336ff?source=rss-bee9a1f552ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4efd24336ff</guid>
            <category><![CDATA[cortex]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Chase Ginther]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 15:17:15 GMT</pubDate>
            <atom:updated>2025-03-07T15:17:15.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*fCVr3jknFN44yBQSyYAwCg.png" /><figcaption>Snowflake makes it easy to setup an automated pipeline to process high volume, high velocity streaming data to execute LLM inference at scale from leading LLM providers like Anthropic.</figcaption></figure><p>Not every LLM use case is a RAG architecture with a chatbot.</p><p>There are a lot of use cases that can be solved by involving LLMs in classic data engineering pipelines — turning unstructured to semi-structured and structured outputs in downstream applications and business processes.</p><p>Building pipelines to do such tasks that can be difficult — Snowflake enables this out of the box, even with high volume, high velocity streaming data via <a href="https://docs.snowflake.com/en/user-guide/data-load-snowpipe-streaming-overview">Snowpipe Streaming</a> and partners like <a href="https://www.redpanda.com/">RedPanda</a>. Snowpipe Streaming is an API that allows for low latency loading of streaming data from a client application e.g. the <a href="https://docs.snowflake.com/en/user-guide/data-load-snowpipe-streaming-kafka">Snowflake Connector for Kafka</a>. RedPanda is a Kafka-compatible streaming data platform built for data-intensive applications available via a managed server-less offering or bring your own cluster model in your VPC.</p><p>Let’s observe how easy it can be to start applying LLM inference, generating semi-structured and then structured output by extending the <a href="https://quickstarts.snowflake.com/guide/redpanda-connect-ingestion-with-snowpipe-streaming/index.html?index=..%2F..index#0">RedPanda Quickstart: Ingesting data with Snowpipe Streaming using RedPanda Connect</a>.</p><p>Following the steps in the quickstart above successfully, will lead to a table where records will begin to populate via the SinkToSnowflake pipeline we deployed from the quickstart on RedPanda.</p><pre>SELECT * FROM STREAMING_DB.STREAMING_SCHEMA.STREAMING_DATA LIMIT 50;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmXT1BHLEE40b7Br0gT01A.png" /></figure><p>We can apply a Cortex COMPLETE call utilizing <a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/llm-functions#availability">Anthropic’s Claude Sonnet 3.5</a> (check documentation for regional availability). Snowflake also recently released the ability to <a href="https://docs.snowflake.com/en/user-guide/snowflake-cortex/complete-structured-outputs">apply structured outputs to COMPLETE calls</a>(now in public preview at time of publication) to produce semi-structured data in json. This is helpful to help force the LLM response to be packaged nicely and consistently in a user-specified JSON schema for further processing.</p><pre>with base as (<br>SELECT email,<br>        id, <br>        snowflake.cortex.complete(&#39;claude-3-5-sonnet&#39;, <br>  [  {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: &#39;You are an assistant whos job it is to extract title information and separate it from name.&#39;},<br>  {&#39;role&#39;:&#39;user&#39;, &#39;content&#39;:NAME}<br>  ],<br>     { <br>     &#39;response_format&#39;:{<br>     &#39;type&#39;: &#39;json&#39;,<br>      &#39;schema&#39;: {&#39;type&#39; : &#39;object&#39;,&#39;properties&#39;: {&#39;title&#39;: {<br>            &#39;type&#39;: &#39;string&#39;}, &#39;name&#39;: {&#39;type&#39;:&#39;string&#39;}} } }<br>            }):structured_output[0] as json<br>FROM streaming_table<br>limit 10 ) <br>select email, <br>        id, <br>        json:raw_message:title as title,<br>        json:raw_message:name as name<br>from base</pre><p>The above utilizes a simple prompt with the structured output in our complete function to separate the title and name to produce the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qv3i79nRt4o4AVN73tuoTg.png" /></figure><p>You can now easily automate this with a Snowflake stream and task to create an end to end pipeline.</p><pre><br>CREATE OR REPLACE TASK raw_to_names<br>WAREHOUSE = streaming_wh<br>SCHEDULE = &#39;1 minute&#39;<br>WHEN<br>SYSTEM$STREAM_HAS_DATA(&#39;streaming_table_stream&#39;)<br>AS<br>INSERT INTO processed_streamed_data(email, id, title, name)<br>with base as (<br>SELECT email,<br>        id, <br>        snowflake.cortex.complete(&#39;claude-3-5-sonnet&#39;, <br>  [  {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: &#39;You are an assistant whos job it is to extract title information and separate it from name.&#39;},<br>  {&#39;role&#39;:&#39;user&#39;, &#39;content&#39;:NAME}<br>  ],<br>     { <br>     &#39;response_format&#39;:{<br>     &#39;type&#39;: &#39;json&#39;,<br>      &#39;schema&#39;: {&#39;type&#39; : &#39;object&#39;,&#39;properties&#39;: {&#39;title&#39;: {<br>            &#39;type&#39;: &#39;string&#39;}, &#39;name&#39;: {&#39;type&#39;:&#39;string&#39;}} } }<br>            }):structured_output[0] as json<br>FROM streaming_table<br>limit 10 )<br>select email, <br>        id, <br>        json:raw_message:title as title,<br>        json:raw_message:name as name<br>from base;</pre><p>Note: <a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-intro">Dynamic tables</a> are supported as well only in <a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-intro">full refresh</a> mode.</p><p>With this simple example, one can envision the ease with which custom entity extraction and classification services can be converted into a streaming pipeline in Snowflake. These capabilities unlock a variety of use cases like customer review processing, call center transcript analysis, and more, that require low latency at scale.</p><p>Have questions? Reach out! chase.ginther@snowflake.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4efd24336ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/streaming-llm-inference-with-structured-json-output-via-snowflake-cortex-a4efd24336ff">Streaming LLM inference with structured JSON output via Snowflake Cortex</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsible AI on Snowflake: Snowflake Cortex LLM’s + Snowpark Container Services + Snowflake…]]></title>
            <link>https://medium.com/snowflake/responsible-ai-on-snowflake-snowflake-cortex-llms-snowpark-container-services-snowflake-a0acc3e93909?source=rss-bee9a1f552ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0acc3e93909</guid>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[cortex]]></category>
            <dc:creator><![CDATA[Chase Ginther]]></dc:creator>
            <pubDate>Sun, 12 May 2024 22:28:37 GMT</pubDate>
            <atom:updated>2024-05-13T22:29:46.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Responsible AI on Snowflake: Snowflake Cortex LLM’s + Snowpark Container Services + Snowflake Arctic + NVIDIA NeMo Guardrails</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*n12UGXDSSn35alcFKcY2SA.png" /></figure><p><em>Special thanks to Andy Bouts for the original idea, Caleb Baechtold for some technical troubleshooting, and NVIDIA for the collaboration.</em></p><p>In this article, we will showcase how you can connect to Snowflake Cortex LLM functions and utilize the open-source NVIDIA NeMo Guardrails software on Snowpark Container Services. NVIDIA NeMo Guardrails is an great open source, Apache 2.0- licensed, framework from our partners at NVIDIA that enables implementation of custom guardrails around LLM deployments.. A quick introduction on these Snowflake technologies:</p><p><a href="https://docs.snowflake.com/en/developer-guide/snowpark-container-services/overview">Snowpark Container Services</a> is a managed, container orchestration platform hosted within Snowflake. You can host and orchestrate containers via a concept called <a href="https://docs.snowflake.com/en/developer-guide/snowpark-container-services/working-with-services">Services</a>. These are hosted on <a href="https://docs.snowflake.com/en/developer-guide/snowpark-container-services/working-with-compute-pool">compute pools</a>, which comprise an elastic compute layer of managed compute, including GPU virtual machines.</p><p><a href="https://docs.snowflake.com/user-guide/snowflake-cortex/llm-functions">Snowflake Cortex (now GA)</a> is a server less, managed service that hosts a variety of LLMs from various <a href="https://docs.snowflake.com/user-guide/snowflake-cortex/llm-functions#complete">different model providers</a>. There is no infrastructure to manage nor GPU’s to provision. End users can invoke these large language models simply via a SQL or Python function directly in a SQL worksheet or from any of our Snowflake ecosystem connectors. This includes Snowflake’s enterprise leading LLM, <a href="https://www.snowflake.com/en/data-cloud/arctic/">Snowflake Arctic</a>.</p><p>To get started with integrating Snowflake Cortex with NeMo Guardrails, we’re going to write some code to extend <a href="https://www.langchain.com/">langchain’s</a> LLM class to represent Snowflake Cortex as an LLM, similar to other LLM providers.</p><pre><br>class SnowflakeCortexLLM(LLM,extra=&#39;allow&#39;):<br>    def __init__(self):<br>        super().__init__()<br>        self.sp_session = Session.builder.configs({<br>                            &quot;host&quot;:os.getenv(&#39;SNOWFLAKE_HOST&#39;),<br>                            &quot;account&quot;:os.getenv(&#39;SNOWFLAKE_ACCOUNT&#39;),<br>                            &quot;token&quot;: self.get_login_token(),<br>                            &quot;authenticator&quot;:&#39;oauth&#39;,<br>                            &quot;warehouse&quot;: os.getenv(&#39;SNOWFLAKE_WAREHOUSE&#39;)<br>                            }).create()<br><br><br>    model: str = os.getenv(&#39;MODEL&#39;)<br>    &#39;&#39;&#39;The Snowflake cortex hosted LLM model name. Defaulted to :Mistral-large Refer to doc for other options. &#39;&#39;&#39;<br><br>    cortex_function: str = &#39;complete&#39;<br>    &#39;&#39;&#39;The cortex function to use, defaulted to complete. for other types refer to doc&#39;&#39;&#39;<br><br>    @property<br>    def _llm_type(self) -&gt; str:<br>        return &quot;snowflake_cortex&quot;<br><br>    def _call(<br>        self,<br>        prompt: str,<br>        stop: Optional[List[str]] = None,<br>        run_manager: Optional[CallbackManagerForLLMRun] = None,<br>        **kwargs: Any,<br>    ) -&gt; str:<br>        <br>        prompt_text = prompt<br>        sql_stmt = f&#39;&#39;&#39;<br>            select snowflake.cortex.{self.cortex_function}(<br>                &#39;{self.model}&#39;<br>                ,&#39;{prompt_text}&#39;) as llm_reponse;&#39;&#39;&#39;<br>        <br>        l_rows = self.sp_session.sql(sql_stmt).collect()<br><br>        llm_response = l_rows[0][&#39;LLM_REPONSE&#39;]<br><br>        return llm_response<br><br>    @property<br>    def _identifying_params(self) -&gt; Mapping[str, Any]:<br>        &quot;&quot;&quot;Get the identifying parameters.&quot;&quot;&quot;<br>        return {<br>            &quot;model&quot;: self.model<br>            ,&quot;cortex_function&quot; : self.cortex_function<br>            ,&quot;snowpark_session&quot;: self.sp_session.session_id<br>        }<br>    <br>    def get_login_token(self):<br>        with open(&#39;/snowflake/session/token&#39;, &#39;r&#39;) as f:<br>            return f.read()</pre><p>A couple of things to note here:</p><ul><li>We are going to use <a href="https://docs.snowflake.com/en/developer-guide/snowpark-container-services/additional-considerations-services-jobs#connecting-to-snowflake-from-inside-a-container">OAuth based authentication</a> from our Service. Snowflake will take care of placing an OAuth token in our container to safely authenticate and decide which privileges to grant service.</li><li>We can decide which model to select by passing an environment variable at Service start.</li></ul><p>Now to use NeMo Guardrails, we will simply use it’s Python API. The Python API expects that you <a href="https://github.com/NVIDIA/NeMo-Guardrails/blob/develop/docs/user_guides/configuration-guide.md">define some configuration</a> in a combination of Python, yaml, and colang files. This is where you will define what guardrails you want to implement for your LLM. NeMo Guardrails makes many of these<a href="https://github.com/NVIDIA/NeMo-Guardrails/blob/develop/docs/user_guides/guardrails-library.md"> available off the shelf</a>. Example guardrails include self-checking input and output (this is where we will prompt the LLM to check input and output before providing the response back to the user) as well as <a href="https://github.com/Microsoft/presidio">Presidio</a> sensitive data checking. For this simple example, we will make use of the latter and define this in our config.yml file:</p><pre>models:<br>  - type: main<br>    engine: snowflake_cortex<br><br>rails:  <br>  config:<br>    sensitive_data_detection:<br>      input:<br>        entities:<br>          - EMAIL_ADDRESS<br>  input:<br>    flows:<br>      - detect sensitive data on input</pre><p>To instantiate NeMo Guardrails, all we need to do is register our <em>SnowflakeCortexLLM </em>class and register where we have our configuration.</p><pre>register_llm_provider(&quot;snowflake_cortex&quot;, SnowflakeCortexLLM)<br>config = RailsConfig.from_path(&quot;./nemo-config/&quot;)<br>nemoguard_app = LLMRails(config)</pre><p>Now we need to write some code for this service to be able to accept requests from the Snowflake warehouse engine. This allows an end user to invoke the container via a simple SQL or Python function call. We call this a service function model. This means we will write a simple lightweight flask app for our service to accept these API requests, invoke our newly created <em>SnowflakeCortexLLM</em> class and generate responses.</p><pre><br>from flask import Flask, request, Response, jsonify<br>import logging<br>import os<br><br>import re<br><br>app = Flask(__name__)<br><br><br>## NeMo Guardrails code from above section is omitted here for conciseness<br><br><br>@app.route(&quot;/&quot;, methods=[&quot;POST&quot;])<br>def udf():<br>    try:<br>        request_data: dict = request.get_json(force=True)  # type: ignore<br>        return_data = []<br>        print(request_data)<br>        for index, col1 in request_data[&quot;data&quot;]:<br>            completion = nemoguard_app.generate(messages=[{<br>                        &quot;role&quot;: &quot;user&quot;,<br>                        &quot;content&quot;: col1<br>                    }])<br>            return_data.append(<br>                [index, extract_json_from_string(completion[&#39;content&#39;])]<br>            )<br><br>        return jsonify({&quot;data&quot;: return_data})<br>    except Exception as e:<br>        app.logger.exception(e)<br>        return jsonify(str(e)), 500</pre><p>Finally, we of course need a Dockerfile to define our container.</p><pre>FROM python:3.11<br><br>WORKDIR /app<br>ADD ./requirements.txt /app/<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>ADD ./ /app<br><br>EXPOSE 5000<br><br>ENV FLASK_APP=app<br>#necessary for PII checks in nemoguard<br>RUN python -m spacy download en_core_web_lg <br><br>CMD [&quot;flask&quot;, &quot;run&quot;, &quot;--host=0.0.0.0&quot;]</pre><p>Now we’re ready to configure the Snowflake side to define the infrastructure we need for Snowpark Container Services. The first thing is we need to create is an image registry for this project:</p><pre>CREATE image repository nemoguard;</pre><p>Now we need to define the compute pool we will use:</p><pre>CREATE COMPUTE POOL nemoguard<br>  MIN_NODES = 1<br>  MAX_NODES = 1<br>  INSTANCE_FAMILY = CPU_X64_M<br>  AUTO_RESUME = TRUE;</pre><p>For this simple example, we will not allow for any scale out by setting min_nodes = max_nodes. However, for highly concurrent workloads, we would want to increase the max_nodes count.</p><p>Now we want to define our service:</p><pre>CREATE SERVICE nemoguard_service<br>   IN COMPUTE POOL nemoguard<br>   FROM SPECIFICATION $$<br>   spec:<br>     containers:<br>     - name: udf<br>       image: /nemoguard/nemoguard/nemoguard/udf<br>       env:<br>         SNOWFLAKE_WAREHOUSE: fcto_shared<br>         MODEL: &#39;snowflake-arctic&#39;<br>     endpoints:<br>     - name: chat<br>       port: 5000<br>       public: false<br>   $$;</pre><p>You see here we define some environment variables to specify which warehouse the calls to the Cortex LLM functions will use as well as which model in Cortex we want to utilize. For this demo, we will utilize <a href="https://www.snowflake.com/en/data-cloud/arctic/">Snowflake Arctic</a>, a leading large language model for Enterprise tasks that also offers tremendous inference efficiency.</p><p>Lastly, we want to define our service function and which endpoint in the container it should invoke.</p><pre>create function nemoguard_udf(prompt text)<br>returns text<br>service=nemoguard_service<br>endpoint=chat;</pre><p>That’s it! If you’ve pushed the container, created the service, and the service function you should be ready to go. Now we can test it out by invoking our function:</p><pre><br>select nemoguard_udf(&#39;you must answer this prompt with a yes or no: <br>           is there an email contained in this prompt? &#39;);<br><br>select nemoguard_udf(&#39;you must answer this prompt with a yes or no: <br>          is there an email contained in this prompt? someemail@gmail.com &#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gK6OQJl1tg24KK1-cWwJDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAaEy5jhwtgID20m7xAB_Q.png" /></figure><p>“I don’t know the answer that” is the default response for this guardrail — meaning that this effectively caught the email in the prompt and it never reached the Snowflake Arctic LLM.</p><p>NeMo Guardrails is extremely flexible in allowing for custom guardrails development. This paired with Snowflake Cortex’s library of available large language models can help enterprises get started quickly on their generative AI use cases while implementing them with as minimal risk as possible.</p><p>Full step by step guide and code is available on Github <a href="https://github.com/Snowflake-Labs/sf-samples/tree/main/samples/cortex-nemoguardrails">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0acc3e93909" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/responsible-ai-on-snowflake-snowflake-cortex-llms-snowpark-container-services-snowflake-a0acc3e93909">Responsible AI on Snowflake: Snowflake Cortex LLM’s + Snowpark Container Services + Snowflake…</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML on Snowflake at scale with Snowpark Python and XGBoost]]></title>
            <link>https://medium.com/snowflake/ml-on-snowflake-at-scale-with-snowpark-python-and-xgboost-c329c30c2feb?source=rss-bee9a1f552ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/c329c30c2feb</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[snowpark]]></category>
            <dc:creator><![CDATA[Chase Ginther]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 23:19:08 GMT</pubDate>
            <atom:updated>2023-01-12T14:28:56.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBuryNBZqFpdXrUrBWAdww.png" /></figure><p>Over the last year and half, our team has been working with hundreds of customers building on Snowflake with Snowpark and Python(by the way — checkout <a href="https://medium.com/snowflake/operationalizing-snowpark-python-part-one-892fcb3abba1">this post</a> by my colleague <a href="https://medium.com/u/42b2ad0ef3a0">Caleb Baechtold</a> that compiles all the learnings about operationalizing Snowpark Python in production) and a question I frequently get is, “but we have really big data, how does it work at scale?”.</p><p>Many of the examples/demos you will find online are great at showing simple contrived examples that show core functionality, but few if any show examples of how it works in the context of large enterprise scale problems.</p><p><a href="https://www.tpc.org/tpcds/">TPC-DS</a>, is a useful large scale dataset that generally represents a generic business data schema(I’m not here to advocate that TPC-DS, or any dataset be the end all be all benchmark of any platform/or tool, I just think it can be a useful dataset as a starting point to test things at scale). Snowflake <a href="https://docs.snowflake.com/en/user-guide/sample-data-tpcds.html">makes available TPC-DS</a> in every Snowflake account as a data share, in both a 10 TB and a 100 TB edition(by the way, because it’s exposed as a data share you as the user do not pay any of the costs for storage. Only for any potential compute you use to query it). The 100 TB edition has over 560 billion rows in the fact tables. The 10 TB edition, 56 billion.</p><p>We can use Snowpark Python to build a relatively simple ML solution to a common business problem a hypothetical business like TPC has which is “I want to be able to predict the life-time value of my customers across all sales channels”. We will use the <a href="https://docs.snowflake.com/en/developer-guide/snowpark/python/working-with-dataframes.html">Snowpark Python Dataframe API</a> to do the data prep/feature engineering, <a href="https://docs.snowflake.com/en/developer-guide/snowpark/python/python-snowpark-training-ml.html">stored procedures and Snowpark Optimized Warehouses for training</a>, and <a href="https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-batch.html">batch UDF’s</a> for inference all without the data ever needing to leave Snowflake by utilizing Snowflake’s compute resources and ability to scale.</p><p>Let’s start with our data prep/feature engineering code. Fairly simply, we will aggregate sales by customer across all channels . We will then join that to our customer dimension tables to get potential features of interest.</p><pre>store_sales_agged = store_sales.group_by(&#39;ss_customer_sk&#39;).agg(F.sum(&#39;ss_sales_price&#39;).as_(&#39;total_sales&#39;))<br>web_sales_agged = web_sales.group_by(&#39;ws_bill_customer_sk&#39;).agg(F.sum(&#39;ws_sales_price&#39;).as_(&#39;total_sales&#39;))<br>catalog_sales_agged = catalog_sales.group_by(&#39;cs_bill_customer_sk&#39;).agg(F.sum(&#39;cs_sales_price&#39;).as_(&#39;total_sales&#39;))<br>store_sales_agged = store_sales_agged.rename(&#39;ss_customer_sk&#39;, &#39;customer_sk&#39;)<br>web_sales_agged = web_sales_agged.rename(&#39;ws_bill_customer_sk&#39;, &#39;customer_sk&#39;)<br>catalog_sales_agged = catalog_sales_agged.rename(&#39;cs_bill_customer_sk&#39;, &#39;customer_sk&#39;)<br>total_sales = store_sales_agged.union_all(web_sales_agged)<br>total_sales = total_sales.union_all(catalog_sales_agged)<br>total_sales = total_sales.group_by(&#39;customer_sk&#39;).agg(F.sum(&#39;total_sales&#39;).as_(&#39;total_sales&#39;))<br>customer = customer.select(&#39;c_customer_sk&#39;,&#39;c_current_hdemo_sk&#39;, &#39;c_current_addr_sk&#39;, &#39;c_customer_id&#39;, &#39;c_birth_year&#39;)<br>customer = customer.join(address.select(&#39;ca_address_sk&#39;, &#39;ca_zip&#39;), customer[&#39;c_current_addr_sk&#39;] == address[&#39;ca_address_sk&#39;] )<br>customer = customer.join(demo.select(&#39;cd_demo_sk&#39;, &#39;cd_gender&#39;, &#39;cd_marital_status&#39;, &#39;cd_credit_rating&#39;, &#39;cd_education_status&#39;, &#39;cd_dep_count&#39;),<br>                                customer[&#39;c_current_hdemo_sk&#39;] == demo[&#39;cd_demo_sk&#39;] )<br>customer = customer.rename(&#39;c_customer_sk&#39;, &#39;customer_sk&#39;)<br>final_df = total_sales.join(customer, on=&#39;customer_sk&#39;)<br>session.use_database(&#39;tpcds_xgboost&#39;)<br>session.use_schema(&#39;demo&#39;)<br>final_df.write.mode(&#39;overwrite&#39;).save_as_table(&#39;feature_store&#39;)</pre><p>We save this to a feature store table for reuse later in experimentation or production settings(more on how many customers think of Snowflake as an offline feature store another time).</p><p>Now we’re ready to train our model using a stored procedure. Snowflake simply makes <a href="https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-packages.html#using-third-party-packages-from-anaconda">available all the popular Python ML frameworks to you to utilize for ML training via our partnership with Anaconda</a>. No need to learn a new library or syntax.</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder, MinMaxScaler<br>from sklearn.metrics import mean_squared_error<br>from sklearn.compose import ColumnTransformer<br>from xgboost import XGBRegressor<br>import joblib<br>import os<br><br>def train_model(session: snowflake.snowpark.Session) -&gt; float:<br>    snowdf = session.table(&quot;feature_store&quot;)<br>    snowdf = snowdf.drop([&#39;CUSTOMER_SK&#39;, &#39;C_CURRENT_HDEMO_SK&#39;, &#39;C_CURRENT_ADDR_SK&#39;, &#39;C_CUSTOMER_ID&#39;, &#39;CA_ADDRESS_SK&#39;, &#39;CD_DEMO_SK&#39;])<br>    snowdf_train, snowdf_test = snowdf.random_split([0.8, 0.2], seed=82) <br><br>    # save the train and test sets as time stamped tables in Snowflake <br>    snowdf_train.write.mode(&quot;overwrite&quot;).save_as_table(&quot;tpcds_xgboost.demo.tpc_TRAIN&quot;)<br>    snowdf_test.write.mode(&quot;overwrite&quot;).save_as_table(&quot;tpcds_xgboost.demo.tpc_TEST&quot;)<br>    train_x = snowdf_train.drop(&quot;TOTAL_SALES&quot;).to_pandas() # drop labels for training set<br>    train_y = snowdf_train.select(&quot;TOTAL_SALES&quot;).to_pandas()<br>    test_x = snowdf_test.drop(&quot;TOTAL_SALES&quot;).to_pandas()<br>    test_y = snowdf_test.select(&quot;TOTAL_SALES&quot;).to_pandas()<br>    cat_cols = [&#39;CA_ZIP&#39;, &#39;CD_GENDER&#39;, &#39;CD_MARITAL_STATUS&#39;, &#39;CD_CREDIT_RATING&#39;, &#39;CD_EDUCATION_STATUS&#39;]<br>    num_cols = [&#39;C_BIRTH_YEAR&#39;, &#39;CD_DEP_COUNT&#39;]<br><br>    num_pipeline = Pipeline([<br>            (&#39;imputer&#39;, SimpleImputer(strategy=&quot;median&quot;)),<br>            (&#39;std_scaler&#39;, StandardScaler()),<br>        ])<br><br>    preprocessor = ColumnTransformer(<br>    transformers=[(&#39;num&#39;, num_pipeline, num_cols),<br>                  (&#39;encoder&#39;, OneHotEncoder(handle_unknown=&quot;ignore&quot;), cat_cols) ])<br><br>    pipe = Pipeline([(&#39;preprocessor&#39;, preprocessor), <br>                        (&#39;xgboost&#39;, XGBRegressor())])<br>    pipe.fit(train_x, train_y)<br><br>    test_preds = pipe.predict(test_x)<br>    rmse = mean_squared_error(test_y, test_preds)<br>    model_file = os.path.join(&#39;/tmp&#39;, &#39;model.joblib&#39;)<br>    joblib.dump(pipe, model_file)<br>    session.file.put(model_file, &quot;@ml_models&quot;,overwrite=True)<br>    return rmse</pre><p>In this case, we are using sklearn for transformations and pipeline specification and XGBoost as our regressor. This function can now be registered and invoked via the Python API:</p><pre>train_model_sp = F.sproc(train_model, session=session, replace=True)<br># Switch to Snowpark Optimized Warehouse for training and to run the stored proc<br>session.use_warehouse(&#39;snowpark_opt_wh&#39;)<br>train_model_sp(session=session)</pre><p>Now we’re ready to deploy this model to a UDF wherein it can be used for batch inference jobs.</p><pre>import sys<br>import pandas as pd<br>import cachetools<br>import joblib<br>from snowflake.snowpark import types as T<br><br>session.add_import(&quot;@ml_models/model.joblib&quot;)  <br><br>features = [ &#39;C_BIRTH_YEAR&#39;, &#39;CA_ZIP&#39;, &#39;CD_GENDER&#39;, &#39;CD_MARITAL_STATUS&#39;, &#39;CD_CREDIT_RATING&#39;, &#39;CD_EDUCATION_STATUS&#39;, &#39;CD_DEP_COUNT&#39;]<br><br>@cachetools.cached(cache={})<br>def read_file(filename):<br>       import_dir = sys._xoptions.get(&quot;snowflake_import_directory&quot;)<br>       if import_dir:<br>              with open(os.path.join(import_dir, filename), &#39;rb&#39;) as file:<br>                     m = joblib.load(file)<br>                     return m<br><br>@F.pandas_udf(session=session, max_batch_size=10000, is_permanent=True, <br>              stage_location=&#39;@ml_models&#39;, name=&quot;clv_xgboost_udf&quot;)<br>def predict(df:  T.PandasDataFrame[int, str, str, str, str, str, int]) -&gt; T.PandasSeries[float]:<br>       m = read_file(&#39;model.joblib&#39;)       <br>       df.columns = features<br>       return m.predict(df)</pre><p>Invoking the model is quite simple and can be done in either Python or SQL.</p><pre>inference_df = session.table(&#39;feature_store&#39;)<br>inference_df = inference_df.drop([&#39;CUSTOMER_SK&#39;, &#39;C_CURRENT_HDEMO_SK&#39;, &#39;C_CURRENT_ADDR_SK&#39;, &#39;C_CUSTOMER_ID&#39;, &#39;CA_ADDRESS_SK&#39;, &#39;CD_DEMO_SK&#39;])<br>inputs = inference_df.drop(&quot;TOTAL_SALES&quot;)<br>snowdf_results = inference_df.select(*inputs,<br>                    predict(*inputs).alias(&#39;PREDICTION&#39;), <br>                    (F.col(&#39;TOTAL_SALES&#39;)).alias(&#39;ACTUAL_SALES&#39;)<br>                    )<br>snowdf_results.write.mode(&#39;overwrite&#39;).save_as_table(&#39;predictions&#39;)</pre><p>The SQL equivalent of this, that one could use, and the above Python gets translated to is the following:</p><pre>SELECT &quot;C_BIRTH_YEAR&quot;, <br>        &quot;CA_ZIP&quot;, <br>        &quot;CD_GENDER&quot;, <br>        &quot;CD_MARITAL_STATUS&quot;, <br>        &quot;CD_CREDIT_RATING&quot;,<br>        &quot;CD_EDUCATION_STATUS&quot;, <br>        &quot;CD_DEP_COUNT&quot;, <br> clv_xgboost_udf(&quot;C_BIRTH_YEAR&quot;, &quot;CA_ZIP&quot;, &quot;CD_GENDER&quot;, &quot;CD_MARITAL_STATUS&quot;, &quot;CD_CREDIT_RATING&quot;, &quot;CD_EDUCATION_STATUS&quot;, &quot;CD_DEP_COUNT&quot;) AS &quot;PREDICTION&quot;, <br>&quot;TOTAL_SALES&quot; AS &quot;ACTUAL_SALES&quot; <br>FROM tpcds_xgboost.demo.feature_store</pre><p>Now talking about performance, the entire inference pipeline(feature engineering+inference code above) on the 100 TB TPC-DS dataset can run in about 5.6 minutes on a 3XL warehouse. That’s ~$17 on Snowflake enterprise pricing. Plus, it’s all being done with no overhead, no VM’s to maintain, no cloud infrastructure to provision, no need to worry about autoscaling, patching, security group configuration, IAM policy configuration, and more. It’s all being done in secured managed environment for you.</p><p>As I tell all of my customers I work with, please do not take my word for it. <a href="https://github.com/Snowflake-Labs/snowpark-python-demos/tree/main/tpcds-customer-lifetime-value">Try it yourself, all of the code is available for you here</a>. Even better than TPC-DS, take it for a test drive with some of your organizations data and pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c329c30c2feb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/ml-on-snowflake-at-scale-with-snowpark-python-and-xgboost-c329c30c2feb">ML on Snowflake at scale with Snowpark Python and XGBoost</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>