<?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[Scaling ML workloads with Google Cloud - Medium]]></title>
        <description><![CDATA[Content discussing different aspects of scaling ML workloads, guidance for addressing common issues, and code demonstrations for deploying with Google Cloud Platform - Medium]]></description>
        <link>https://medium.com/gcp-contributions?source=rss----53eba2bd3dcb---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Scaling ML workloads with Google Cloud - Medium</title>
            <link>https://medium.com/gcp-contributions?source=rss----53eba2bd3dcb---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:24:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/gcp-contributions" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build Next-Gen AI: A Deep Dive into Google Cloud’s Agent Development Kit (ADK)]]></title>
            <link>https://medium.com/gcp-contributions/build-next-gen-ai-a-deep-dive-into-google-clouds-agent-development-kit-adk-598593900176?source=rss----53eba2bd3dcb---4</link>
            <guid isPermaLink="false">https://medium.com/p/598593900176</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[adk]]></category>
            <category><![CDATA[agent-development-kit]]></category>
            <category><![CDATA[marketing]]></category>
            <dc:creator><![CDATA[Jwortz]]></dc:creator>
            <pubDate>Fri, 09 May 2025 16:53:35 GMT</pubDate>
            <atom:updated>2025-05-09T16:53:35.061Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Authors: </em><a href="https://www.linkedin.com/in/wortz/"><em>Jeremy Wortz</em></a><em>, </em><a href="https://www.linkedin.com/in/jordantotten/"><em>Jordan Totten</em></a></p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXcV5gaGhxNQ&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXcV5gaGhxNQ%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/323ff0388b1fe7718d418032f8a1c813/href">https://medium.com/media/323ff0388b1fe7718d418032f8a1c813/href</a></iframe><p>The world of artificial intelligence is rapidly evolving from single models to complex, multi-agent systems that can reason, act, and collaborate. Here at Google Cloud, we’re excited to empower developers to build these next-generation applications. That’s why we recently announced the <a href="https://google.github.io/adk-docs/"><strong>Agent Development Kit</strong></a><strong> (ADK)</strong> at Google Cloud Next — an opinionated, open-source, first-party toolkit designed to make it easier for you to develop and deploy sophisticated AI agents in a scalable way for enterprises.</p><p>This blog post will walk you through what ADK is, how it works, and demonstrate its power with a practical use case: creating a dynamic marketing campaign.</p><p><strong>What is the Agent Development Kit (ADK)?</strong></p><p>Think of ADK as a comprehensive framework that simplifies the entire lifecycle of agent development: building, interacting, evaluating, and deploying. It’s designed to be flexible, allowing you to use your preferred models (though it’s optimized for Gemini and the Google Cloud ecosystem) and deploy to various environments. ADK is the same framework powering agents within Google products like Agentspace and the Google Customer Engagement Suite (CES).</p><p>Key aspects of ADK include:</p><ul><li><strong>Simplified Development:</strong> Build production-ready agents with intuitive Python code (more languages coming soon).</li><li><strong>Orchestration Layer:</strong> Easily create multi-agent systems where specialized agents can collaborate and delegate tasks.</li><li><strong>Tool Use:</strong> Equip your agents with a rich ecosystem of tools, including pre-built ones like Google Search, custom Python functions, or even other agents.</li><li><strong>Cloud Integration:</strong> ADK integrates seamlessly with Google Cloud, meaning your tools, sessions, and memory can live as first-class citizens on the platform, just like a BigQuery instance or a GCS bucket. This allows you to apply the same security principles you’re used to.</li></ul><p><strong>A Practical Use Case: The Trends and Insights Agent for Marketing</strong></p><p>To showcase ADK’s capabilities, let’s explore a use case we’ve developed, drawing from our experience with internal and customer projects in retail and CPG. We’ll build an agent that helps generate fresh, relevant marketing content by identifying trends and creating campaign briefs.</p><p><strong>Setting Up Your ADK Environment</strong> Getting started is straightforward. <a href="https://github.com/tottenjordan/zghost">Our ADK repository</a> is publicly available on GitHub. The README provides detailed instructions on:</p><ol><li>Cloning the repo.</li><li>Creating a virtual environment (we use Poetry).</li><li>Enabling necessary Google Cloud services.</li><li>Setting up your .env files with your project details and API keys.</li><li>Creating a Google Cloud Storage bucket.</li></ol><p>Once set up, you can run adk web to launch a local development UI, which is incredibly helpful for interacting with and debugging your agents.</p><p><strong>The Multi-Agent System at Work</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tcB_4_HA0MD6fPX-" /></figure><p>Our marketing agent isn’t just one monolithic block; it’s a system of specialized sub-agents working together under a root agent. This includes:</p><ul><li><strong>Marketing Guide Data Generator Agent:</strong> Takes an initial campaign brief (e.g., a PDF outlining target audience, product, objectives) and structures this information.</li><li><strong>Web Researcher Agent:</strong> Conducts Google searches and YouTube research to find relevant content.</li><li><strong>Trends Assistant Agent:</strong> Identifies broader consumer trends, potentially using the YouTube API to find popular videos in specific regions.</li><li><strong>Ad Content Creator Agent:</strong> Generates ad copy, and can even create images or videos based on the gathered insights.</li><li><strong>Research Generator Agent:</strong> Creates a PDF summary of all of the research generated by other agents.</li></ul><p><strong>Walkthrough: Generating Short form Ad Copy Ideas in Less than 5 Minutes ⏰</strong></p><ol><li><strong>Input Campaign Idea Document:</strong> We start by providing a <a href="https://github.com/tottenjordan/zghost/blob/main/trends_and_insights_agent/marketing_guide_Pixel_9.pdf">campaign guide</a> to the root agent (but users can start without one). For our demo, we imagined marketing the Google Pixel phone to Gen Z individuals in Atlanta and Chicago, highlighting features like <a href="https://support.google.com/phoneapp/answer/9118387?hl=en">Pixel Call Assist</a> and <a href="https://pixel.withgoogle.com/Pixel_Fold/use-magic-eraser?hl=en&amp;country=US">Magic Eraser</a>, with an objective to increase brand awareness.</li><li><strong>Unstructured Inputs to Structured Data:</strong> The root agent transfers this task to the Marketing Guide Data Generator Agent. This agent reads the PDF, extracts key information (brand, target audience, selling points, etc.), and structures it into a defined Python data class, which we define under this agents <a href="https://github.com/tottenjordan/zghost/blob/main/trends_and_insights_agent/common_agents/marketing_guide_data_generator/tools.py">tools</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*xgNnyyBm2pwBRLxC" /></figure><p>This structured data becomes a session state variable that other agents can access and build upon throughout the session:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*2yIP4F4cUdL93Vz1" /></figure><p>3. <strong>Broad Research 📖 &amp; Insights 👁️:</strong> Next, we ask the agent to research the Pixel phone to find insights related to the product and audience. This task is picked up by the Web Researcher Agent.</p><ul><li>It makes asynchronous calls to Google Search and YouTube API (e.g., querying “Google Pixel 9 review” or “Gen Z smartphone preferences”).</li><li>Using Gemini models (like Gemini 2.0 Flash in our demo), it analyzes the content of these search results and videos. For YouTube videos, it can identify key selling points and determine if the content is geared towards the Gen Z audience. This isn’t just transcript analysis; Gemini can process the video content itself.</li><li>The gathered insights (titles, descriptions, URLs, key entities, relationships) are added to the session state.</li><li><a href="https://github.com/tottenjordan/zghost/blob/main/trends_and_insights_agent/agent.py#L41"><strong>Callbacks</strong></a> are a powerful ADK feature <a href="https://github.com/tottenjordan/zghost/blob/main/trends_and_insights_agent/utils.py#L35">demonstrated here</a>. After an agent completes a task (like the web research), a callback can update the session state, ensuring all insights are captured. <a href="https://google.github.io/adk-docs/callbacks/">Callbacks</a> can also implement safety guardrails or other logic before or after an LLM call.</li></ul><p>4. <strong>Finding 🔥 Hot Trends 🔥:</strong> We then prompt the agent to find current hot trends. The Trends and Insights Agent takes over.</p><ul><li>It can use tools like the YouTube API to find trending videos in a specified region (e.g., the US), and display them to the user (see the <a href="https://github.com/tottenjordan/zghost/blob/main/trends_and_insights_agent/common_agents/trend_assistant/prompts.py#L15">prompt</a>)</li><li>The user can decide which video(s) to analyze, including how much of the video to watch in the prompt. For example, <a href="https://www.youtube.com/watch?v=tabhZgEhdS0">this Minecraft video</a> was trending, but it was almost 42 minutes long. To save time, we asked the agent to watch just the first 7 minutes of the video.</li><li>Leveraging Gemini’s multimodal capabilities, the agent can “watch” and understand these public YouTube videos frame-by-frame. It then captures things like a short description, the key entities involved, their relationship with each other, audience profiles likely interested in the overall theme, and initial suggestions how to relate it to the target product</li></ul><p><strong>5. Connecting Trends 📈 to the Product &amp; Generating Ad Content:</strong> Now, the magic happens. The Ad Content Creator Agent takes the product insights (about the Pixel) and the identified trends (like Minecraft’s popularity with Gen Z) to generate creative ad copy.</p><ul><li>The goal is to find the resonating intersection of product, audience, brief, and broad cultural insights.</li><li>The agent might generate initial ad copy. We can then iterate with it. For instance, we saw it generate surreal, meme-inspired ad copy and even an image for “Chi Town” (Chicago) featuring the Pixel 9.</li></ul><figure><img alt="pretty surreal!" src="https://cdn-images-1.medium.com/max/1024/0*NkPK0Et-GAXORrPH" /></figure><ul><li>ADK supports <strong>tool use</strong> for these creative tasks. In the demo, the agent used Google’s VEO model to generate a short video based on an image and a prompt (e.g., “Minecraft deep dish pizzas for Chicago”).</li><li>The Agent built some initial copy that looked like this:</li></ul><blockquote><strong>Chicago, IL Ad Concept (Surreal Meme Boost):</strong></blockquote><blockquote><strong>Ad Copy:</strong> “Chicago, is this real life? 🤔 Build impossible structures with Minecraft and the Pixel 9’s mind-blowing camera. Giant floating pizza slices GUARANTEED. Glitch aesthetics encouraged. #Pixel9 #Chicago #SurrealMemes #Minecraft #GlitchArt”</blockquote><blockquote><strong>Video Prompt:</strong> “A whimsical video showing a miniature Chicago skyline made of Minecraft blocks with impossible, Escher-esque architecture. Giant, pixelated deep-dish pizza slices float in the sky as a Pixel 9 records the scene with a glitch camera effect. The camera pans across the landscape.”</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5irXL04XjLU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2F5irXL04XjLU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5irXL04XjLU%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/04b44cfe728ea1fad6111a3ea6805745/href">https://medium.com/media/04b44cfe728ea1fad6111a3ea6805745/href</a></iframe><ul><li>This initial output was great, but we found it did not did not have a focus on the target product. Below is the result of refining the video:</li></ul><blockquote>User” How do we incorporate the target product (Pixel 9)?”</blockquote><blockquote><strong>Ad Copy:</strong> “Chi-Town, build the unreal. 🍕 Glitch your world! Use the Pixel 9 to create Minecraft builds with impossible designs. The city will turn into one giant fun house.”</blockquote><blockquote><strong>Visual Concept (Video Prompt):</strong> A short video ad for the Chicago, IL Ad Concept is required. Make sure the ad highlights these features. The video also displays, Pixel 9 showing the phone’s capabilities to produce unique and impossible creations, the video displays Pixel 9 itself highlighting camera from the Pixel 9 phone itself. Video is in first-person and we never see the user.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCng4-Tjn_io%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCng4-Tjn_io&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCng4-Tjn_io%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/45aa6f9c4e4fcceb5564fdfb21944e02/href">https://medium.com/media/45aa6f9c4e4fcceb5564fdfb21944e02/href</a></iframe><ul><li><strong>Human-in-the-loop</strong> is key. If the initial ad content doesn’t quite hit the mark (e.g., not enough product presence), we can provide feedback. The agent, remembering the session context (like the target product being Pixel 9), can then revise the content. We saw an example where the agent incorporated the “Magic Eraser” Pixel feature into a newly generated video.</li></ul><blockquote><strong>Chicago, IL Ad Concept (Surreal Meme Boost &amp; Explicit Pixel 9 Feature):</strong></blockquote><blockquote><strong>Ad Copy:</strong> “Chi-Town, remix reality! 🍕 Glitch the skyline with your own Minecraft madness. Use the Pixel 9’s ultra-wide lens and magic eraser to remove the impossible in designs of iconic landmarks to create iconic landscapes. Share your creation!”</blockquote><blockquote><strong>Visual Concept (Video Prompt):</strong> “A first-person perspective video ad. The viewer is seemingly holding the Pixel 9. The phone displays a Minecraft build interface creating Chicago landmarks in the sky. Highlighting the surreal, unique creations that are highlighted on the phone’s front interface. One quick zoom of the ultra-wide lense creating large scale designs and images of the location, using the ‘magic eraser’ that removes key parts to highlight the unique surreal meme aspects.”</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4YaEpO6VuuA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4YaEpO6VuuA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4YaEpO6VuuA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d4d5ae819c54a2c1de7fdef10db05d8/href">https://medium.com/media/5d4d5ae819c54a2c1de7fdef10db05d8/href</a></iframe><p><strong>6. Maintaining Session State (Memory):</strong> Throughout this entire process, ADK maintains session state. This “knowledge graph” of context allows agents to understand the ongoing conversation and build upon previous interactions. Out of the box, ADK uses the <a href="https://google.github.io/adk-docs/sessions/memory/">in-memory service</a> by default, but it can also be <a href="https://google.github.io/adk-docs/sessions/memory/">backed by a long-term RAG-Like</a> MemoryService.</p><p><strong>7. Generating a Research Packet:</strong> Once we’re satisfied with the insights and creative concepts, we can ask the agent to generate a research report. This bundles the initial brief, all the gathered trends and insights, and the generated ad concepts into a shareable PDF.</p><p><strong>Deploying Your ADK Agents</strong></p><p>Building locally with adk web is great for development and testing. But ADK is built for production. You have several deployment options:</p><ul><li><strong>Agent Engine:</strong> This is a fully managed <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview">Google Cloud service</a> that simplifies deploying, managing, and scaling your AI agents. It abstracts away infrastructure concerns. We provide deployment scripts and convenience classes to wrap your ADK agent for Agent Engine.</li><li><strong>Agent Space:</strong> Our new single pane of glass to<a href="https://cloud.google.com/products/agentspace?e=48754805"> house all agents across your organization</a>.</li><li><strong>Cloud Run:</strong> For a simple and direct way to deploy your agent and expose it via an API, you can deploy<a href="https://google.github.io/adk-docs/deploy/cloud-run/"> directly to Cloud Run</a>. The ADK includes commands like deploy cloud run to facilitate this. Docker image builds are handled, often using Poetry for managing Python dependencies.</li></ul><p><strong>Testing and Evaluation</strong></p><p>ADK also supports robust testing:</p><ul><li><strong>Traditional Unit and Integration Testing:</strong> For <a href="https://github.com/tottenjordan/zghost/blob/main/tests/gcs.py">GCS</a> and <a href="https://github.com/tottenjordan/zghost/blob/main/tests/yt_web_tools.py">other cloud tools</a>.</li><li><strong>Agent Eval:</strong> This is a newer concept. You can save <a href="https://github.com/tottenjordan/zghost/blob/main/tests/capability.test.json">interactions</a> with your agent (input and output) and then <a href="https://github.com/tottenjordan/zghost/blob/main/tests/simple_agent_eval.py">run tests against it</a>. The <a href="https://google.github.io/adk-docs/evaluate/">evaluation</a> can check criteria like ROUGE scores for text similarity or verify if specific tools were called as expected.</li></ul><p><strong>Future Directions &amp; Getting Involved</strong></p><p>We’re continuously working to enhance ADK. Some ideas include integrating Google Search trends directly from<a href="https://support.google.com/trends/answer/12764470?hl=en"> BigQuery public datasets</a> and further exploring multimodal interactions, perhaps leveraging features from<a href="https://gemini.google/overview/gemini-live/?hl=en"> Project Astra and Gemini Live</a> for real-time voice conversations.</p><p>The <a href="https://google.github.io/adk-docs/">Agent Development Kit</a> is an open-source project, and we’re excited for the community to get involved. We’ve built this based on our experiences and the challenges we’ve seen developers face. Our goal is to provide you with well-documented, working patterns and examples that you can adapt and build upon.</p><p><a href="https://github.com/google/A2A/">A2A</a> is also another exciting example of Google’s effort to have Agent’s interact with each other with a standard protocol. This addresses a question we often get when asked “how do I scale from 1–2 agents to hundreds”. Just this week, <a href="https://www.microsoft.com/en-us/microsoft-cloud/blog/2025/05/07/empowering-multi-agent-apps-with-the-open-agent2agent-a2a-protocol/">Microsoft announced support for A2A as well</a>.</p><p><strong>Ready to build the next generation of AI agents?</strong></p><ul><li><strong>Explore the ADK GitHub repository:</strong> <a href="https://github.com/google/adk-python">https://github.com/google/adk-python</a> (You’ll find the sample agent discussed here and others!)</li><li><strong>Check out the documentation:</strong> <a href="https://google.github.io/adk-docs/">https://google.github.io/adk-docs/</a></li></ul><p>Fork the <a href="https://github.com/tottenjordan/zghost">repo</a>, try it out, and let us know your feedback. We’re eager to see what you build with ADK!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=598593900176" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gcp-contributions/build-next-gen-ai-a-deep-dive-into-google-clouds-agent-development-kit-adk-598593900176">Build Next-Gen AI: A Deep Dive into Google Cloud’s Agent Development Kit (ADK)</a> was originally published in <a href="https://medium.com/gcp-contributions">Scaling ML workloads with Google Cloud</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One way to think about Reinforcement Learning for Recommender Systems]]></title>
            <link>https://medium.com/gcp-contributions/one-way-to-think-about-reinforcement-learning-for-recommender-systems-39c742d5f661?source=rss----53eba2bd3dcb---4</link>
            <guid isPermaLink="false">https://medium.com/p/39c742d5f661</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Jordan Totten]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 12:39:11 GMT</pubDate>
            <atom:updated>2024-06-21T22:02:30.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*icgOcSfWXE0nzF_h" /><figcaption>Hansel realizing the <a href="https://www.youtube.com/watch?v=L_o_O7v1ews">files are in the computer</a></figcaption></figure><p>Applying reinforcement learning- (RL) based techniques to recommender systems (RecSys) has gained increased attention over the years. And while industrial R&amp;D teams have demonstrated that RL can play a significant role in RecSys (see appendix), problem formulation and code implementation can still be a challenge.</p><p>This article will introduce a framework for understanding how to apply RL to RecSys. To do this, we’ll highlight a few foundational RL concepts (just the ones we need), clarify their implications to RecSys, and illustrate how they can be applied to supervised learning (SL) methods we may already know. Our goal is to understand SL-based RecSys modeling in RL terms. This will prepare us for subsequent posts in which we dive deeper into applying RL to RecSys.</p><blockquote>We won’t review code here, but the interested reader can check out <a href="https://github.com/tottenjordan/tf_vertex_agents/tree/main">tf_vertex_agents</a>, where I’m creating e2e code examples for implementing RL and bandit algorithms with <a href="https://github.com/tensorflow/agents/tree/master">TF-Agents</a> and <a href="https://cloud.google.com/vertex-ai/docs/start/introduction-unified-platform">Vertex AI</a></blockquote><h3>RL foundations for RecSys</h3><p>In the general RL framework, an agent learns to perform actions by interacting with an environment, where the goal is to find the best sequence of actions that lead to an optimal objective (e.g., max reward):</p><ul><li>Environment starts with an initial state: <strong><em>s(t)</em></strong></li><li>Agent takes action <strong><em>a(t)</em></strong></li><li>Environment gives reward: <strong><em>r(t+1)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*Bs0FIhxtE7YnfWGB" /><figcaption><em>Figure 1: Simple illustration of RL framework in which an agent learns to perform actions by interacting with an environment.</em></figcaption></figure><p>RL can play a significant role in RecSys because it provides a mechanism for better decision making that can (1) optimize for long-term objectives, (2) adapt quickly to dynamic user preferences, and (3) efficiently explore regions of uncertainty. To make this more clear, let’s review a few foundational RL concepts.</p><h4>Environment simulation</h4><p>In RL, we design agents that learn by interacting with an environment. The environment represents the task or problem to be solved. At every time step, it provides the agent with an observation, the agent chooses an action, the action is applied to the environment, and the environment returns a reward and new observation. Iterating through an environment’s time steps, an agent eventually learns a policy to select the actions which maximize the sum of all rewards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qnvf4X_A_-MsFS-w" /><figcaption><em>Figure 2: Environments are used to model behaviors we expect our agent to encounter. If training an agent to detect abrupt or slowly drifting changes to the reward distribution, we may choose to simulate with some non-stationary environment implementation.</em></figcaption></figure><p>With RecSys, environments are used to simulate the online environment, essentially preparing the agent for its real world task(s). Conceptually, this would be like preparing a robotic agent for the real world by teaching it how to walk in a “3D replica” of the world.</p><p>For use cases with large action spaces, simulating specific individual events can be extremely challenging, but also unnecessary. Instead, we try to generate events with similar frequencies as those observed in real world data. The goal is typically to address broader questions with aggregated statistics (e.g., “how does a policy adapt to an abrupt shift in user behavior vs an incremental drift over time?”). Ultimately, we want to simulate <em>known</em> factors of variation in the environment that are important for decision-making.</p><h4>RL Agents</h4><p>RL agents are the <em>learner</em> entity interacting with environments, and their goal is to learn the optimal sequence of actions that lead to the highest reward. There are three properties of an agent to highlight for our discussion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sKNW0KtsUICCOn6IQ3EeQ.png" /></figure><p>To understand these in terms of RecSys, let’s consider a policy that produces a ranking response (i.e., slate) of items to display to users. And let’s also assume we have a list of brand new items just recently added to our catalog. For a given user, the value function predicts scores for individual items. The policy fills the slate in rank order according to the predicted values, except with epsilon (ε)<em> </em>probability the 3rd item in the slate is replaced with a random item from our list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*imh5X6GmdUYb0-9x" /><figcaption><em>Figure 3: A general workflow for an </em><a href="https://paperswithcode.com/method/epsilon-greedy-exploration"><em>epsilon-greedy</em></a><em> policy and its value function. For a given state (user, context), the policy fills a slate with the top-k action values; in each response, the 3rd position in the slate has ε</em> probability of being replaced with a random item from our list.</figcaption></figure><p>Here, the value function is telling us the predicted value of each action (item) for an environment state (user and context). The policy uses these predicted values and an <a href="https://paperswithcode.com/method/epsilon-greedy-exploration"><em>epsilon-greedy</em></a> algorithm to produce the final ranking response, where the 3rd-highest slate position has an <em>ε</em> probability of being replaced with a random item from our list.</p><p>Over time, as the agent learns from its actions and updates its policy, it learns a policy that knows when to recommend the brand new items.</p><h4>Exploring information to exploit</h4><blockquote>Recommended reading | viewing: Exploration in Recommender Systems by Minmin Chen (<a href="https://dl.acm.org/doi/abs/10.1145/3460231.3474601">paper</a> | <a href="https://www.youtube.com/watch?v=ArolGOFpODY&amp;list=PLS97YNAc6Zh6impPtzJWGtfhtGNzQMxit&amp;index=8">recording</a>)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Gc2odjSzDPEJ_eq" /><figcaption><em>Figure 4: RL and Bandit agents learn from interacting with an unknown or partially unknown environment; bandits are a subset of RL in which the agent’s actions do not influence the next environment state (e.g., no credit to past actions, no planning ahead).</em></figcaption></figure><p>The <strong><em>explore vs exploit tradeoff</em></strong> is faced by all RL and bandit agents, and it describes the tradeoff between exploiting actions known to produce high rewards versus exploring unseen actions to potentially discover better outcomes. Exploration is needed in RL because the agent has an incomplete view of the environment. As an agent explores different actions and observes their outcomes, it learns more about the environment, and in turn becomes closer to determining an optimal policy.</p><p>Balancing this tradeoff is crucial for optimizing long-term objectives in the face of uncertainty. Let’s consider common sources of uncertainty in RecSys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X6tUp5DOLcV0AyQ4" /></figure><p>Training SL-based RecSys models with historical interaction data <em>reinforces</em> patterns learned from past system behavior, creating a feedback loop that encourages two limitations:</p><ol><li><strong>Myopic recommendations:</strong> users are shown the same familiar content likely to lead to an immediate response (instead of content with longer-term user value)</li><li><strong>System bias:</strong> we only observe feedback on items previously recommended</li></ol><p>Exploration is a key mechanism for escaping this feedback loop and optimizing for long-term objectives. To do this efficiently, we consider three kinds of exploration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ctmhng-a7nFcSfGt" /></figure><blockquote>Online exploration is especially critical for implementing an efficient exploration strategy because it uses real time feedback to self-correct errors made during user and system exploration. We’ll revisit this in subsequent sections.</blockquote><p>Exploration implies taking risks to acquire new information about the environment. As these risks translate to real cost in our RecSys, understanding the cost and value of this information can help us guide RL agents to explore efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dx0lEDTFNB_frG_N" /><figcaption><em>Figure 5: exploration in RL-based RecSys</em></figcaption></figure><p>Recall one of our goals with environment simulation is to simulate <em>known</em> factors of variation that are important for decision-making. This is using what we know (or can confidently estimate) to prepare the agent. With exploration, however, we are dealing with what we don’t know. Rather, we are seeking information about <em>unknown</em> factors of variation. And, “important for decision-making” means we want <em>actionable </em>information about these factors. This is the information that leads to better decision-making.</p><p>If we are able to quantify cost, ideally we can arrive at some metric like “actionable info per unit cost”. Such metrics help implement <em>guided exploration</em>, where for example an agent avoids unnecessary risk like over-exploring a specific region of uncertainty.</p><p>All of this suggests exploration is best utilized if it contributes to the agent’s body of information available to exploit. For example, instead of selecting a completely random item from the entire item catalog, an agent could start from a subset of items that we want to know more about. As the agent recommends these items to <strong><em>users with known interests</em></strong>, we learn actionable information that helps us better recommend them to other users in the future.</p><h4>Generalized Policy Iteration</h4><blockquote>For this section, I suggest referencing <a href="http://www.incompleteideas.net/book/ebook/node40.html">chapter 4</a> of Sutton and Barto’s book, <a href="http://www.incompleteideas.net/book/ebook/the-book.html">Reinforcement Learning: an Introduction</a>.</blockquote><p><a href="http://www.incompleteideas.net/book/ebook/node46.html">Generalized Policy Iteration</a> (GPI) refers to a general RL framework that uses value functions to organize and structure the search for better policies. For this section, I want to use this broad meaning of the term so we can later think about SL- and RL-based systems in like terms. Below is my attempt at a concise explanation of the salient points.</p><p>Specifically, GPI describes two interacting processes, (i) <a href="http://www.incompleteideas.net/book/ebook/node41.html">policy evaluation</a> and (ii) <a href="http://www.incompleteideas.net/book/ebook/node42.html">policy improvement</a>, that eventually converge on the optimal policy and value functions as an agent interacts with an environment. For our purposes, here is what we need to know about each of these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rt1CN3qZ3vKqjSaM" /></figure><p>In their book, Sutton and Barto <a href="http://www.incompleteideas.net/book/ebook/node46.html">suggest</a> thinking of the processes in GPI as two separate, but non-orthogonal constraints or goals:</p><ol><li><strong>Make the value function consistent with the current policy and environment</strong></li><li><strong>Make the policy greedy with respect to the current value function</strong></li></ol><p>Each process pushes either the value function or policy toward one of the two goals — and consequently away from the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*WzeQPoCq-QaxHXT_" /><figcaption><em>Figure 6: The competing processes of GPI interact to eventually converge on a single joint solution: the optimal value function and an optimal policy</em></figcaption></figure><p>Here, the word “current” can be confusing (e.g., <em>current</em> value function vs <em>current</em> policy). If so, it may help to write the following by hand (e.g., something similar to figure 7):</p><p>Suppose we start with a policy, π.</p><p>We <strong>evaluate</strong> this policy by calculating its value function, Vπ .</p><p>A <strong>policy improvement</strong> occurs when we use Vπ to find a better policy, π’, by selecting actions leading to the highest reward for every state encountered thus far. This improved policy is exactly the same as the original policy, except for every state it will choose actions that result in either the same or greater rewards.</p><p>But this makes the current value function, Vπ, incorrect for the changed (current) policy, π’, as Vπ no longer applies.</p><p>So, we then compute a <strong>policy evaluation</strong>, Vπ’, making the value function consistent with the current policy, π’.</p><p>But this, in turn, causes the current policy, π’, to no longer be greedy with respect to the current value function, Vπ’ (remember, π’ is greedy with respect to Vπ). So we <strong>improve</strong> again, resulting in a new (current) policy, π’’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eX8JQ4eDdA11G3xA" /><figcaption><em>Figure 7: GPI results in a sequence of monotonically improving policies and value functions</em></figcaption></figure><p>This cycle repeats until a policy is found that is greedy with respect to its own value function, which is the case when these processes converge on a single, joint solution: the optimal value function, <em>V*</em>, and an optimal policy, <em>π*</em>.</p><h3>Traditional RecSys as GPI</h3><p>Now, let’s see how a traditional RecSys looks in terms of GPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*6wXBGeyz0dcMZwFs" /><figcaption><em>Figure 8: traditional RecSys in which regression and ranking models are trained offline with supervised learning, and training examples are labeled with user feedback</em></figcaption></figure><p>Consider a traditional SL-based RecSys which serves recommendations using regression and ranking models. For simplicity, let’s assume the user interests are fixed (i.e., stationary). The interaction between users, items, and our RecSys includes:</p><ol><li>For a given user context, a trained regression model predicts scores for <strong><em>&lt;user, item&gt;</em></strong> pairs; a ranking model uses the predicted scores to produce a list of top-k items</li><li>User provides feedback (like vs dislike) for each of the top-k items</li><li>The user context, top-k items, and feedback are logged as labeled examples for future model training</li><li>The RecSys retrains the regression and ranking models with the labeled examples</li><li>User treatment changes when the newly trained models are deployed to production</li></ol><p>Now let’s consider how user feedback manifests into items presented to users:</p><ol><li>On the first day, two items are presented to the user; user gives feedback that they like item1 and dislike item2</li><li>On the second day, a new model is trained with the labeled feedback and pushed to production</li><li>In the newly trained model, the score of item1 increases and the score of item2 decreases, causing item3 to have a larger predicted score than item2</li><li>As a result, item3 replaces item2 in the top-k list presented to the user</li></ol><p>Keeping user interests constant, after enough training iterations we can expect the order of the top-k items to become consistent with user feedback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O77amDWtmt9A8Lf_" /><figcaption><em>Figure 9: GPI components in traditional RecSys</em></figcaption></figure><p>Let’s describe our SL-based RecSys in terms of the GPI components. For simplicity of the illustration, we’ll just consider the ranking model:</p><ul><li><strong>Value function (V<em>π</em>): </strong>the ranking model; it assigns the value to all possible actions for a given state</li><li><strong>Policy (<em>π</em>):</strong> the ranking server, including the value function and business logic (e.g., filtering). Given an environment state (user, context), it determines the actions to take (top-k items to recommend)</li><li><strong>Policy evaluation:</strong> the SL training updates the ranking model’s weights based on the latest feedback. This produces a new model available to deploy. In RL terms, the training updated the value function to be consistent with the current policy, i.e., all the actions and feedback produced from the policy currently deployed</li><li><strong>Policy improvement:</strong> pushing the newly trained ranking model to production is analogous to improving the original policy (previous model deployment). The new policy is greedy with respect to the current value function because it will simply take actions that lead to equal or greater rewards (i.e., it learned from the previous deployments mistakes)</li><li><strong>Exploration:</strong> the process of showing the user item2, adjusting with feedback, and later replacing it with item3, is analogous to exploration. This is what contributes to the <em>policy improvement</em> because it explores the action space</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zg9OahMPx6JnCqu5" /><figcaption><em>Figure 10: GPI components in traditional RecSys</em></figcaption></figure><p>With this view, we can see SL-based models complete a GPI cycle once a model is trained and deployed to production. Also note how exploration is related to this cycle. This cycle is essentially the same “feedback delay” we highlighted earlier; it refers to the expected latency of reflecting a user interaction in the system behavior (i.e., from click to serving a system trained on that click).</p><p>With RL we can address this delay and self-correct with an online learning component. Let’s see what that means.</p><h3>Online learning as GPI</h3><blockquote>Online exploration is especially critical for implementing an efficient exploration strategy because it uses real time feedback to self-correct errors made during user and system exploration</blockquote><p>With online learning, agents incrementally update their policy and value functions as they observe real time streams of user and system feedback.</p><p>For <em>online learning</em> to take place, the agent’s policy needs to be updated. The agent’s policy is updated when it trains (updates) its value function using the logged <strong><em>&lt;context, action, reward&gt;</em> <em>tuples</em> </strong>from recent interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fQ7KtD1wzW94K2eP" /><figcaption><em>Figure 11: Baseline reference architecture for RL-based online learning</em></figcaption></figure><p>In Figure 11, we see a baseline reference architecture for online learning:</p><ul><li><strong>Offline simulation</strong> is used to simulate interactions and any alternative exploration policies or model parameters we wish to experiment</li><li><strong>Online learning</strong> refers to updating the value function, where each iteration can be viewed as standard offline SL</li><li>Once trained, an <strong>updated policy</strong> based on the value function is pushed to the server (typically on the order of <em>minutes</em>)</li><li>Given a state (user, context), the <strong>deployed policy determines the actions</strong> to take</li><li>Interactions and rewards are logged asynchronous with a unique tuple ID to an <strong>event store</strong>. This prevents having to store context and action in memory for the duration of reward feedback delay</li><li>Once the user feedback is logged, the join server creates labeled examples as <strong><em>&lt;context, action, reward&gt;</em> tuples</strong> and stores them for future training</li></ul><p>Each iteration of online learning is like an SL procedure that trains (updates) the policy’s value function to make it more consistent with the current policy and environment (i.e., <strong>policy evaluation</strong>). Then we push an updated policy to the serving application (i.e., <strong>policy improvement</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yWMS2EvIdeX6Lofr" /><figcaption><em>Figure 12: GPI components in RL-based online learning</em></figcaption></figure><p>As the duration of each online learning iteration (i.e., GPI cycle) decreases, we approach fully continuous online learning.</p><p>In a more extreme case, we could simplify the architecture and deploy an online agent that learns (trains) and takes actions (predicts) in the same process (i.e., on the server)…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/0*A-IujLGsH_nliKBZ" /></figure><p>…which is a perfect topic to cover in a future post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5mL2z4M2h4P-mQ69" /><figcaption><em>Figure 13: reference architecture illustrating an agent that trains in the same process (i.e., the same server) where it takes action. In these settings, most implementations trigger event aggregation and model updates every few minutes or hundreds of events, whichever comes first.</em></figcaption></figure><h3>Appendix</h3><h4>White papers</h4><ul><li><a href="https://dl.acm.org/doi/abs/10.1145/3366423.3380130">Off-policy Learning in Two-stage Recommender Systems</a></li><li><a href="https://arxiv.org/abs/2307.15893">Online Matching: A Real-time Bandit System for Large-scale Recommendations</a></li><li><a href="https://arxiv.org/abs/1812.02353">Top-K Off-policy Correction for a REINFORCE Recommender System</a></li><li><a href="https://arxiv.org/abs/1811.07819">Learning actionable representation with goal-conditioned policies</a></li></ul><h4>Code repositories</h4><ul><li><a href="https://github.com/google-research/recsim_ng/tree/master"><em>RecSim NG</em></a><em> — simulation platform for uncertainty modeling in RecSys ecosystems</em></li><li><a href="https://github.com/tensorflow/agents/tree/master"><em>TF-Agents</em></a><em>: — TensorFlow library for RL and contextual bandits</em></li><li><a href="https://github.com/google-research/rlds"><em>RLDS</em></a><em> — Reinforcement Learning Datasets</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39c742d5f661" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gcp-contributions/one-way-to-think-about-reinforcement-learning-for-recommender-systems-39c742d5f661">One way to think about Reinforcement Learning for Recommender Systems</a> was originally published in <a href="https://medium.com/gcp-contributions">Scaling ML workloads with Google Cloud</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling deep learning workloads with PyTorch / XLA and Cloud TPU VM | Google Cloud Blog]]></title>
            <link>https://medium.com/gcp-contributions/scaling-deep-learning-workloads-with-pytorch-xla-and-cloud-tpu-vm-google-cloud-blog-1bc427213601?source=rss----53eba2bd3dcb---4</link>
            <guid isPermaLink="false">https://medium.com/p/1bc427213601</guid>
            <category><![CDATA[distributed-training]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[tpu]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[webdataset]]></category>
            <dc:creator><![CDATA[Jordan Totten]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 12:03:50 GMT</pubDate>
            <atom:updated>2024-05-21T13:14:02.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Many deep learning advancements can be attributed to increases in (1) data size and (2) computational power. Training deep learning models with larger datasets can be extremely beneficial for model training. Not only do they help stabilize model performance during training, but <a href="https://arxiv.org/abs/1712.00409">research</a> shows that for moderate to large-scale models and datasets, model performance converges as a power-law with training data size, meaning we can predict improvements to model accuracy as the dataset grows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SDEoCAxX92mx9AI4sLT_hg.png" /><figcaption><em>Figure 1: Learning curve and dataset size for word language models (</em><a href="https://arxiv.org/abs/1712.00409"><em>source</em></a><em>)</em></figcaption></figure><p>In practice this means as we look to improve model performance with larger datasets, (1) we need access to hardware accelerators, such as GPUs or TPUs, and (2) we need to architect a system that efficiently stores and delivers this data to the accelerators. There are a few reasons why we may choose to stream data from remote storage to our accelerator devices:</p><ul><li><strong>Data size</strong>: data can be too large to fit on a single machine, requiring remote storage and efficient network access</li><li><strong>Streamlined workflows</strong>: transferring data to disk can be time consuming and resource intensive, we want to make fewer copies of the data</li><li><strong>Collaboration</strong>: disaggregating data from accelerator devices means we can more efficiently share accelerator nodes across workloads and teams</li></ul><p>Streaming training data from remote storage to accelerators can alleviate these issues, but it introduces a host of new challenges:</p><ul><li><strong>Network overhead:</strong> Many datasets consist of millions of individual files, randomly accessing these files can introduce network bottlenecks. We need <a href="https://en.wikipedia.org/wiki/Sequential_access">sequential access</a> patterns</li><li><strong>Throughput</strong>: Modern accelerators are fast; the challenge is feeding them fast enough to keep them fully utilized. We need parallel I/O and pipelined access to data</li><li><strong>Randomness vs Sequential</strong>: The optimization algorithms in deep learning jobs benefit from randomness, but <a href="https://en.wikipedia.org/wiki/Random_access">random file access</a> introduces network bottlenecks. Sequential access alleviates network bottlenecks, but can reduce the randomness needed for training optimization. We need to balance these</li></ul><p><strong><em>How do we architect a system that addresses these challenges at scale?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZY8AlSUI3TZcYt4fn_otA.png" /><figcaption><em>Figure 2: Scaling to larger datasets, more devices</em></figcaption></figure><p>In this post, we will cover:</p><ul><li>The challenges associated with scaling deep learning jobs to distributed training settings</li><li>Using the new <a href="https://cloud.google.com/blog/products/compute/introducing-cloud-tpu-vms">Cloud TPU VM</a> interface</li><li>How to stream training data from Google Cloud Storage (GCS) to <a href="https://pytorch.org/xla/release/1.9/index.html">PyTorch / XLA</a> models running on Cloud TPU Pod slices</li></ul><p>You can find accompanying code for this article in this <a href="https://github.com/mlexample/torchxla_tpu">GitHub repository</a>.</p><h3>Model and dataset</h3><p>In this article, we will train a PyTorch / XLA ResNet-50 model on a v3–32 TPU Pod slice where training data is stored in GCS and streamed to the TPU VMs at training time. ResNet-50 is a 50-layer convolutional neural network commonly used for computer vision tasks and machine learning performance benchmarking. To demonstrate an end-to-end example, we will use the <a href="https://www.cs.toronto.edu/~kriz/cifar.html">CIFAR-10 dataset</a>. The original dataset consists of 60,000 32x32 color images divided into 10 classes, each class containing 6,000 images. We have upsampled this dataset, creating a training and test set of 1,280,000 and 50,000 images, respectively. CIFAR is used because it is publicly accessible and well known; however, in the GitHub repository, we provide guidance for adapting this solution to your workloads, as well as larger datasets such as <a href="https://en.wikipedia.org/wiki/ImageNet">ImageNet</a>.</p><h3>Cloud TPU</h3><p><a href="https://cloud.google.com/tpu">TPUs</a>, or Tensor Processing Units, are ML ASICs specifically designed for large-scale model training. As they excel at any task where large matrix multiplications dominate, they can accelerate deep learning jobs and reduce the total cost of training. If you’re new to TPUs, check this <a href="https://cloud.google.com/tpu/docs/beginners-guide">article</a> to understand how they work.</p><p>The v3–32 TPU used in this example consists of 32 TPU v3 cores and 256 GiB of total TPU memory. This TPU Pod slice consists of 4 TPU Boards (a Board has 8 TPU cores). Each TPU Board is connected to a high-performance CPU-based host machine for things like loading and preprocessing data to feed to the TPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVz3qIw2YNaMhiPa89DEEw.png" /><figcaption>Figure 3: Cloud TPU VM architecture, where TPU VMs run on TPU host machines directly attached to each TPU accelerator.</figcaption></figure><p>We will access the TPU through the new <a href="https://cloud.google.com/tpu/docs/users-guide-tpu-vm#set_up_a_gcp_project">Cloud TPU VMs</a>. When we use Cloud TPU VMs, a VM is created for each TPU board in the configuration. Each VM consists of 48 vCPUs and 340 GB of memory, and comes preinstalled with the latest PyTorch / XLA image. Because there is no user VM, we ssh directly into the TPU host to run our model and code. This root access eliminates the need for a network, VPC, or firewall between our code and the TPU VM, which can significantly improve the performance of our input pipeline. For more details on Cloud TPU VMs, see the <a href="https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_vms">System Architecture</a>.</p><h3>PyTorch / XLA</h3><p><a href="https://pytorch.org/xla/release/1.9/index.html">PyTorch / XLA</a> is a Python library that uses the <a href="https://developers.googleblog.com/2017/03/xla-tensorflow-compiled.html">XLA</a> (Accelerated Linear Algebra) deep learning <a href="https://www.tensorflow.org/xla">compiler</a> to connect PyTorch and Cloud TPUs. Check out the <a href="https://github.com/pytorch/xla">GitHub repository</a> for tutorials, best practices, Docker Images, and code for popular models (e.g., ResNet-50 and AlexNet).</p><p>Distributed training typically refers to training workloads which use multiple accelerator devices (e.g. GPU or TPU). In our example, we are executing a data parallel distributed training job with stochastic gradient descent. In data parallel training, our model fits on a single TPU device and we replicate the model across each device in our distributed configuration. When we add more devices, our goal is to reduce overall training time by distributing non-overlapping partitions of the training batch to each device for parallel processing. Because our model is replicated across devices, the models on each device need to communicate to synchronize their weights after each training step. In distributed data parallel jobs, this device communication is typically done either asynchronously or synchronously.</p><p>Cloud TPUs execute synchronous device communication over the dedicated high-speed network connecting the chips. In our model code, we use PyTorch / XLA’s optimizer_step(optimizer) to calculate the gradients and initiate this synchronous update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ysTeHXIrlebcEML8xbuqxA.gif" /><figcaption><em>Figure 4: Synchronous all-reduce on Cloud TPU interconnect. </em>The high-speed interconnect <strong>synchronizes any parameter updates</strong> in a single TPU with thousands of TPUs with very short latency. No need to setup the parameter server nor cluster of GPU nodes by yourself.</figcaption></figure><h3>Input pipeline performance</h3><pre>for step, (data, target) in enumerate(loader):<br>    optimizer.zero_grad() # zero the parameter gradients<br>    output = model(data)<br>    loss = loss_fn(output, target)<br>    loss.backward()<br>    xm.optimizer_step(optimizer) # initiate weight synchronization</pre><p>In this illustration, we see the following steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*OVqf5eT5UNOF_cv0oH1a5Q.png" /><figcaption><em>Figure 5: Common machine learning training loop and hardware configuration</em></figcaption></figure><ul><li>Training data is either stored on local disk or remote storage</li><li>The CPU (1) requests and reads the data, augments it with various transformations, batches it, and feeds it to the model</li><li>Once the model has the transformed, batched training data, (2) the accelerator takes over</li><li>The accelerator (2a) computes the forward pass, (2b) loss, and (2c) backwards pass</li><li>After computing the gradients, (3) the parameter weights are updated (the learning!)</li><li>And we repeat the cycle over again</li></ul><p>While this pattern can be adapted in several ways (e.g., some transformations could be computed on the accelerator), the prevailing theme is that an ideal architecture seeks to maximize utilization of the most expensive component, the accelerator. And because of this, we see most performance bottlenecks occurring in the input pipeline driven by the CPU. To help with this, we are going to use the <a href="https://github.com/webdataset/webdataset">WebDataset</a> library. WebDataset is a PyTorch dataset implementation designed to improve streaming data access for deep learning workloads, especially in remote storage settings. Let’s see how it helps.</p><h3>WebDataset format</h3><h3>(1) Sequential I/O</h3><p>GCS is capable of sustaining high throughput, but there is some network overhead when initiating a connection. If we are accessing millions of individual image files, this is not ideal. Alternatively, we can achieve sequential I/O by requesting a tar file containing our individual image files. Once we request the tar file, we get sequential reads of the individual files within that tar file, which allows for faster object I/O over the network. This reduces the number of network connections to establish with GCS, and thus reduces potential network bottlenecks.</p><h3>(2) Pipelined data access</h3><p>With file-based I/O we randomly access image files, which is good for training optimization, but for each image file there is a client request and storage server response. Our sequential storage achieves higher throughput because with a single client request for a tar file, the data samples in that file flow sequentially to the client. This pattern gives us pipelined access to our individual image files, resulting in higher throughput.</p><h3>(3) Sharding</h3><p>Storing TBs of data in a single sequential file could be difficult to work with and it prevents us from achieving parallel I/O. Sharding the dataset can help us in several ways:</p><ol><li>Aggregate network I/O by opening shards in parallel</li><li>Accelerate data preprocessing by processing shards in parallel</li><li>Randomly access shards, but read sequentially within each shard</li><li>Distribute shards efficiently across worker nodes and devices</li><li>Guarantee equal number of training samples on each device</li></ol><p>Because we can control the number of shards and the number of samples in those shards, we can distribute equal-sized shards and guarantee each device receives the same number of samples in each training epoch. Sharding the tar files helps us balance the tradeoff between random files access and sequential reads. Random access to the shards and in-memory shuffling satisfy enough randomness for the training optimization. The sequential reads from each shard reduce network overhead.</p><h3>Distributing shards across devices and workers</h3><p>As we are essentially creating a PyTorch <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset">IterableDataset</a>, we can use the PyTorch <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader">DataLoader</a> to load data on the devices for each training epoch. Traditional PyTorch Datasets distribute data at the sample-level, but we are going to distribute at the shard-level. We will create two functions to handle this distribution logic and pass them to the `splitter=` and `nodesplitter=` arguments when we create our dataset object. All these functions need to do is take a list of shards and return a subset of those shards.</p><p>We will split shards across workers with:</p><pre>def my_worker_splitter(urls):<br>   &quot;&quot;&quot;<br>   Split urls per worker<br>   Selects a subset of urls based on Torch get_worker_info.<br>   Used as a shard selection function in Dataset.<br>   replaces wds.split_by_worker<br>   &quot;&quot;&quot;<br><br>   urls = [url for url in urls]<br><br>   assert isinstance(urls, list)<br><br>   worker_info = torch.utils.data.get_worker_info()<br>   if worker_info is not None:<br>       wid = worker_info.id<br>       num_workers = worker_info.num_workers<br><br>       return urls[wid::num_workers]<br>   else:<br>       return urls</pre><p>We will split shards across devices with:</p><pre>def my_node_splitter(urls):<br>   &quot;&quot;&quot;<br>   Split urls_ correctly per accelerator node<br>   :param urls:<br>   :return: slice of urls_<br>   &quot;&quot;&quot;<br>   rank=xm.get_ordinal()<br>   num_replicas=xm.xrt_world_size()<br>​<br>   urls_this = urls[rank::num_replicas]<br>  <br>   return urls_this</pre><p>With these two functions we will create a data loader for both train and validation data. Here is the train loader:</p><pre>def make_train_loader(<br>    cifar_img_dim, <br>    shuffle=10000,<br>    batch_size=FLAGS.batch_size<br>):<br>    <br>    num_dataset_instances = xm.xrt_world_size() * FLAGS.num_workers<br>    epoch_size = trainsize // num_dataset_instances<br><br>    image_transform = transforms.Compose(<br>        [<br>            transforms.RandomCrop(cifar_img_dim, padding=4),<br>            transforms.RandomHorizontalFlip(),<br>            transforms.ToTensor(),<br>            normalize,<br>        ]<br>    )<br>    <br>    dataset = (<br>        wds.WebDataset(FLAGS.wds_traindir,<br>                       splitter=my_worker_splitter,<br>                       nodesplitter=my_node_splitter,<br>                       shardshuffle=True, length=epoch_size)<br>        .shuffle(shuffle)<br>        .decode(&quot;pil&quot;)<br>        .to_tuple(&quot;ppm;jpg;jpeg;png&quot;, &quot;cls&quot;)<br>        .map_tuple(image_transform, identity)<br>        .batched(batch_size, partial=True)<br>        )<br><br>    loader = torch.utils.data.DataLoader(dataset, batch_size=None, <br>                                         shuffle=False, drop_last=False, <br>                                         num_workers=FLAGS.num_workers)<br>    return loader</pre><p>Here is an explanation of some of the variables used in these snippets:</p><ul><li>xm.xrt_world_size() is the total number of devices, or TPU cores</li><li>FLAGS.num_workers is the number of subprocesses spawned per TPU core for loading and preprocessing data</li><li>The epoch_size specifies the number of training samples each device should expect for each epoch</li><li>shardshuffle=True means we will shuffle the shards, while .shuffle(10000) shuffles samples inline</li><li>.batched(batch_size, partial=True) explicitly batches data in the Dataset by batch_size and &#39;partial=True&#39; handles partial batches, typically found in the last shard</li><li>Our loader is a standard PyTorch DataLoader. Because our WebDataset Dataset accounts for batching, shuffling, and partial batches, we do not use these arguments in PyTorch’s DataLoader</li></ul><h3>Performance comparison</h3><p>The table in Figure 7 compares the performance between 3 different training configurations for a PyTorch / XLA ResNet-50 model training on the ImageNet dataset. Configuration A provides baseline metrics and represents a model reading from local storage, randomly accessing individual image files. Configuration B uses a similar setup as A, except the training data is sharded into 640 POSIX tar files and the WebDataset library is used to sample and distribute shards to the model replicas on Cloud TPU devices. Configuration C uses the same sampling and distribution logic as B, but sources training data from remote storage in GCS. The metrics represent an average of each configuration over five 90-epoch training jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*XH84EKmy-PcrUDKeWFWkuQ.png" /><figcaption><em>Figure 7: Training performance comparison</em></figcaption></figure><p>Comparing configurations A and B, these results show that simply using a sharded, sequentially readable data format improves pipeline and model throughput (average examples per second) by 11.2%. They also show that we can take advantage of remote storage without negatively impacting model training performance. Comparing configurations A and C, we were able to maintain pipeline and model throughput, training time, and model accuracy.</p><p>To highlight the impacts of sequential and parallel I/O, we held many configuration settings constant. There are still several areas to investigate and improve. In a later post we will show how to use the <a href="https://cloud.google.com/tpu/docs/pytorch-xla-performance-profiling-tpu-vm">Cloud TPU profiler</a> tool to further optimize PyTorch / XLA training jobs.</p><h3>End-to-end example</h3><p>Let’s walk through a full example.</p><p>To follow this example, you can use <a href="https://github.com/mlexample/torchxla_tpu/blob/main/Create_CIFAR_shards.ipynb">this notebook</a> to create a sharded CIFAR dataset.</p><h3>Before you begin</h3><p>In the Cloud Shell, run the following commands to configure <a href="https://cloud.google.com/sdk/gcloud/reference">gcloud</a> to use your GCP project, install components needed for the TPU VM preview, and enable the TPU API. For additional TPU 1VM setup details, see these <a href="https://cloud.google.com/tpu/docs/users-guide-tpu-vm">instructions</a>.</p><pre>gcloud config set account YOUR_EMAIL_ACCOUNT<br>gcloud config set project YOUR_PROJECT_ID<br>gcloud components install alpha <br>gcloud services enable tpu.googleapis.com</pre><h3>Connecting to a Cloud TPU VM</h3><p>The default network comes preconfigured to allow ssh access to all VMs. If you don’t use the default network, or the default network settings were edited, you may need to explicitly enable SSH access by adding a firewall rule:</p><pre>gcloud compute firewall-rules create \<br>    --network=network allow-ssh \<br>    --allow=tcp:22</pre><p>Currently in the TPU VM preview, we recommend disabling <a href="https://cloud.google.com/compute/docs/instances/managing-instance-access">OS login</a> to allow native scp (required for PyTorch / XLA Pods).</p><pre>gcloud compute project-info add-metadata \<br>    --metadata enable-oslogin=FALSE \<br>    --project ${PROJECT_ID}</pre><h3>Creating a TPU 1VM slice</h3><p>We will create our TPU Pod slice in europe-west4-a because this region supports both TPU VMs and v3–32 TPU Pod slices.</p><pre>export REGION=europe-west4<br>export ZONE=europe-west4-a<br>export ACCELERATOR_TYPE=v3-32<br>export TPU_NAME=my-1vm-tpu<br>export RUNTIME_VERSION=v2-alpha</pre><ul><li><strong>ACCELERATOR_TYPE</strong>: find the list of supported accelerator types <a href="https://cloud.google.com/tpu/docs/types-zones#types">here</a></li><li><strong>RUNTIME_VERSION:</strong> for PyTorch / XLA, use v2-alpha for single TPUs and TPU pods. This is a stable version for our public preview release.</li></ul><p>PyTorch / XLA requires all TPU VMs to be able to access the model code and data. Using gcloud, we will include a metadata startup-script which installs the necessary packages and code on each TPU VM.</p><pre>gcloud alpha compute tpus tpu-vm create ${TPU_NAME} --zone ${ZONE} \<br>   --accelerator-type ${ACCELERATOR_TYPE} --version ${RUNTIME_VERSION} \<br>   --metadata startup-script=&#39;#! /bin/bash<br>pip install webdataset==0.1.54<br>pip install google-cloud-storage<br>pip install tensorboardX<br>cd /usr/share/<br>git clone --recursive https://github.com/pytorch/pytorch<br>cd pytorch/<br>git clone --recursive https://github.com/pytorch/xla.git<br>git clone --recursive https://github.com/mlexample/torchxla_tpu.git<br>EOF&#39;</pre><p>This command will create a v3–32 TPU Pod slice and 4 VMs, one dedicated to each TPU board.</p><p>To ssh into a TPU VM, we will use the gcloud ssh command below. By default, this command will connect to the first TPU VM worker (denoted with w-0). To ssh into any other VM associated with the TPU Pod, append `--worker ${WORKER_NUMBER}` in the command, where the WORKER_NUMBER is 0-based. See <a href="https://cloud.google.com/tpu/docs/managing-tpus-tpu-vm">here</a> for more details on managing TPU VMs.</p><pre>gcloud alpha compute tpus tpu-vm ssh ${TPU_NAME} \<br>    --zone ${ZONE} \<br>    --project ${PROJECT_ID}</pre><p>Once in the VM, run the following command to generate the ssh-keys to ssh between VM workers on a pod:</p><pre>gcloud compute config-ssh</pre><h3>PyTorch training</h3><p>Check to make sure the metadata startup script has cloned all the repositories. After running the following command, we should see the torchxla_tpu directory.</p><pre>cd /usr/share/pytorch</pre><p>To train the model, let’s first set up some environment variables:</p><pre>export BUCKET=          # TODO ex: tpu-demo-xxxx<br>export TRAIN_SHARDS=    # TODO ex: &#39;train/cifar-train-{000000..000639}.tar&#39;<br>export VAL_SHARDS=      # TODO ex: &#39;val/cifar-val-{000000..000049}.tar&#39;<br>export WDS_TRAIN_DIR=&quot;pipe:gsutil cat gs://${BUCKET}/${TRAIN_SHARDS}&quot;<br>export WDS_VAL_DIR=&quot;pipe:gsutil cat gs://${BUCKET}/${VAL_SHARDS}&quot;<br>export LOGDIR=&quot;${LOGDIR:-gs://${BUCKET}/log-$(date &#39;+%Y%m%d%H%M%S&#39;)}&quot;</pre><ul><li><strong>BUCKET</strong> : name of GCS bucket storing our sharded dataset. We will also store training logs and model checkpoints here (see <a href="https://cloud.google.com/storage/docs/naming-objects#object-considerations">guidelines</a> on GCS object names and folders)</li><li><strong>{split}_SHARDS</strong>: train/val shards, using brace notation to enumerate the shards</li><li><strong>WDS_{split}_DIR</strong>: uses pipe to run a gsutil command for downloading the train/val shards</li><li><strong>LOGDIR</strong>: location in GCS bucket for storing training logs</li></ul><pre>export TPU_NAME=my-1vm-tpu         # Name of TPU <br>export NUM_EPOCHS=10               # Total number of epochs<br>export BATCH_SIZE=128              # Samples per train batch<br>export TEST_BATCH_SIZE=64          # Samples per test batch<br>export NUM_WORKERS=8               # Workers per TPU VM to prep/load data<br>export TRAIN_SIZE=1280000          # Total number of training samples<br>export TEST_SIZE=50000             # Total number of test samples</pre><p>Optionally, we can pass environment variables for storing model checkpoints and loading from a previous checkpoint file:</p><pre>export SAVE_MODEL=&#39;/tmp/model-chkpt.pt&#39; # local file to upload to GCS<br>export LOAD_CHKPT_FILE=                 # object in GCS bucket <br>export LOAD_CHKPT_DIR=                  # local directory/filename</pre><p>When we choose to save model checkpoints, a checkpoint file will be saved at the end of each epoch if the validation accuracy improves. Each time a checkpoint is created, the PyTorch / XLA xm.save() utility API will save the file locally, overwriting any previous file if it exists. Then, using the Cloud Storage Python SDK, we will upload the file to the specified $LOGDIR, overwriting any previous file if it exists. Our example saves a dictionary of relevant information like this:</p><pre>if FLAGS.save_model != &quot;&quot;:<br> ...<br> if accuracy &gt; best_valid_acc:<br>   xm.save(<br>       {<br>           &quot;epoch&quot;: epoch,<br>           &quot;nepochs&quot;: FLAGS.num_epochs,<br>           &quot;model_state_dict&quot;: model.state_dict(),<br>           &quot;best_valid_acc&quot;: best_valid_acc,<br>        },<br>        FLAGS.save_model,)<br>  if xm.is_master_ordinal():<br>      _upload_blob_gcs(FLAGS.logdir, FLAGS.save_model, &#39;model-chkpt.pt&#39;)</pre><p>Here is the function that uses the Cloud Storage SDK to upload each model checkpoint to GCS:</p><pre>def _upload_blob_gcs(gcs_uri, source_file_name, destination_blob_name):<br>   &quot;&quot;&quot;Uploads a file to GCS bucket&quot;&quot;&quot;<br>   client = storage.Client()<br>   blob = Blob.from_string(os.path.join(gcs_uri, destination_blob_name))<br>   blob.bucket._client = client<br>   blob.upload_from_filename(source_file_name)</pre><p>If we want to resume training from a previous checkpoint, we use the LOAD_CHKPT_FILE variable to specify the GCS object to download and the LOAD_CHKPT_DIR variable to specify the local directory to place this file. Once the model is initialized, we deserialize the dictionary with , load the model&#39;s parameter dictionary with <a href="https://pytorch.org/docs/stable/nn.html?highlight=load_state_dict#torch.nn.Module.load_state_dict">load_state_dict()</a>, and move the model to the devices with .to(device).</p><pre>if FLAGS.load_chkpt_file != &quot;&quot;:<br>   _read_blob_gcs(FLAGS.model_bucket,<br>                  FLAGS.load_chkpt_file,<br>                  FLAGS.load_chkpt_dir) # download object from GCS<br>   checkpoint = torch.load(FLAGS.load_chkpt_dir) # deserialize<br>   model.load_state_dict(checkpoint[&#39;model_state_dict&#39;]) # load params<br>   model = model.to(device) # move model to devices</pre><p>Here is the function that uses the Cloud Storage SDK to download the checkpoint and save it to a local directory:</p><pre>def _read_blob_gcs(BUCKET, CHKPT_FILE, DESTINATION):<br>   &quot;&quot;&quot;Downloads a file from GCS to local directory&quot;&quot;&quot;<br>   client = storage.Client()<br>   bucket = client.get_bucket(BUCKET)<br>   blob = bucket.get_blob(CHKPT_FILE)<br>   blob.download_to_filename(DESTINATION)</pre><p>We can use other information from our dictionary to configure the training job, such as updating the best validation accuracy and epoch:</p><pre>if FLAGS.load_chkpt_file != &quot;&quot;:<br>   best_valid_acc = checkpoint[&#39;best_valid_acc&#39;]<br>   start_epoch = checkpoint[&#39;epoch&#39;]<br>else:<br>   best_valid_acc = 0.0<br>   start_epoch = 1</pre><p>If we don’t want to save or load these files, we can omit them from the command line arguments. Details on saving and loading PyTorch / XLA checkpoint files can be found <a href="https://github.com/pytorch/xla/blob/master/API_GUIDE.md#saving-and-loading-xla-tensors">here</a>.</p><p>Now we are ready to train.</p><pre>python3 -m torch_xla.distributed.xla_dist --tpu=$TPU_NAME \<br>   --restart-tpuvm-pod-server --env XLA_USE_BF16=1 \<br>   -- python3 /usr/share/pytorch/torchxla_tpu/test_train_mp_wds_cifar.py \<br>   --num_epochs=$NUM_EPOCHS \<br>   --batch_size=$BATCH_SIZE \<br>   --num_workers=$NUM_WORKERS \<br>   --log_steps=10 \<br>   --test_set_batch_size=$TEST_BATCH_SIZE \<br>   --wds_traindir=&quot;$WDS_TRAIN_DIR&quot; --wds_testdir=&quot;$WDS_VAL_DIR&quot; \<br>   --save_model=$SAVE_MODEL --model_bucket=$BUCKET \<br>   --trainsize=$TRAIN_SIZE --testsize=$TEST_SIZE \<br>   --logdir=$LOGDIR 2&gt;&amp;1 | tee -a /tmp/out-wds-1.log</pre><ul><li><strong>--restart-tpuvm-pod-server</strong> restarts the XRT_SERVER (XLA Runtime) and is useful when running consecutive TPU jobs (especially if that server was left in a bad state). Since the XRT_SERVER is persistent for the pod setup, environment variables won&#39;t be picked up until the server is restarted.</li><li><strong>test_train_mp_wds_cifar.py </strong>closely follows the PyTorch / XLA distributed, multiprocessing <a href="https://github.com/pytorch/xla/blob/master/test/test_train_mp_imagenet.py">script</a>, but is adapted to include support for WebDataset and CIFAR</li><li>TPUs have hardware support for <a href="https://cloud.google.com/blog/products/ai-machine-learning/bfloat16-the-secret-to-high-performance-on-cloud-tpus">Brain Floating Point Format</a>, which can be used by setting <strong>XLA_USEBF16=1</strong></li></ul><p>During training, output for each step looks like this:</p><pre>10.164.0.25 [0] | Training Device=xla:0/2 Epoch=8 Step=310 Loss=0.26758 Rate=1079.01 GlobalRate=1420.67 Time=18:02:10</pre><ul><li><strong>10.164.0.25</strong> refers to the IP address for this VM worker</li><li><strong>[0]</strong> refers to VM worker 0. Recall, there are 4 VM workers in our example</li><li><strong>Training Device=xla:0/2</strong> refers to the TPU core 2. In our example there are 32 TPU cores, so you should see up to (since they are 0-based)</li><li><strong>Rate=1079.01</strong> refers to the exponential moving average of examples per second for this TPU core</li><li><strong>GlobalRate=1420.67</strong> refers to the average number of examples per second for this core so far during this epoch</li></ul><p>At the end of each epoch’s train loop, you will see output like this:</p><pre>[0] Epoch 8 train end 18:02:10, Epoch Time=0:00:28, Replica Train Samples=39664, Reduced GlobalRate=45676.50</pre><ul><li><strong>Replica Train Samples </strong>tells us how many training samples this replica processed</li><li><strong>Reduced GlobalRate </strong>is the average GlobalRate across all replicas for this epoch</li></ul><p>Once training is complete, you will see the following output:</p><pre>[0] Total Train Time: 0:03:59<br>[0] Max Accuracy: 79.67%<br>[0] Avg. Global Rate: 48718.11 examples per second</pre><p>The logs for each VM worker are produced asynchronously, so it can be difficult to read them sequentially. To view the logs sequentially for any TPU VM worker, we can execute the following command, where the IP_ADDRESS is the address to the left of our [0].</p><pre>grep &quot;IP_ADDRESS&quot; /tmp/out-wds-1.log</pre><p>We can convert these to a .txt file and store them in a GCS bucket like this:</p><pre>grep &quot;IP_ADDRESS&quot; /tmp/out-wds-1.log &gt; /tmp/out-wds-1.log.txt<br><br>gsutil cp /tmp/out-wds-1.log.txt gs://${BUCKET}/YOUR_FILE_NAME.txt</pre><h3>Cleaning up</h3><p>We can clean up our TPU VM resources in one simple command.</p><p>First, disconnect from the TPU VM, if you have not already done so:</p><pre>exit</pre><p>In the Cloud Shell, use the following command to delete the TPU VM resources:</p><pre>gcloud alpha compute tpus tpu-vm delete ${TPU_NAME} \<br>    --zone ${ZONE} \<br>    --project ${PROJECT_ID}</pre><p>If you wish to delete the GCS bucket and its contents, run the following command in the Cloud Shell terminal:</p><pre>gsutil rm -r gs://${BUCKET}</pre><h3>What’s next?</h3><p>In this article we explored the challenges of using remote storage in distributed deep learning training jobs. We discussed the advantages of using sharded, sequentially readable data formats to solve the challenges with remote storage access and how the WebDataset library makes this easier with PyTorch. We then walked through an example demonstrating how to stream training data from GCS to TPU VMs and train a PyTorch / XLA model on Cloud TPU Pod slices.</p><h3>References</h3><p>In the next installment of this series, we will revisit this example and work with <a href="https://cloud.google.com/tpu/docs/cloud-tpu-tools">Cloud TPU Tools</a> to further optimize our training job. We will demonstrate how variables such as shard size, shard count, batch size, and number of workers impact the input pipeline, resource utilization, examples per second, accuracy, loss, and overall model convergence.</p><p>Have a question or want to chat? Find the authors here — <a href="https://www.linkedin.com/in/jordantotten/">Jordan</a> and <a href="https://www.linkedin.com/in/shanemhansen/">Shane</a>.</p><p>Special thanks to <a href="https://www.linkedin.com/in/karlweinmeister/">Karl Weinmeister</a>, <a href="https://www.linkedin.com/in/rajeshthallam/">Rajesh Thallam</a>, and <a href="https://www.linkedin.com/in/1vaibhavsingh/">Vaibhav Singh</a> for their contributions to this post, as well as <a href="https://www.linkedin.com/in/jysohn23/">Daniel Sohn</a>, <a href="https://www.linkedin.com/in/zachary-cain-74330061/">Zach Cain</a>, and the rest of the PyTorch / XLA team for their efforts to enhance the PyTorch experience on Cloud TPUs.</p><p><em>Originally published at </em><a href="https://cloud.google.com/blog/topics/developers-practitioners/scaling-deep-learning-workloads-pytorch-xla-and-cloud-tpu-vm"><em>https://cloud.google.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bc427213601" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gcp-contributions/scaling-deep-learning-workloads-with-pytorch-xla-and-cloud-tpu-vm-google-cloud-blog-1bc427213601">Scaling deep learning workloads with PyTorch / XLA and Cloud TPU VM | Google Cloud Blog</a> was originally published in <a href="https://medium.com/gcp-contributions">Scaling ML workloads with Google Cloud</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling deep retrieval with TensorFlow Recommenders and Vertex AI Vector Search]]></title>
            <link>https://medium.com/gcp-contributions/scaling-deep-retrieval-with-tensorflow-recommenders-and-vertex-ai-vector-search-11f280dedc58?source=rss----53eba2bd3dcb---4</link>
            <guid isPermaLink="false">https://medium.com/p/11f280dedc58</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow-recommenders]]></category>
            <dc:creator><![CDATA[Jordan Totten]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 10:17:45 GMT</pubDate>
            <atom:updated>2025-05-09T16:44:01.508Z</atom:updated>
            <content:encoded><![CDATA[<p>Authors: <a href="https://www.linkedin.com/in/jordantotten/">Jordan Totten</a> and <a href="https://www.linkedin.com/in/wortz/">Jeremy Wortz</a>, ML Specialists @ Google Cloud</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kpdR4iCOvqw0GGbI.jpg" /></figure><p>In a previous <a href="https://cloud.google.com/blog/topics/developers-practitioners/looking-build-recommendation-system-google-cloud-leverage-following-guidelines-identify-right-solution-you-part-i">blog</a>, we outlined three approaches for implementing recommendation systems on Google Cloud, including (1) a fully managed solution from <a href="https://cloud.google.com/retail/docs">Recommendations AI</a>, (2) matrix factorization with <a href="https://cloud.google.com/bigquery-ml/docs/">BigQuery ML</a>, and (3) custom deep retrieval techniques using two-tower encoders and <a href="https://cloud.google.com/vertex-ai/docs/matching-engine/overview">Vertex AI Vector Search</a>. In this blog, we dive deep into option (3) and demonstrate how to build a playlist recommendation system by implementing an end-to-end candidate retrieval workflow from scratch with Vertex AI. Specifically, we will cover:</p><ul><li>The evolution of retrieval modeling and why two-tower encoders are popular for deep retrieval tasks</li><li>Framing a playlist-continuation use-case using the <a href="https://www.aicrowd.com/challenges/spotify-million-playlist-dataset-challenge">Spotify Million Playlist Dataset</a> (MPD)</li><li>Developing custom two-tower encoders with the <a href="https://www.tensorflow.org/recommenders">TensorFlow Recommenders</a> (TFRS) library</li><li>Serving candidate embeddings in an approximate nearest neighbors (ANN) index with <a href="https://cloud.google.com/vertex-ai/docs/matching-engine/overview">Vertex AI Vector Search</a></li></ul><p>All related code can be found in this <a href="https://github.com/jswortz/spotify_mpd_two_tower">GitHub repository</a>.</p><h3>Background</h3><p>To meet low latency serving requirements, large-scale recommenders are often deployed to production as <a href="https://medium.com/nvidia-merlin/recommender-systems-not-just-recommender-models-485c161c755e">multi-stage systems</a>. The goal of the first stage (candidate retrieval) is to sift through a large (&gt;100M elements) corpus of candidate items and retrieve a relevant subset (~hundreds) of items for downstream ranking and filtering tasks. To optimize this retrieval task, we consider two core objectives:</p><ol><li>During model training, find the best way to compile all knowledge into &lt;query, candidate&gt; embeddings.</li><li>During model serving, retrieve relevant candidate items fast enough to meet latency requirements</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2wYBuvRhUJ2lc0_P5h-Ew.png" /><figcaption><em>Figure 1: Conceptual components of multi-stage recommendation systems; the focus of this blog is the first stage, candidate retrieval.</em></figcaption></figure><p>Two-tower architectures are popular for retrieval tasks because they capture the semantics of query and candidate entities, and map these to a shared <a href="https://developers.google.com/machine-learning/recommendation/overview/candidate-generation#embedding-space">embedding space</a> such that semantically similar entities cluster closer together. This means, if we compute the <a href="https://cloud.google.com/blog/topics/developers-practitioners/meet-ais-multitool-vector-embeddings">vector embeddings</a> of a given query, we can search the embedding space for the closest (most similar) candidates. Because these neural network-based retrieval models take advantage of metadata, context, and feature interactions, they can produce highly informative embeddings and offer flexibility to adjust for various business objectives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*axlM-Q5la7I_npOLksr64g.gif" /><figcaption><em>Figure 2: The two-tower encoder model is a specific type of embedding-based search where one deep neural network tower produces the query embedding and a second tower computes the candidate embedding. Calculating the </em><a href="https://developers.google.com/machine-learning/recommendation/overview/candidate-generation#dot-product"><em>dot product</em></a><em> between the two embedding vectors determines how close (similar) the candidate is to the query. Source: </em><a href="https://medium.com/mlearning-ai/building-a-multi-stage-recommendation-system-part-1-1-95961ccf3dd8"><em>Announcing ScaNN: Efficient Vector Similarity Search</em></a></figcaption></figure><p>While these capabilities help achieve useful &lt;query, candidate&gt; embeddings, we still need to resolve the retrieval latency requirements. To this end, the two-tower architecture offers one more advantage: the ability to decouple inference of query and candidate items. This decoupling means all candidate item embeddings can be precomputed, reducing the serving computation to (1) converting queries to embedding vectors and (2) searching for similar vectors (among the precomputed candidates).</p><p>As candidate datasets scale to millions (or billions) of vectors, the similarity search often becomes a computational bottleneck for model serving. Relaxing the search to approximate distance calculations can lead to significant latency improvements, but we need to minimize negatively impacting search accuracy (i.e., relevance, recall).</p><p>In the paper <a href="https://arxiv.org/abs/1908.10396">Accelerating Large-Scale Inference with Anisotropic Vector Quantization</a>, Google Researchers address this speed-accuracy trade-off with a novel compression algorithm that, compared to <a href="https://github.com/erikbern/ann-benchmarks#evaluated">previous state-of-the-art methods</a>, improves both the relevance and speed of retrieval. At Google, this technique is widely-adopted to support deep retrieval use cases across Search, YouTube, Ads, Lens, and others. And while it’s available in an open-sourced library (<a href="https://github.com/google-research/google-research/tree/master/scann">ScaNN</a>), it can still be challenging to implement, tune, and scale. To help teams take advantage of this technology without the operational overhead, Google Cloud offers these capabilities (and more) as a managed service with <a href="https://cloud.google.com/vertex-ai/docs/matching-engine/overview">Vertex AI Vector Search</a>.</p><p>The goal of this post is to demonstrate how to implement these deep retrieval techniques using Vertex AI and discuss the decisions and trade-offs teams will need to evaluate for their use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoCzZap2HH1HiNBbpv6Gjw.png" /><figcaption><em>Figure 3: A reference architecture for two-tower training and deployment on Vertex AI.</em></figcaption></figure><h3>Two-towers for deep retrieval</h3><p>To better understand the benefits of two-tower architectures, let’s review three key modeling milestones in candidate retrieval.</p><h4>Evolution of retrieval modeling</h4><p>Traditional information retrieval systems rely heavily on token-based matching, where candidates are retrieved using an inverted index of n-grams. These systems are interpretable, easy to maintain (e.g., no training data), and are capable of achieving high precision. However, they typically suffer poor recall (i.e., trouble finding all relevant candidates for a given query) because they look for candidates having exact matches of key words. While they are still used for select Search use cases, many retrieval tasks today are either adapted with or replaced by embedding-based techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kmuLQaXojvmFbMZixiCJg.jpeg" /><figcaption><em>Figure 4: Token-based matching selects candidate items by matching key words found in both query and candidate items.</em></figcaption></figure><p>Factorization-based retrieval introduces a simple embedding-based model that offers much better <a href="https://developers.google.com/machine-learning/crash-course/generalization/video-lecture">generalization</a> by capturing the similarity between &lt;query, candidate&gt; pairs and mapping them to a shared embedding space. One of the major benefits to this <a href="https://developers.google.com/machine-learning/recommendation/collaborative/basics">collaborative filtering</a> technique is that embeddings are learned automatically from implicit query-candidate interactions. Fundamentally, these models factorize the full query-candidate interaction (co-occurrence) matrix to produce smaller, dense embedding representations of queries and candidates, where the product of these embedding vectors is a good approximation of the interaction matrix. The idea is that by compacting the full matrix into k dimensions the model learns the top k latent factors describing &lt;query, candidate&gt; pairs with respect to the modeling task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-a9-98pwW5cAz3TtSuRlOw.jpeg" /><figcaption><em>Figure 5: Factorization-based models factorize a query-candidate interaction matrix into the product of two lower-rank matrices that capture the query-candidate interactions.</em></figcaption></figure><p>The latest modeling paradigm for retrieval, commonly referred to as neural deep retrieval (NDR), produces the same embedding representations, but uses deep learning to create them. NDR models like two-tower encoders apply deep learning by processing input features with successive network layers to learn layered representations of the data. Effectively, this results in a neural network that acts as an information distillation pipeline, where raw, multi-modal features are repeatedly transformed such that useful information is magnified and irrelevant information is filtered. This results in a highly expressive model capable of learning non-linear relationships and more complex feature interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVMCW_3Rmz7fjf97LKV2KQ.png" /><figcaption><em>Figure 6: NDR architectures like two-tower encoders are conceptually similar to factorization models. Both are embedding-based retrieval techniques computing lower-dimensional vector representations of query and candidates, where the similarity between these two vectors is determined by computing their </em><a href="https://developers.google.com/machine-learning/recommendation/overview/candidate-generation#dot-product"><em>dot product</em></a><em>.</em></figcaption></figure><p>In a two-tower architecture, each tower is a neural network that processes either query or candidate input features to produce an embedding representation of those features. Because the embedding representations are simply vectors of the same length, we can compute the <a href="https://developers.google.com/machine-learning/recommendation/overview/candidate-generation#dot-product">dot product</a> between these two vectors to determine how close they are. This means the orientation of the embedding space is determined by the dot product of each &lt;query, candidate&gt; pair in the training examples.</p><h4>Decoupled inference for optimal serving</h4><p>In addition to increased expressivity and generalization, this kind of architecture offers optimization opportunities for serving. Because each tower only uses its respective input features to produce a vector, the trained towers can be operationalized separately. Decoupling inference of the towers for retrieval means we can precompute what we want to find when we encounter its pair in the wild. It also means we can optimize each inference task differently:</p><ul><li>Run a batch prediction job with a trained candidate tower to precompute embedding vectors for all candidates, attach NVIDIA GPU to accelerate computation</li><li>Compress precomputed candidate embeddings to an ANN index optimized for low-latency retrieval; deploy index to an endpoint for serving</li><li>Deploy trained query tower to an endpoint for converting queries to embeddings in real time, attach NVIDIA GPU to accelerate computation</li></ul><p>Training two-tower models and serving them with an ANN index is different from training and serving traditional machine learning (ML) models. To make this clear, let’s review the key steps to operationalize this technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPXKpZeCLNnS-RsvC8aZYw.png" /><figcaption><em>Figure 7: A reference architecture for two-tower training and deployment on Vertex AI.</em></figcaption></figure><ol><li>Train combined model (two-towers) offline; each tower is saved separately for different tasks</li><li>Upload the query tower to Vertex AI Model Registry and deploy to an online endpoint</li><li>Upload the candidate tower to Vertex AI Model Registry</li><li>Request candidate tower to predict embeddings for each candidate track, save embeddings in JSON file</li><li>Create ANN serving index from embeddings JSON, deploy to online index endpoint</li><li>User application calls endpoint.predict() with playlist data, model returns the embedding vector representing that playlist</li><li>Use the playlist embedding vector to search for N nearest neighbors (candidate tracks)</li><li>Vertex AI Vector Search returns the product IDs for the N nearest neighbors</li></ol><h3>Problem framing</h3><p>In this example, we use MPD to construct a recommendation use case, playlist continuation, where candidate tracks are recommended for a given playlist (query). This dataset is publicly available and offers several benefits for this demonstration:</p><ul><li>Includes real relationships between entities (e.g., playlists, tracks, artists) which can be difficult to replicate</li><li>Large enough to replicate scalability issues likely to occur in production</li><li>Variety of feature representations and data types (e.g., playlist and track IDs, raw text, numerical, datetime); ability to enrich dataset with additional metadata from the <a href="https://developer.spotify.com/documentation/web-api/">Spotify Web Developer API</a></li><li>Teams can analyze the impact of modeling decisions by listening to retrieved candidate tracks (e.g., generate recommendations for your own Spotify playlists)</li></ul><h4>Training examples</h4><p>Creating training examples for recommendation systems is a non-trivial task. Like any ML use case, training data should accurately represent the underlying problem we are trying to solve. Failure to do this can lead to poor model performance and unintended consequences for the user experience. One such lesson from the <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/45530.pdf">Deep Neural Networks for YouTube Recommendations</a>EditSignEditSignEditSign paper highlights that relying heavily on features such as ‘click-through rate’ can result in recommending clickbait (i.e., videos users rarely complete), as compared to features like ‘watch time’ which better capture a user’s engagement.</p><p>Training examples should represent a semantic match in the data. For playlist-continuation, we can think of a semantic match as pairing playlists (i.e., a set of tracks, metadata, etc.) with tracks similar enough to keep the user engaged with their listening session. How does the structure of our training examples influence this?</p><ul><li>Training data is sourced from positive &lt;query, candidate&gt; pairs</li><li>During training, we forward propagate query and candidate features through their respective towers to produce the two vector representations, from which we compute the dot product representing their similarity</li><li>After training, and before serving, the candidate tower is called to predict (precompute) embeddings for all candidate items</li><li>At serving time, the model processes features for a given playlist and produces a vector embedding</li><li>The playlist’s vector embedding is used in a search to find the most similar vectors in the precomputed candidate index</li><li>The placement of candidate and playlist vectors in the embedding space, and the distance between them, is defined by the semantic relationships reflected in the training examples</li></ul><p>The last point is important. Because the quality of our embedding space dictates the success of our retrieval, the model creating this embedding space needs to learn from training examples that best illustrate the relationship between a given playlist and ‘similar’ tracks to retrieve.</p><p>This notion of similarity being highly dependent on the choice of paired data highlights the importance of preparing features that describe semantic matches. A model trained on &lt;playlist title, track title&gt; pairs will orient candidate tracks differently than a model trained on &lt;aggregated playlist audio features, track audio features&gt; pairs.</p><p>Conceptually, training examples consisting of &lt;playlist title, track title&gt; pairs would create an embedding space in which all tracks belonging to playlists of the same or similar titles (e.g., &#39;beach vibes&#39; and &#39;beach tunes&#39;) would be closer together than tracks belonging to different playlist titles (e.g., &#39;beach vibes&#39; vs &#39;workout tunes&#39;); and examples consisting of &lt;aggregated playlist audio features, track audio features&gt; pairs would create an embedding space in which all tracks belonging to playlists with similar audio profiles (e.g., &#39;live recordings of instrumental jams&#39; and &#39;high energy instrumentals&#39;) would be closer together than tracks belonging to playlists with different audio profiles (e.g., &#39;live recordings of instrumental jams&#39; vs &#39;acoustic tracks with lots of lyrics&#39;).</p><p>The intuition for these examples is that when we structure the rich track-playlist features in a format that describes how tracks show up on certain playlists, we can feed this data to a two tower model that learns all of the niche relationships between parent playlist and child tracks. Modern deep retrieval systems often consider user profiles, historical engagements, and context. While we don’t have user and context data in this example, they can easily be added to the query tower.</p><h3>Implementing deep retrieval with TFRS</h3><p>When building retrieval models with TFRS, the two towers are implemented with <a href="https://www.tensorflow.org/guide/keras/custom_layers_and_models">model subclassing</a>. Each tower is built separately as a callable to process input feature values, pass them through feature layers, and concatenate the results. This means the tower is simply producing one concatenated vector (i.e., the representation of the query or candidate; whatever the tower represents).</p><p>First, we define the basic structure of a tower and implement it as a subclassed Keras model:</p><pre>class Playlist_Tower(tf.keras.Model):<br>   &#39;&#39;&#39;<br>   produced embedding represents the features<br>   of a Playlist known at query time<br>   &#39;&#39;&#39;<br>   def __init__(self, layer_sizes, vocab_dict):<br>       super().__init__()<br><br>       # TODO: build sequential model for each feature here<br><br>   def call(self, data):<br>       &#39;&#39;&#39;<br>       defines what happens when the model is called<br>       &#39;&#39;&#39;<br>       all_embs = tf.concat(<br>           [<br>               # TODO: concatenate output of all features defined above<br>                           <br>           ], axis=1)<br>      <br>       # pass output to dense/cross layers<br>       if self._cross_layer is not None:<br>           cross_embs = self._cross_layer(all_embs)<br>           return self.dense_layers(cross_embs)<br>       else:<br>           return self.dense_layers(all_embs)</pre><p>We further define the subclassed towers by creating Keras sequential models for each feature being processed by that tower:</p><pre># Feature: pl_name_src<br>self.pl_name_src_text_embedding = tf.keras.Sequential(<br>   [<br>       tf.keras.layers.TextVectorization(<br>           vocabulary=vocab_dict[&#39;pl_name_src&#39;],<br>           ngrams=2,<br>           name=&quot;pl_name_src_textvectorizor&quot;<br>       ),<br>       tf.keras.layers.Embedding(<br>           input_dim=MAX_TOKENS,<br>           output_dim=EMBEDDING_DIM,<br>           name=&quot;pl_name_src_emb_layer&quot;,<br>           mask_zero=False<br>       ),<br>       tf.keras.layers.GlobalAveragePooling1D(name=&quot;pl_name_src_1d&quot;),<br>   ], name=&quot;pl_name_src_text_embedding&quot;<br>)</pre><p>Because the features represented in the playlist’s STRUCT are sequence features (lists), we need to reshape the embedding layer output and use 2D pooling (as opposed to the 1D pooling applied for non-sequence features):</p><pre># Feature: artist_genres_pl<br>self.artist_genres_pl_embedding = tf.keras.Sequential(<br>   [<br>       tf.keras.layers.TextVectorization(<br>           ngrams=2,<br>           vocabulary=vocab_dict[&#39;artist_genres_pl&#39;],<br>           name=&quot;artist_genres_pl_textvectorizor&quot;<br>       ),<br>       tf.keras.layers.Embedding(<br>           input_dim=MAX_TOKENS, <br>           output_dim=EMBED_DIM,<br>           name=&quot;artist_genres_pl_emb_layer&quot;,<br>           mask_zero=False<br>       ),<br>       tf.keras.layers.Reshape([-1, MAX_PL_LENGTH, EMBED_DIM]),<br>       tf.keras.layers.GlobalAveragePooling2D(name=&quot;artist_genres_pl_2d&quot;),<br>   ], name=&quot;artist_genres_pl_emb_model&quot;<br>)</pre><p>Once both towers are built, we use the TFRS base model class (<a href="https://www.tensorflow.org/recommenders/api_docs/python/tfrs/models/Model">tfrs.models.Model</a>) to streamline building the combined model. We include each tower in the class __init__ and define the compute_loss method:</p><pre>class TheTwoTowers(tfrs.models.Model):<br><br>   def __init__(self, layer_sizes, vocab_dict, parsed_candidate_dataset):<br>       super().__init__()<br>      <br>       self.query_tower = Playlist_Tower(layer_sizes, vocab_dict)<br><br>       self.candidate_tower = Candidate_Track_Tower(layer_sizes, vocab_dict)<br>      <br>       self.task = tfrs.tasks.Retrieval(<br>           metrics=tfrs.metrics.FactorizedTopK(<br>               candidates=parsed_candidate_dataset.batch(128).map(<br>                   self.candidate_tower,<br>                   num_parallel_calls=tf.data.AUTOTUNE<br>               ).prefetch(tf.data.AUTOTUNE)<br>           )<br>       )<br><br>   def compute_loss(self, data, training=False):<br>      <br>       query_embeddings = self.query_tower(data)<br>       candidate_embeddings = self.candidate_tower(data)<br>      <br>       return self.task(<br>           query_embeddings,<br>           candidate_embeddings,<br>           compute_metrics=not training,<br>           candidate_ids=data[&#39;track_uri_can&#39;],<br>           compute_batch_metrics=True<br>       )</pre><h4>Dense and cross layers</h4><p>We can increase the depth of each tower by adding dense layers after the concatenated embedding layer. As this will emphasize learning successive layers of feature representations, this can improve the expressive power of our model.</p><p>Similarly, we can add deep and cross layers after our embedding layer to better model feature interactions. Cross layers model explicit feature interactions before combining with deep layers that model implicit feature interactions. These parameters often lead to better performance, but can significantly increase the computational complexity of the model. We recommend evaluating different deep and cross layer implementations (e.g., parallel vs stacked). See the TFRS <a href="https://www.tensorflow.org/recommenders/examples/dcn">Deep and Cross Networks</a> guide for more details.</p><h3>Feature engineering</h3><p>As the factorization-based models offer a pure collaborative filtering approach, the advanced feature processing with NDR architectures allow us to extend this to also incorporate aspects of <a href="https://developers.google.com/machine-learning/recommendation/content-based/basics">content-based filtering</a>. By including additional features describing playlists and tracks, we give NDR models the opportunity to learn semantic concepts about &lt;playlist, track&gt; pairs. The ability to include label features (i.e., features about candidate tracks) also means our trained candidate tower can compute an embedding vector for candidate tracks not observed during training (i.e., cold-start). Conceptually, we can think of such a new candidate track embedding compiling all the content-based and collaborative filtering information learned from candidate tracks with the same or similar feature values.</p><p>With this flexibility to add multi-modal features, we just need to process them to produce embedding vectors with the same dimensions so they can be concatenated and fed to subsequent deep and cross layers. This means if we use pre-trained embeddings as an input feature, we would pass these through to the concatenation layer (see Figure 8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*Ror97q8sZyfAt-IF7QobTg.png" /><figcaption><em>Figure 8: Illustration of feature processing from input to concatenated output. Text features are generated via n-grams. Integer indexes of n-grams are passed to an embedding layer. Hashing produces unique integers up to 1,000,000; values passed to an embedding layer. If using pre-trained embeddings, these are passed through the tower without transformation and concatenated with the other embedding representations.</em></figcaption></figure><h4>Hashing vs StringLookup() layers</h4><p>Hashing is generally recommended when fast performance is needed and is preferred over string lookups because it skips the need for a lookup table. Setting the proper bin size for the hashing layer is critical. When there are more unique values than hashing bins, values start getting placed into the same bins, and this can negatively impact our recommendations. This is commonly referred to as a hashing collision, and can be avoided when building the model by allocating enough bins for the unique values. See <a href="https://www.tensorflow.org/recommenders/examples/featurization#turning_categorical_features_into_embeddings">turning categorical features into embeddings</a> for more details.</p><h4>TextVectorization() layers</h4><p>The key to text features is to understand if creating additional NLP features with the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/TextVectorization">TextVectorization</a> layer is helpful. If additional context derived from the text feature is minimal, it may not be worth the cost to model training. This layer needs to be adapted from the source dataset, meaning the layer requires a scan of the training data to create lookup dictionaries for the top N n-grams (set by max_tokens).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*GZ-vAgWrOVfm8nGxTRUVYw.png" /><figcaption><em>Figure 9: Decision tree to guide feature engineering strategy.</em></figcaption></figure><h3>Efficient retrieval with Vertex AI Vector Search</h3><p>So far we’ve discussed how to map queries and candidates to the shared embedding space. Now let’s discuss how to best use this shared embedding space for efficient serving.</p><p>Recall at serving time, we will use the trained query tower to compute the embeddings for a query (playlist) and use this embedding vector in a nearest neighbor search for the most similar candidate (track) embeddings. And, because the candidate dataset can grow to millions or billions of vectors, this nearest neighbor search often becomes a computational bottleneck for low-latency inference.</p><p>Many state-of-the-art techniques address the computational bottleneck by compressing the candidate vectors such that ANN calculations can be performed in a fraction of the time needed for an exhaustive search. The novel compression algorithm proposed by Google Research modifies these techniques to also optimize for the nearest neighbor search accuracy. The details of their proposed technique are described <a href="https://ai.googleblog.com/2020/07/announcing-scann-efficient-vector.html">here</a>, but fundamentally their approach seeks to compress the candidate vectors such that the original distances between vectors are preserved. Compared to previous solutions, this results in a more accurate relative ranking of a vector and its nearest neighbors, i.e., it minimizes distorting the vector similarities our model learned from the training data.</p><h3>Fully managed vector database and ANN service</h3><p>Vertex AI Vector Search is a managed solution utilizing these techniques for efficient vector similarity search. It offers customers a highly scalable vector database and ANN service while alleviating the operational overhead of developing and maintaining similar solutions, such as the open sourced <a href="https://github.com/google-research/google-research/tree/master/scann">ScaNN</a> library. It includes several capabilities that simplify production deployments, including:</p><ul><li><strong>Large-scale:</strong> supports large embedding datasets with up to 1 billion embedding vectors</li><li><strong>Incremental updates:</strong> depending on the number of vectors, complete index rebuilds can take hours. With incremental updates, customers can make small changes without building a new index (see <a href="https://cloud.google.com/vertex-ai/docs/matching-engine/update-rebuild-index">Update and rebuild an active index</a> for more details)</li><li><strong>Dynamic rebuilds:</strong> when an index grows beyond its original configuration, Vector Search periodically re-organizes the index and serving structure to ensure optimal performance</li><li><strong>Autoscaling:</strong> underlying infrastructure is autoscaled to ensure consistent performance at scale</li><li><strong>Filtering and diversity:</strong> ability to include multiple restrict and crowding tags per vector. At query inference time, use boolean predicates to filter results with strings, numerical values, allow lists, and deny lists; enforce diversity with crowding tags (see <a href="https://cloud.google.com/vertex-ai/docs/matching-engine/filtering">filter vector matches</a> for more details)</li><li><strong>Multi-index deployments</strong> — <a href="https://github.com/googleapis/python-aiplatform/blob/main/google/cloud/aiplatform/matching_engine/matching_engine_index_endpoint.py#L1222">deploy multiple indexes</a> to a single endpoint (sometimes referred to as “namespacing”)</li></ul><p>When creating an ANN index, Vector Search uses the <a href="https://arxiv.org/abs/1908.10396">Tree-AH</a> algorithm to build a distributed implementation of our candidate index. The term “tree-AH” refers to a <a href="https://github.com/google-research/google-research/tree/master/scann/scann/tree_x_hybrid">tree-x hybrid</a> model, which essentially combines two complementary algorithms:</p><ul><li><strong>Distributed search tree</strong> for hierarchically organizing the embedding space. Each level of this tree is a clustering of the nodes at the next level down, where the final leaf-level is a clustering of our candidate embedding vectors</li><li><strong>Asymmetric hashing</strong> (AH) for fast dot product approximation algorithm used to score similarity between a query vector and the search tree nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1E9XFQW7Q7nPKyN4VEObeg.png" /><figcaption><em>Figure 10: conceptual representation of the partitioned candidate vector dataset. During query inference, all partition centroids are scored. In the centroids most similar to the query vector, all candidate vectors are scored. The scored candidate vectors are aggregated and re-scored, returning the top N candidate vectors.</em></figcaption></figure><p>This strategy shards our embedding vectors into partitions, where each partition is represented by the centroid of the vectors it contains. The aggregate of these partition centroids form a smaller dataset summarizing the larger, distributed vector dataset. At inference time, Vector Search scores all the partitioned centroids, then scores the vectors within the partitions whose centroids are most similar to the query vector.</p><h3>Conclusion</h3><p>In this blog we took a deep dive into understanding critical components of a candidate retrieval workflow using <a href="https://www.tensorflow.org/recommenders">TensorFlow Recommenders</a> and <a href="https://cloud.google.com/vertex-ai/docs/matching-engine/overview">Vertex AI Vector Search</a>. We took a closer look at the foundational concepts of two-tower architectures, explored the semantics of query and candidate entities, and discussed how things like the structure of training examples can impact the success of candidate retrieval.</p><p>All related code can be found in this <a href="https://github.com/jswortz/spotify_mpd_two_tower">GitHub repository</a>.</p><h4><em>Connect with the authors</em></h4><p><a href="https://www.linkedin.com/in/jordantotten/">Jordan Totten</a> — ML Specialist @ Google Cloud</p><p><a href="https://www.linkedin.com/in/wortz/">Jeremy Wortz</a> — ML Specialist @ Google Cloud</p><h4>Related content</h4><ul><li><a href="https://cloud.google.com/blog/products/ai-machine-learning/rags-powered-by-google-search-technology-part-1">RAGs powered by Google Search technology, Part 1 | Google Cloud Blog</a></li><li><a href="https://cloud.google.com/blog/products/ai-machine-learning/multimodal-generative-ai-search">Multimodal generative AI search | Google Cloud Blog</a></li><li><a href="https://cloud.google.com/blog/topics/developers-practitioners/mercari-leverages-googles-vector-search-technology-create-new-marketplace">Mercari leverages Google&#39;s vector search technology to create a new marketplace | Google Cloud Blog</a></li><li><a href="https://cloud.google.com/vertex-ai/docs/vector-search/notebooks">Vector Search notebook tutorials | Vertex AI | Google Cloud</a></li></ul><p><em>Originally published at </em><a href="https://cloud.google.com/blog/products/ai-machine-learning/scaling-deep-retrieval-tensorflow-two-towers-architecture"><em>https://cloud.google.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11f280dedc58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gcp-contributions/scaling-deep-retrieval-with-tensorflow-recommenders-and-vertex-ai-vector-search-11f280dedc58">Scaling deep retrieval with TensorFlow Recommenders and Vertex AI Vector Search</a> was originally published in <a href="https://medium.com/gcp-contributions">Scaling ML workloads with Google Cloud</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>