<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jordan Totten on Medium]]></title>
        <description><![CDATA[Stories by Jordan Totten on Medium]]></description>
        <link>https://medium.com/@jordantotten?source=rss-e92a11317fd9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lZh96neU7anDjvC7</url>
            <title>Stories by Jordan Totten on Medium</title>
            <link>https://medium.com/@jordantotten?source=rss-e92a11317fd9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:10:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jordantotten/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Being a (context) Control Freak: 4 optimizations that made my ADK agent 2.7x faster]]></title>
            <link>https://medium.com/@jordantotten/being-a-context-control-freak-4-optimizations-that-made-my-adk-agent-2-7x-faster-1164a1e63ab2?source=rss-e92a11317fd9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1164a1e63ab2</guid>
            <category><![CDATA[trends]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[google-adk]]></category>
            <dc:creator><![CDATA[Jordan Totten]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 05:03:12 GMT</pubDate>
            <atom:updated>2025-12-02T08:06:35.945Z</atom:updated>
            <content:encoded><![CDATA[<h4>Managing context and state to improve agent runtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZuUXBCansBIxVxX3UF0vg.png" /></figure><p>I recently reduced the total runtime of my <a href="https://google.github.io/adk-docs/">ADK</a> agent by <strong>~64%</strong>, making it <strong>2.7x faster</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*tx0Y8YnK1BZjUBapauuV-g.png" /><figcaption><strong>Performance optimization:</strong> improving in agent’s total runtime after implementing context engineering techniques.</figcaption></figure><p>This article details the four optimization techniques that led to this performance increase:</p><ol><li>Enforcing the single responsibility principle (SRP)</li><li>Mandating machine-readability with structured output</li><li>Creating context-aware instructions with direct injection</li><li>Explicit context isolation with context pruning</li></ol><p>For context, we’ll first introduce the core design philosophy, <strong>context engineering</strong>, and explain relevant aspects of the agent and tool design.</p><h4>from the source</h4><p>All code can be found <a href="https://github.com/tottenjordan/adk_pipe">here</a>.<br>Point your code agent at these PRs if you’d rather hear it from them 😤</p><ul><li>PR #28: <a href="https://github.com/tottenjordan/adk_pipe/pull/28/files">tweak prompts and tool calling for better performance #28</a></li><li>PR #29: <a href="https://github.com/tottenjordan/adk_pipe/pull/29/files">optimized e2e agent runtime w/ context engineering and efficient tool #29</a></li></ul><h3>Do you have Context Control?</h3><p>A common challenge when developing context-aware agents is dealing with the ever-growing context fed to the LLMs. As this context grows, so does the damage:</p><ul><li><strong>Cost:</strong> high token count</li><li><strong>Latency: </strong>slower<strong> </strong>processing time</li><li><strong>Context rot: </strong>performance degradation as the LLM struggles to focus</li></ul><p><a href="https://www.philschmid.de/context-engineering"><strong>Context engineering</strong></a> provides a framework for optimizing the context provided to LLMs, effectively controlling what to include and exclude from the input payload.</p><p>Fortunately, the <a href="https://google.github.io/adk-docs/">ADK</a> provides a <a href="https://google.github.io/adk-docs/get-started/about/">layered system</a> for managing context, helping developers build sophisticated, stateful, and capable agents.</p><p>This guide outlines four optimization techniques for controlling the flow of information (context), reducing resource consumption (latency, token usage, cost), and improving the quality and reliability of agent responses.</p><h3>The Agent Design</h3><blockquote>This section explains the agent and tool design that makes the four optimizations possible. It <strong>does not</strong> describe design elements contributing directly to the performance <strong>improvement</strong> of 64%.</blockquote><p>The <a href="https://github.com/tottenjordan/adk_pipe/tree/main/creative_agent">creative_agent</a> is a multi-tool agent designed to run offline with no human interaction. Given campaign metadata (e.g., brand, target product, key selling points, and target audience) and a target search trend, this agent completes the following sub-tasks:</p><ol><li>Conduct web research</li><li>Compile a comprehensive research report</li><li>Generate ad copy</li><li>Generate visual concepts</li><li>Generate ad creatives</li><li>Save HTML file displaying the top ad copy and creative ideas</li></ol><p>To complete these sub-tasks, the agent uses a powerful architectural pattern for context management by implementing LLM agents as callable functions, i.e., <a href="https://google.github.io/adk-docs/tools-custom/function-tools/#agent-tool">AgentTools</a>. These are simply LLM agents wrapped in an AgentTool <a href="https://github.com/google/adk-python/blob/main/src/google/adk/tools/agent_tool.py#L38">adapter</a> and included in the tool list of a <em>root_agent</em>. The <em>root_agent’s</em> LLM, guided by its <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L753-L800">instructions</a>, determines when to execute each “agent-as-a-tool” by generating a standard function call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtLih3z9PrFiYZ0dqrqCQw.png" /><figcaption>The root_agent has access to four <a href="https://google.github.io/adk-docs/tools-custom/function-tools/#agent-tool">Agents-as-Tools</a>. Each AgentTool’s outputs are saved to the session state and available as context for subsequent tasks performed by the `root_agent`.</figcaption></figure><p>The <a href="https://github.com/tottenjordan/adk_pipe/tree/main/creative_agent">creative_agent</a>’s <em>root_agent</em> has access to four <a href="https://google.github.io/adk-docs/tools-custom/function-tools/#agent-tool">AgentTools</a>. And because one AgentTool’s outputs can be used as input to another AgentTool, their LLM instructions, input context, and output schemas are critical in the context engineering of our agent and tool design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJefuZ9iw6kbhFAUVQHvTA.png" /><figcaption>AgentTools available to the root_agent.</figcaption></figure><h4>When Agents Become Tools</h4><blockquote>Why we eventually converted our sub-agents to AgentTools</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3R76T50BZ8bvy7TwHWlCw.png" /><figcaption>AgentTools are wrapped agents, similar to how FunctionTools are wrapped functions.</figcaption></figure><p>Earlier versions of the creative_agent delegated the sub-tasks to lower-level LLM Agents: <a href="https://google.github.io/adk-docs/agents/multi-agents/#agent-hierarchy-parent-agent-sub-agents"><strong>sub-agents</strong></a>. The difference between treating an LLM agent as a sub-agent and an AgentTool is largely about control flow and context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bc1cdFHu66CQy_VkdFkjiQ.png" /><figcaption>Key differences between sub-agents and Agents-as-a-tool.</figcaption></figure><p>In our observations, two challenges with sub-agents made it difficult to reduce the agent’s total runtime:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLrcErkNkoa7SxK3pl6W0w.png" /><figcaption>Because sub-agents transfer control, they currently need to transfer entire conversation history too. This can lead to context rot and unexpected behaviors.</figcaption></figure><p>Converting the sub-agents to AgentTools allowed us to address both challenges with better context control:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHY8tSTmCb7ObYu5r3ls1g.png" /><figcaption>The AgentTool pattern is architecturally superior for preventing context rot in hierarchical systems because it enforces encapsulation. It creates “black box” specialists, keeping the parent agent’s context clean and concise.</figcaption></figure><p>The current AgentTool pattern provides context isolation as the <em>root_agent’s</em> conversational history is not polluted with the internal steps of the AgentTool. The <em>root_agent</em> receives only the final structured results, just like any other <a href="https://google.github.io/adk-docs/tools-custom/function-tools/">function tool</a>, making it ideal for agents in which context control is a priority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RjVFxuJuDdzszukU6wH4g.png" /><figcaption>When the root_agent calls an AgentTool, the root_agent’s conversational history is not polluted with internal steps of the AgentTool’s LLM Agent (like it would be with an agent transfer to a sub-agent). The root_agent’s session.events log will show only two relevant events: a single FunctionCall to the AgentTool and a single FunctionResponse containing the final summary. The AgentTool’s entire internal process e.g., its own LLM calls and reasoning, is encapsulated and abstracted away.</figcaption></figure><h4>Defining and Invoking the AgentTool</h4><p>In the following code snippet, note how AgentTools are treated like any other FunctionTool in the LLM agent’s instructions: defined in the &lt;AVAILABLE_TOOLS&gt; block and instructed when to use in the &lt;WORKFLOW&gt; block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*fAPFkZqAh1W8IzxvCnW2Pw.png" /><figcaption>root_agent with condensed LLM instruction. Note using the XML blocks to organize components of the prompt. See the full instruction <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L749">here</a>.</figcaption></figure><blockquote>For more sub-agent vs AgentTool guidance, see <a href="https://medium.com/google-cloud/2-minute-adk-sub-agents-vs-agent-tools-fact-sheet-f20bba2c01cd">2-Minute ADK: Sub-agents vs Agent Tools Fact Sheet.</a></blockquote><h3>The Speed Boost: Becoming a (Context) Control Freak</h3><blockquote>Now let’s review the four optimizations that led to a 2.7x speedup.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*sKz40a63gJ_AVCgv9DZTjw.png" /></figure><h3>[1] Enforcing Single Responsibility Principle (SRP)</h3><p>In agent and tool design, it’s best if each LLM agent has one primary responsibility.</p><p>Recall the <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L715">Visual Generation Pipeline</a>, an <a href="http://incompleteideas.net/book/first/ebook/node66.html">actor-critic</a> framework comprised of the following agents:</p><ul><li><a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L503">visual concept drafter</a> — the “actor” generates 10 visual concept ideas, including prompts for image generation</li><li><a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L584">visual concept critic</a> — the “critic” refines each of the 10 image prompts to align with a set of best practices</li><li><a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L673">visual concept finalizer</a> — selects a subset of the 6 best visual concepts, based on a provided criteria</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72bTLivryxb0wd5Ko-davw.png" /><figcaption>visual generation pipeline using an actor-critic pattern to generate, refine, and finalize visual concepts</figcaption></figure><p><strong>The problem:</strong> I originally combined the last two tasks, leaving a single LLM to perform two relatively complex tasks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlYwixSYzX9uxTQG8sXAYw.png" /><figcaption>A previous, sub-optimal version of the Visual Generation Pipeline where a single LLM agent must perform the last two, relatively complex tasks</figcaption></figure><h4><strong>Why this was sub-optimal:</strong></h4><ul><li>Combining the tasks required the LLM to perform two complex, distinct forms of reasoning simultaneously</li><li>The final selection process should use the <strong>final, optimized prompt </strong>as a key criterion. By separating, the selection agent gets to see the best possible version of each idea before making the final cut.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDKmhos9LYiJg7P037z_IQ.png" /><figcaption>Reasons why combining the last two steps in the Visual Generation Pipeline into a single LLM Agent is not ideal.</figcaption></figure><h4>SRP’s impact on context engineering</h4><p>While <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">SRP</a> is a general software design principle, applying it to the design of ADK agents, tools, and the logic for context engineering itself leads to more modular, manageable, and effective agentic systems.</p><ul><li><strong>Cleaner inputs to context:</strong> when agents and tools adhere to SRP, the data they produce (which often becomes part of the LLM’s context) is more focused and predictable. This simplifies context engineering with clearer signals and less noise to manage.</li><li><strong>Modular context management:</strong> The code and components responsible for managing LLM context (e.g., filtering history, retrieving from memory, formatting prompts) should also be designed following SRP e.g., separate functions or classes to handle session history summarization, relevant memory retrieval, and tool output formatting</li><li><strong>Improved maintainability: </strong>the system becomes easier to understand, debug, and modify. This is crucial as the complexity of agent interactions and context manipulation grows</li></ul><p><strong>Bottom line: </strong>keep each LLM agent focused on a single task. Break them into two different LLM agents if needed. If they always occur sequentially, wrap them in a <em>SequentialAgent</em> workflow agent (like <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/sub_agents/campaign_researcher/agent.py#L140-L144">this</a>)</p><h3>[2] Structured Output: Mandate Machine-Readability</h3><p>One of the biggest improvements to quality and performance came from enforcing a structured, machine readable output (e.g., JSON) instead of a natural language numbered list. This eliminated the need for any complex parsing logic in the downstream tool.</p><p>The original prompt:</p><pre>campaign_web_planner = Agent(<br>    model=config.lite_planner_model,<br>    name=&quot;campaign_web_planner&quot;,<br>    include_contents=&quot;none&quot;,<br>    description=_DESCRIPTION,<br>    instruction=&quot;&quot;&quot;<br>You are a research strategist. <br>Your job is to create high-level queries to help marketers better understand <br>the target audience, product, and key selling points for a campaign.<br><br>&lt;INSTRUCTIONS&gt;<br>To complete the task, you need to follow these steps:<br>1. Review the campaign metadata provided in the &lt;CONTEXT&gt; block<br>2. Follow the tips provided in the &lt;KEY_GUIDANCE&gt; block to generate a list <br>   of 4-6 web queries that will help better understand the campaign metadata. <br>&lt;/INSTRUCTIONS&gt;<br><br>---<br>&lt;CONTEXT&gt;<br>...<br>&lt;/CONTEXT&gt;<br><br>---<br>&lt;KEY_GUIDANCE&gt;<br> ...<br>&lt;/KEY_GUIDANCE&gt;<br><br>---<br>### Final Instructions<br>Make sure your web queries address the points made in the &lt;KEY_GUIDANCE&gt;.<br>**CRITICAL RULE: Your output should just include a numbered list of queries. <br>Nothing else.**<br>&quot;&quot;&quot;,<br>    output_key=&quot;initial_campaign_queries&quot;,<br>)</pre><p>And here is the <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/sub_agents/campaign_researcher/agent.py#L42">revised prompt</a>:</p><pre>class CampaignSearchQuery(BaseModel):<br>    &quot;&quot;&quot;Model representing a specific search query for web search.&quot;&quot;&quot;<br><br>    search_query: str = Field(<br>        description=&quot;A highly specific and targeted query for web search.&quot;<br>    )<br><br>class CampaignQueryList(BaseModel):<br>    &quot;&quot;&quot;Model for providing evaluation feedback on research quality.&quot;&quot;&quot;<br><br>    queries: list[CampaignSearchQuery] | None = Field(<br>        default=None,<br>        description=(<br>            &quot;A list of specific, targeted web queries to provide&quot;<br>            &quot;initial insights for marketers.&quot;<br>        ),<br>    )<br><br>campaign_web_planner = Agent(<br>    model=config.lite_planner_model,<br>    name=&quot;campaign_web_planner&quot;,<br>    include_contents=&quot;none&quot;,<br>    description=_DESCRIPTION,<br>    instruction=&quot;&quot;&quot;<br>Role: You are an expert market research strategist and query <br>  optimization specialist.<br>Your job is to create a focused list of **exactly 5** high-level, <br>  effective web search queries that will provide critical insights <br>  for marketers re: target audience, product, and key selling points.<br><br>&lt;INSTRUCTIONS&gt;<br>To complete the task, you must follow these steps precisely:<br>1.  Carefully review the campaign metadata provided in the &lt;CONTEXT&gt; block.<br>2.  Follow the guidelines in the &lt;KEY_GUIDANCE&gt; block to generate a list of <br>    **exactly 5** web queries.<br>3.  **CRITICAL FOR COMPLETION:** Ensure your output is a single, valid <br>    JSON object containing the generated queries.<br>&lt;/INSTRUCTIONS&gt;<br><br>&lt;CONTEXT&gt;<br>...<br>&lt;/CONTEXT&gt;<br><br>&lt;KEY_GUIDANCE&gt;<br>...<br>&lt;/KEY_GUIDANCE&gt;<br><br>---<br>### Output Format<br>**STRICT RULE: Your entire output MUST be a valid JSON object matching <br>the &#39;CampaignQueryList&#39; schema. Do not include any introductory text,<br>reasoning, or markdown outside the JSON block.**<br>    &quot;&quot;&quot;,<br>    output_schema=CampaignQueryList,<br>    output_key=&quot;initial_campaign_queries&quot;,<br>)</pre><p>Notice we are strictly enforcing the JSON object by passing our <em>CampaignQueryList</em> class to the <em>output_schema</em> argument.</p><p>The instruction in the <strong>Output Format</strong> is brief because our class is properly defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAmmoZvvvy2MiUKKzIr6Zw.png" /></figure><h4>The impact of structured output in context engineering</h4><p>Enforcing structured outputs from the LLM or tools within an agentic system significantly impacts how context is managed and utilized:</p><p><strong>Predictability and Reliability:</strong></p><ul><li>The predictability of data generated in a known, expected format is crucial for context engineering, as the output of one step often becomes the input or part of the context for the next step</li><li>Reliably parsing and using these outputs is easier, reducing errors and inconsistencies in the data fed back into the LLM’s context.</li></ul><p><strong>Reduced Context Pollution:</strong></p><ul><li>Unstructured text outputs can be verbose and contain unnecessary information, quickly filling up the limited context window with “noise.” <strong>This context rot can degrade performance</strong> and cause the agent to lose track of its goal</li><li>Structured outputs allow the system to be precise about what information is carried forward, ensuring only valuable data occupies the context space</li></ul><p><strong>Improved Tool Integration and Chaining:</strong></p><ul><li>As ADK agents often interact with various tools, structured outputs ensure seamless integration with these tools</li><li>The structured output from one tool can be reliably parsed and fed into another tool or back to the LLM, enabling complex, multi-step agentic workflows</li></ul><p><strong>Bottom line:</strong> if you are passing anything other than a block of text to a downstream task (e.g., list of questions, multiple dictionary entries), create a <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L372-L408">class</a> and pass it to the <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L457">output_schema</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHFJeIflIJD7CnyvujxdEA.png" /><figcaption>structured output saved to session state</figcaption></figure><h3>[3] Direct Injection: Put the Context Where the LLM Can See It</h3><p>When working with LLM agent instances, we can directly inject session state values into the agent’s instructions, allowing us to create dynamic and context-aware instructions.</p><p><strong>The problem:</strong> Initially, I incorrectly instructed my LLM agents to retrieve session state values <em>directly from the session state keys</em>.</p><p><strong>Why this is sub-optimal:</strong> The LLM agent should only read from its instructions prompt. It will not retrieve data from a session state key.</p><h4>In a system orchestrated by a root_agent, the data flow is typically:</h4><ol><li><strong>Orchestrator’s Action:</strong> The <em>root_agent</em> retrieves data from a state key (e.g., <em>visual_draft</em>).</li><li><strong>Orchestrator’s Role:</strong> The <em>root_agent</em> then <strong>injects</strong> that data as a variable into the <strong>Agent’s Prompt</strong> (usually inside an XML block like &lt;CONTEXT&gt;).</li><li><strong>LLM Agent’s Action:</strong> The LLM Agent’s only job is to process the text <strong>within its prompt</strong>. It cannot <em>directly</em> read from the external ADK state key.</li></ol><p>Therefore, the LLM Agent should be instructed to read from the &lt;CONTEXT&gt; block and not from any session state key. See how I implemented this fix in the sample prompts below.</p><p>The original prompt:</p><pre>&quot;&quot;&quot;<br>&lt;INSTRUCTIONS&gt;<br>1.  **Parse and Map:** Retrieve and parse the JSON list of visual concepts <br>    from the `visual_draft` state key.<br>&lt;/INSTRUCTIONS&gt;<br><br><br> &lt;CONTEXT&gt;<br>     &lt;visual_concept_drafts_json&gt;<br>     {visual_draft}<br>     &lt;/visual_concept_drafts_json&gt;<br> &lt;/CONTEXT&gt;<br>&quot;&quot;&quot;</pre><p>The <a href="https://github.com/tottenjordan/adk_pipe/blob/main/creative_agent/agent.py#L592">revised prompt</a>:</p><pre>&quot;&quot;&quot;<br>&lt;INSTRUCTIONS&gt;<br>1.  **Parse and Map:** Retrieve and parse the JSON list of visual concepts<br>    from the **`&lt;CONTEXT&gt;` block&#39;s `visual_concept_drafts_json`** input. <br>&lt;/INSTRUCTIONS&gt;<br><br><br> &lt;CONTEXT&gt;<br>    &lt;visual_concept_drafts_json&gt;<br>    {visual_draft}<br>    &lt;/visual_concept_drafts_json&gt;<br> &lt;/CONTEXT&gt; <br>&quot;&quot;&quot;</pre><p>This is known as <a href="https://google.github.io/adk-docs/sessions/state/#bypassing-state-injection-with-instructionprovider">direct injection</a> and its benefits include:</p><ul><li><strong>Clarity:</strong> Makes it explicit which parts of the instruction are dynamic and based on session state</li><li><strong>Reliability:</strong> Avoids relying on the LLM to correctly interpret natural language instructions to access state</li><li><strong>Maintainability:</strong> Simplifies instruction strings and reduces the risk of errors when updating state variable names</li></ul><h4>Why is this commonly misunderstood?</h4><p>The reason both concepts often appear in documentation or examples is to manage the flow of the <strong>Orchestrator</strong> while guiding the <strong>LLM Agent</strong>:</p><ul><li><strong>Orchestrator’s View:</strong> “I need to take the data stored in the visual_draft state key and pass it to this agent.”</li><li><strong>LLM Agent’s View (the prompt):</strong> “I need to read the data from the input variable named &lt;visual_concept_drafts_json&gt; within my &lt;CONTEXT&gt; block.”</li></ul><blockquote>For the purpose of optimizing the LLM’s prompt and performance, the LLM should be instructed to read only from the inputs it can see: the &lt;CONTEXT&gt; block.</blockquote><h4>Naming Dynamic Variables in LLM Agent instructions</h4><pre>&quot;&quot;&quot;<br>&lt;CONTEXT&gt;<br>    &lt;revised_visual_concepts_json&gt;<br>    {visual_concept_critique}  &lt;-- This is the value of the state key<br>    &lt;/revised_visual_concepts_json&gt;<br>&lt;/CONTEXT&gt;<br>&quot;&quot;&quot;</pre><p>The data passed <em>into</em> the prompt is the content of the {visual_concept_critique}, but the LLM sees it within the tag &lt;revised_visual_concepts_json&gt;<em> .</em></p><blockquote>for the LLM,<strong> the source of the data is the tag: &lt;revised_visual_concepts_json&gt;</strong></blockquote><p>To optimize for the LLM’s performance and clarity, the instruction should direct the agent to the <strong>exact place it can find the data</strong> within the text it is reading.</p><p>To prevent me from making this mistake again, I just use the same name for the <strong>{dynamic_variable}<em> </em></strong>and the <strong>&lt;tag&gt;</strong>:</p><pre>&quot;&quot;&quot;<br>&lt;CONTEXT&gt;<br>   &lt;visual_concept_critique&gt;  &lt;-- Use the same name as the state key<br>   {visual_concept_critique}<br>   &lt;/visual_concept_critique&gt;<br>&lt;/CONTEXT&gt;<br>&quot;&quot;&quot;</pre><h4>Direct injection in context engineering</h4><p>Accessing session state within agent instructions is a key aspect of dynamic context engineering and creating more adaptive and intelligent agents:</p><ul><li><strong>Dynamic Instructions: </strong>The content of the instructions can change based on the outputs saved to session state from earlier tasks. This makes the session state a communication bus for passing data between steps.</li><li><strong>Contextualizing Behavior:</strong> Session state can store user-specific information. By referencing this state in the instructions, the agent can provide a more personalized experience. For example, addressing the user by name or remembering past interactions within the session.</li></ul><h3>[4] Active Input Management: Pruning the Context Tree</h3><blockquote>Note: implementing direct injection from session state (Optimization #3) is critical for implementing Optimization #4!</blockquote><p>The simplest way to make an agent ignore past turns is configuring it to be <em>stateless</em>.</p><p>When an LLM Agent gets its context from the instructions prompt, which includes the direct injection from session state in the &lt;CONTEXT&gt; block, setting the include_contents=&quot;none&quot; (<a href="https://google.github.io/adk-docs/agents/llm-agents/#managing-context-include_contents">docs</a>) parameter on the LLM agent prevents any historical context from influencing its behavior. This is also ideal for optimizing performance.</p><h4><strong>In the context of the ADK, when you instantiate an agent or call it within a workflow:</strong></h4><p><strong>[1] Default Behavior (high cost/context):</strong> By default, the framework passes a large amount of ambient context to the LLM. This can include:</p><ul><li>The <strong>entire conversation history</strong> (all prior turns, even if they’re irrelevant)</li><li>The <strong>full state of the session</strong> (possibly including large research reports not explicitly needed by the current agent)</li><li>The <strong>tool invocation history</strong> (and not just which tool was called, but each tool call’s inputs and outputs)</li></ul><p><strong>[2] This <em>bloats</em> the prompt,</strong> increasing <strong>latency</strong> (processing time) and <strong>cost</strong> (token count), and can even lead to the LLM getting confused or exceeding its context window limit (context rot).</p><p><strong>[3] Optimized Behavior → set </strong>include_contents=&quot;none&quot;<strong>: </strong>this setting tells the framework, “do not include any ambient context. Only pass the system prompt (role, instructions) and data the user explicitly injects via the inputs/context blocks.”</p><h4>Optimizing the creative_agent:</h4><p>For <strong>maximum performance, predictability, and cost-efficiency</strong>, we explicitly set include_contents=&quot;none&quot; for every agent in this workflow</p><ul><li>In every case, the agent’s input is a precisely defined, explicit set of data injected into the &lt;CONTEXT&gt; block</li><li>The massive context from the entire agent session (which the LLM might otherwise see) is <strong><em>completely irrelevant</em></strong> to the current task</li><li>This forces the agent to focus solely on the structured inputs we provide, which are already designed to contain exactly the information needed for that specific step</li></ul><h4>Pruning conversation history for context engineering</h4><p>In the code snippet below, we prune conversation history to enforce context isolation</p><ul><li><strong>Context control: </strong>By preventing<strong> </strong>the visual_concept_finalizer agent from receiving prior conversation history (contents), its reasoning will be based solely on its instruction and the data available in session state</li><li><strong>Idempotency: </strong>This technique is ideal for creating pure agents that act like idempotent functions, performing a specific task based only on the current turn’s data</li></ul><pre># This agent will not see any past conversation history.<br><br>visual_concept_finalizer = Agent(<br>    model=config.worker_model,<br>    name=&quot;visual_concept_finalizer&quot;,<br>    include_contents=&quot;none&quot;,<br>    description=&quot;Finalize visual concepts to proceed with.&quot;,<br>    instruction=&quot;&quot;&quot;<br>Role: You are the Lead Creative Director and Final Gatekeeper. <br>Your task is to apply ultimate strategic judgment to the final set of <br>visual concepts, selecting the absolute best for image generation<br><br>&lt;INSTRUCTIONS&gt;<br>1.  **Parse and Map:** Retrieve and parse the JSON list of revised <br>    visual concepts from the **`&lt;CONTEXT&gt;` block&#39;s `visual_concept_critique` <br>    input.<br> ...<br>&lt;/INSTRUCTIONS&gt;<br><br>&lt;CONTEXT&gt;<br>    &lt;visual_concept_critique&gt;<br>    {visual_concept_critique}<br>    &lt;/visual_concept_critique&gt;<br>&lt;/CONTEXT&gt;<br><br>&lt;OUTPUT_FORMAT&gt;<br>**CRITICAL RULE: Your entire output MUST be a single, raw JSON object<br> validating against the &#39;VisualConceptFinalList&#39; schema**<br>&lt;/OUTPUT_FORMAT&gt;<br>    &quot;&quot;&quot;,<br>    generate_content_config=types.GenerateContentConfig(<br>        temperature=0.8,<br>    ),<br>    output_schema=VisualConceptFinalList,<br>    output_key=&quot;final_visual_concepts&quot;,<br>)</pre><h4>A scalpel, not a chainsaw: what include_contents doesn’t isolate</h4><blockquote>two gotchas to aid in your debugging adventures</blockquote><ol><li><strong>Not a global setting:</strong> The include_contents parameter applies only to the individual agent on which it is set. It determines whether <em>that specific agent</em> will receive the session history (conversation history) included in its input context when called. This means if you set the include_contents parameter on an LLM agent but omit it on a downstream LLM agent, the conversation history will appear in the second LLM agent’s input context.</li><li><strong>Not a complete sandbox:</strong> From our observations and <a href="https://github.com/google/adk-python/issues/2207">user-reported issues</a>, the include_contents parameter only prunes the historical context from previous turns (session.events). It does <em>not</em> isolate the agent from context generated by other sub-agents <em>within the same invocation</em> (e.g., in a SequentialAgent). Data passed via session.state remains fully accessible. This makes it a <em>scalpel</em> for removing long-term history, but not a complete sandbox for isolating a single turn.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*b2Iw7iTmA7eCoam58T-d1g.png" /><figcaption>The <strong>include_contents</strong> parameter only prunes the historical context from previous turns, not context generated by other sub-agents within the same invocation (e.g., in a SequentialAgent). Additionally, it only applies to the individual agent on which it is set.</figcaption></figure><h3>Conclusion</h3><p>In this article we reviewed techniques to improve performance across agent design, tool definition, and context engineering. Let’s recap the 4 major performance drivers:</p><h4>Optimization #1: Enforcing Single Responsibility Principle (SRP)</h4><p><strong>The Problem:</strong> Combining two relatively complex tasks into one LLM call<br><strong>The Fix:</strong> Enforce SRP</p><ul><li><strong>Agent 1 (Drafter):</strong> Creative</li><li><strong>Agent 2 (Critic):</strong> Analytical/Technical</li><li><strong>Agent 3 (Selector):</strong> Strategic</li></ul><p><strong>The Result:</strong> By separating, the selection agent gets to see the best possible version of each idea before making the final cut<br><strong>The Bottom line:</strong> applying SRP to the design of ADK agents, tools, and the logic for context engineering leads to more modular, manageable, and effective agentic systems</p><h4>Optimization #2: Structured Output: Mandate Machine-Readability</h4><ul><li><strong>The Win:</strong> The single biggest performance improvement for a tool-chaining agent</li><li><strong>The Benefit:</strong> Eliminates complex parsing logic and reduces the chance of hallucination</li><li><strong>The Bottom line:</strong> If you are passing anything other than a block of text to a downstream task, create a class and pass it to the <strong><em>output_schema</em></strong></li></ul><h4>Optimization #3: Direct Injection: Put the Context Where the LLM Can See It</h4><ul><li><strong>Concept: </strong>The LLM Agent can only see what’s in its prompt (specifically the &lt;CONTEXT&gt; block), not the external session state keys</li><li><strong>Action: </strong>The Orchestrator must inject the data from state keys into the prompt’s &lt;CONTEXT&gt; block</li><li><strong>The Instruction: </strong>The LLM should be instructed to read from the &lt;CONTEXT&gt; block, not the session state key</li><li><strong>Key Benefit: </strong>Allows us to use session state as an effective communication bus for passing data between steps</li></ul><h4>Optimization #4: Active Input Management: Pruning the Context Tree</h4><ul><li><strong>Concept: </strong>By default, frameworks often bloat the prompt with <em>ambient context</em> (full session history, irrelevant state, previous logs, all tool invocations). This costs tokens and time</li><li><strong>Action: </strong>Set include_contents=&quot;none&quot; for any LLM agent needing context isolation</li><li><strong>The Why: </strong>This tells the framework: <em>Only pass the system prompt (Role, Instructions) and the data I explicitly inject via the inputs/context blocks</em></li><li><strong>The Result: </strong>The agent focuses solely on the structured inputs you provided via direct injection, leading to maximum performance, predictability, and cost-efficiency</li></ul><blockquote>Did any of these give you a performance boost? Let me know in the comments or reach out via <a href="https://www.linkedin.com/in/jordantotten/">LinkedIn</a>!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1164a1e63ab2" width="1" height="1" alt="">]]></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-e92a11317fd9------2</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>Fri, 21 Jun 2024 20:45:19 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-e92a11317fd9------2</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-e92a11317fd9------2</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 09:56:13 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>