<?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 Tanay Chowdhury on Medium]]></title>
        <description><![CDATA[Stories by Tanay Chowdhury on Medium]]></description>
        <link>https://medium.com/@tanaychowdhury?source=rss-3e6cf0cd7003------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LSTYieSXEdUHBfD_7EUOPw.jpeg</url>
            <title>Stories by Tanay Chowdhury on Medium</title>
            <link>https://medium.com/@tanaychowdhury?source=rss-3e6cf0cd7003------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:32:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanaychowdhury/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[Pairwise Ranking Outperforms Reinforcement Learning for Offline Explanation Selection]]></title>
            <link>https://medium.com/@tanaychowdhury/pairwise-ranking-outperforms-reinforcement-learning-for-offline-explanation-selection-0de8a8729e85?source=rss-3e6cf0cd7003------2</link>
            <guid isPermaLink="false">https://medium.com/p/0de8a8729e85</guid>
            <category><![CDATA[learning-to-rank]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Tanay Chowdhury]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 04:12:37 GMT</pubDate>
            <atom:updated>2026-09-07T04:12:37.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>A practical lesson from building an explainable recommender system: when every candidate action can be scored offline, a simple ranker beats PPO, GRPO, and DPO</h3><p><strong>📄 Accepted to RecSys 2026</strong> (Research &amp; Practice Notes track) · <a href="http://arxiv.org/abs/2608.18531">Paper on arXiv</a> · <a href="https://github.com/amazon-science/XplainRecommendation">Code on GitHub</a></p><p>You’ve seen this before: Netflix tells you a show is “Because you watched <em>Stranger Things</em>.” Amazon says a blender is “Frequently bought with items in your cart.” Yelp tells you a restaurant matches “your taste for cozy, casual spots.”</p><p>That little sentence — the <em>explanation</em> — is doing real work. It’s the difference between a recommendation feeling like a lucky guess and feeling like the system actually gets you. And increasingly, it’s not hand-written. It’s generated by an LLM.</p><p>Here’s the problem nobody talks about: <strong>generating that sentence for every single request is expensive.</strong> If your site gets thousands of requests per second, and each one triggers a live call to an LLM, you’re paying for an LLM inference <em>and</em> eating hundreds of milliseconds of latency, every single time, forever.</p><p>We ran into exactly this problem while building <a href="https://github.com/amazon-science/XplainRecommendation">XplainRecommendation</a>, the code behind our paper, <a href="http://arxiv.org/abs/2608.18531"><em>“Pairwise Ranking Outperforms Single-Action RL for Offline Explanation Selection”</em></a>, accepted to the <strong>RecSys 2026 Research &amp; Practice Notes track</strong>. Along the way we found something we didn’t expect — and it changed how we think about when to reach for reinforcement learning at all.</p><h3>The fix: stop writing on the spot. Write ahead of time, then just pick.</h3><p>Think about how a good restaurant menu works. The chef doesn’t invent a description of the soup fresh for every customer who walks in — the descriptions are already written on the menu. The waiter’s job isn’t to <em>write</em>, it’s to <em>recommend the right dish from what’s already on the menu</em> based on what you tell them you’re in the mood for.</p><p>We applied the same idea to explanations. Instead of calling an LLM live, at the moment someone loads a page, we:</p><ol><li><strong>Ahead of time</strong> (offline, in a batch job, no user waiting): generate a <em>pool</em> of candidate explanations for each user–item pair — using a handful of different prompt styles and a couple of cheap LLMs. Think 40 different attempts at describing the same recommendation.</li><li><strong>At request time</strong>: use a tiny, fast model — not an LLM — to look at those 40 candidates and pick the single best one.</li></ol><p>That second model is what we call the <strong>selector</strong>, or the “picker.” It runs on a CPU, returns an answer in under a millisecond, and needs zero GPU. All the expensive LLM work already happened hours earlier, in bulk, off the clock.</p><p>This alone is a nice engineering trick. But it raises a more interesting question: <strong>what’s the best way to build that picker?</strong></p><h3>Two philosophies for building a picker</h3><p>Once you’ve framed it this way — pick the best option out of a known, fixed set of candidates — there are two natural families of approach:</p><p><strong>Reinforcement learning (RL).</strong> Treat picking as a decision an agent learns to make through trial and reward. Show it a candidate, get a score, nudge the policy toward higher-scoring choices. This is the modern, popular hammer — PPO, GRPO, DPO are all variations on “try things, learn from the reward.”</p><p><strong>Pairwise ranking.</strong> Since every candidate in the pool <em>already has a quality score</em> (we can measure, offline, how close each one is to a real reference explanation), just train a plain ranking model — the same kind of model that’s been sorting search results and ads for twenty years — to rank all 40 candidates and take the top one.</p><p>The RL approach feels more modern and more “AI.” The ranking approach feels almost boring by comparison. We expected the fancier methods to win, or at least be competitive. They weren’t.</p><h3>The result</h3><p>We tested this on 2,958 real (user, business) pairs from Google Local reviews, comparing five methods we trained ourselves against two published systems (XRec and G-Refer), using <strong>BERTScore-F1</strong> as the accuracy metric — essentially, “how close is the picked explanation to what a human would actually say?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OS1UFtqIszXfv_0abF8HSQ.png" /></figure><p>A plain LightGBM ranking model — the same LambdaRank algorithm used in search engines — beat every single RL variant we tried, by a wide and statistically solid margin (the gap is more than 15 times larger than the natural noise between random seeds). It also beat both published baseline systems.</p><p>That’s not a small result. It means that for this task, throwing PPO, GRPO, or DPO at the problem — three separate flavors of reinforcement learning — was strictly worse than just… ranking the options.</p><h3>Why does the “boring” method win?</h3><p>Here’s the intuition, and it’s simpler than it sounds.</p><p>Imagine you’re grading 40 candidate explanations for a single recommendation, and you already know exactly how good each one is (we measured this offline, remember — that’s the whole point of the pool).</p><ul><li><strong>The ranking model gets to see all 40 scores, every single time it trains.</strong> It learns “given these 40 options and their true quality, put the best one first.” Every training example uses the <em>entire</em> pool.</li><li><strong>The RL methods only get to see one option per attempt.</strong> DPO samples a candidate, gets its reward, and updates. Then it samples another. Most of the labeled information sitting right there in the pool — the quality scores of the other 39 candidates — is never used in that update.</li></ul><p>It’s not that RL is a bad algorithm. It’s that <strong>RL is solving a harder problem than we actually had.</strong> RL formulations exist for situations where you <em>don’t</em> know the value of every option upfront — you have to explore and discover it. We weren’t in that situation. We already had every candidate’s score sitting in a table. Reaching for RL here is like exploring a maze with a blindfold on when someone already handed you the map.</p><p><strong>The practical takeaway, if you remember nothing else:</strong> if your problem lets you score every candidate action offline, before training even starts, try a plain ranking model before reaching for RL. It’s cheaper to train, it’s easier to debug, and — at least in our case — it just wins.</p><h3>But nothing is free: the diversity trade-off</h3><p>Here’s the twist. The ranking model doesn’t just win on accuracy — it also becomes the <em>least</em> diverse method. When we measured <strong>Unique-Sentence Ratio (USR)</strong> — literally, “what fraction of the explanations shown across all users are actually different sentences” — the picture flips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qHvTTtBwt5P_LaiCxEbag.png" /></figure><p>LambdaRank is the most accurate and the least diverse. The RL methods sacrifice a bit of accuracy but keep more variety. And a completely different approach we also tested — building explanations by walking a knowledge graph of real review snippets (“KG-path”) — sacrifices accuracy almost entirely, but <em>guarantees</em> every explanation is unique, since each one is grounded in a different, specific graph path.</p><p>Why does the most “accurate” method converge on repetitive answers? Because the safest bet — the explanation closest to what most people would say — tends to be the same handful of generic-but-correct phrasings (“great food, friendly service, cozy atmosphere”) repeated across many similar restaurants. Being right and being interesting aren’t the same objective, and it turns out you can’t fully maximize both with one model.</p><p>If your product needs strict factual grounding, pick the ranker. If your product needs every user to feel like they got something individually written for them, that trade-off might matter more than the accuracy number.</p><h3>Two failure stories worth knowing about</h3><p>We hit two dead ends worth sharing, because they’re the kind of thing you only learn by actually trying:</p><p><strong>Failure 1 — polishing something that’s already good can make it worse.</strong> We took our best distilled model (a smaller model trained to imitate the ranker) and tried to give it a further RL fine-tuning pass, expecting a small extra bump. Instead, performance got <em>worse</em> — a statistically clear regression. Our best explanation: the RL fine-tuning’s exploration pressure pushed a policy that had already converged to a good answer back into “trying new things,” away from the good answer it had already found. Lesson: RL fine-tuning on top of an already-strong model only helps if that model still has real room to improve. Ours didn’t.</p><p><strong>Failure 2 — teaching a model to grade its own homework goes badly, fast.</strong> In a separate experiment, we tried fine-tuning the <em>generator itself</em> end-to-end with reinforcement learning, using our evaluation metric (BERTScore) directly as the reward. Within a few hundred training steps, the model discovered a shortcut: a specific phrase — “user enjoys” — happened to score well against the reference text, regardless of whether it made sense. So it started repeating that phrase everywhere. Technically, the reward went up. Practically, the outputs became useless. This is a textbook case of <strong>reward hacking</strong> — optimize a proxy metric hard enough, and the model will cheerfully break whatever that metric was supposed to measure. Decoupling generation from selection (our original design) sidesteps this failure mode entirely, because the generator is never inside the training loop in the first place.</p><h3>What we’re releasing</h3><p>Everything — the pipeline, the pool-generation code, all the selector variants (LambdaRank, PPO, GRPO, DPO, distillation), and the knowledge-graph path family — is open source:</p><p>👉 <strong>Code:</strong> <a href="https://github.com/amazon-science/XplainRecommendation">github.com/amazon-science/XplainRecommendation</a> 👉 <strong>Paper:</strong> <a href="http://arxiv.org/abs/2608.18531">arXiv:2608.18531</a> — accepted to <strong>RecSys 2026</strong> (Research &amp; Practice Notes track)</p><p>It’s released as paper code (CC-BY-NC-4.0) specifically to support reproducing the results in the paper — the whole pipeline runs CPU-only at inference time, and rebuilding the entire candidate pool from scratch costs about $15 in LLM API spend.</p><p>If you’re building anything where an LLM writes something at serving time — explanations, summaries, personalized copy — and you’re paying for a live generation call on every request, ask yourself the question this project is really about: <strong>do you actually need to generate this on the fly, or could you generate a handful of good options ahead of time and just pick?</strong> It’s a smaller architecture change than it sounds like, and in our case, it was also the more accurate one.</p><p><em>This work was done by Tanay Chowdhury and Saeideh Shahrokh Esfahani (equal contribution), and is accompanied by a paper accepted to the RecSys 2026 Research &amp; Practice Notes track.</em></p><p><strong>If you’d like to cite this work:</strong></p><pre>@inproceedings{chowdhury2026pairwise,<br>  title     = {Pairwise Ranking Outperforms Single-Action RL for Offline Explanation Selection: A Practical Lesson},<br>  author    = {Chowdhury, Tanay and Shahrokh Esfahani, Saeideh},<br>  booktitle = {Proceedings of the 20th ACM Conference on Recommender Systems (RecSys &#39;26), Research and Practice Notes},<br>  year      = {2026}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0de8a8729e85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open AI Dev day updates]]></title>
            <link>https://medium.com/@tanaychowdhury/open-ai-dev-day-updates-d8441cfa25da?source=rss-3e6cf0cd7003------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8441cfa25da</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Tanay Chowdhury]]></dc:creator>
            <pubDate>Thu, 09 Nov 2023 05:44:56 GMT</pubDate>
            <atom:updated>2023-11-09T06:23:35.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nzc_qLMCtg2COObR2rzW3A.png" /></figure><p>Being in the LLM space, like all of you I too was very excited about the announcements made in the Open AI dev day by Sam Altman (CEO — Open AI). If you want to follow the video you can do so from <a href="https://www.youtube.com/watch?v=U9mJuUkhUzk">here</a>. However I did that to save the time for some of you and here is list of all the exciting updates provided there.</p><ol><li><strong>Context length : </strong><br>So far GPT-4 supported 8k-32k context length. GPT-4 turbo will support 128k context length. Which is 300 pages of a standard book!</li><li><strong>More control :</strong> Developer will have have more control<br>i) json mode : Which ensures that model will respond with valid json.<br>ii) function calling : Model can do many function calling at once.<br>iii) reproducible outputs : You can pass seed parameter and model can generate reproducible output.Rolled out in beta on 11/06.<br>iv) view log probabilities : Developer can see log probabilities in api. Rolls out in coming weeks.</li><li><strong>Better world knowledge :</strong><br>i) You can bring knowledge from outside documents or database into whatever you are building.<br>ii) Updated knowledge cut-off from September 2021 to April 2023 for GPT-4, and will continue to improve.</li><li><strong>New modalities :</strong><br>i) DALLE3, GPT-4 with vision and Text-to-Speech(TTS) all are going to api on 11/06.<br>ii) GPT-4 turbo can accept images as input via the api, and can generate captions, classifications and analysis.<br>iii) Text-to-speech (TTS) can generate incredibly natural sounding audio, from text in the api with 6 preset voices to choose from.<br>iv) Whisper V3 is released and will soon be coming to api.</li><li><strong>Customization :</strong><br>i) Fine tuning will extend to 16k version of the GPT-3 model.<br>ii) Invited developers for the experimental access program for GPT-4 fine tuning.<br>iii) Custom model is launched where OpenAI developers will work with companies to fine tune model for their data and need, and that includes<br> a. Doing additional domain specific pre-training.<br> b. A custom RL post training process tailored for specific domain and whatever else.<br> c. It will be scaled over time so that many companies can go for it.</li><li><strong>Higher rate limits :</strong><br>i. They are doubling the tokens per minute for all of their established GPT-4 customers.<br>ii. Also customers can request further rate limit increase.<br>iii. Copy right shield : They will step in and defend their customers and pay the costs incurred if they face legal claims or copyright infringement for both ChatGPT enterprise or the API. Also they said that they do not train on your data from the API or ChatGPT Enterprise, ever.</li></ol><p><strong>Pricing</strong><br>GPT-4 Turbo is considerably cheaper than GPT-4 by a factor of 3x for prompt tokens and 2x for output tokens.Which is 1 cent/1000 input tokens and 3 cent/1000 outputs tokens.<br>Which makes GPT-4 turbo almost 2.75x cheaper than GPT-4 for most customers.</p><p>GPT-3.5 Turbo 16k will be cheaper than GPT-3.5 Turbo 4k by a factor of 3x for prompt tokens and 2x for output tokens..Which is 0.3 cent/1000 input tokens and 0.4 cent/1000 outputs tokens.</p><p>Fine tuned GPT-3.5 Turbo 4k will be 1.2 cents/1000 tokens for input tokens (3x less) and 1.6 cents/1000 tokens for output tokens (2x less).<br>Fine tuned GPT-3.5 Turbo 16k will be 0.3 cents/1000 tokens for input tokens (4x less) and 0.6 cents/1000 tokens for output tokens (2.7x less).</p><p><strong>GPTs</strong></p><p>GPTs are customized version of ChatGPT for almost anything with instruction, expanded knowledge and actions. It can be programmed just by talking to it. A GPT store will launch soon that will store all GPTs.</p><p><strong>API</strong></p><p>Assistance API : It includes persistent api to take care of long conversation history. It’ll also facilitate threading, retrieval, code interpreter and function calling. It went to beta on 11/06.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8441cfa25da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Step Function Inference pipeline for Time Series Forecasting model]]></title>
            <link>https://medium.com/analytics-vidhya/aws-step-function-inference-pipeline-for-time-series-forecasting-model-9d5cc3121f88?source=rss-3e6cf0cd7003------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d5cc3121f88</guid>
            <category><![CDATA[step-functions]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Tanay Chowdhury]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 21:28:38 GMT</pubDate>
            <atom:updated>2026-09-07T04:53:39.829Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://medium.com/@tanaychowdhury/aws-step-function-pipeline-for-time-series-forecasting-model-using-tensorflow-d993abc10ddc">article</a> I covered how we can create a training pipeline to train Tensorflow model on time series data and create a SageMaker endpoint from that. In this article I’ll explain how to invoke the endpoint through an end-to-end pipeline.</p><p>The AWS Step Function pipeline looks as following. In this pipeline step function orchestrate the workflow by calling AWS s3, AWS Athena , AWS SageMaker and AWS Lambda services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heNDup8ZI0n3PEgsV-_XCA.png" /></figure><p>We need to import following libraries for that.</p><pre>from stepfunctions.steps import *<br>from stepfunctions.inputs import ExecutionInput<br>from stepfunctions.workflow import Workflow<br>import time</pre><p>We also need to create an <em>execution_input </em>for the input features to kick off the inference pipeline.</p><pre>execution_input = ExecutionInput(<br>schema={<br>&quot;bucketName&quot;:str,<br>&quot;srcSqlFile&quot;: str,<br>&quot;endpointName&quot;: str,<br>&quot;tgtBucket&quot; : str,<br>&quot;tgtKey&quot;: str<br>}<br>)</pre><p>Run source sql for inference data : The is accomplished by creating a lambda function and eventually calling it from step function. Following is the code for the lambda function <em>ds-StartQueryExecution. </em>The function reads the sql file from a s3 location and runs the sql using <em>start_query_execution</em> api.Following is the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/746062afa6173b7ac2b32c176200f6dd/href">https://medium.com/media/746062afa6173b7ac2b32c176200f6dd/href</a></iframe><p>We call this lambda function in step function using following code, where <em>LambdaStep</em> invokes the lambda function and <em>Catch</em> step catches the failure and <em>Retry</em> reties the step in case of failure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e40de6d7889389010affd9fa6c72fca2/href">https://medium.com/media/e40de6d7889389010affd9fa6c72fca2/href</a></iframe><p>The sql fired could be long running sql, so to track that we need do following tasks.</p><p>Wait for source sql execution : Create a Wait step in Step function.</p><pre>from stepfunctions.steps import Wait<br>wait_src_query_execution_job =  Wait(state_id=&quot;Wait for source sql execution - 30 sec&quot;,seconds=30)</pre><p>Check for source sql job : As the sql can run longer, its running status need to checked using a lambda function called <em>ds-GetQueryExecution </em>using<em> get_query_execution </em>api<em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3f6c17f355ea68635b3f37961be871/href">https://medium.com/media/6f3f6c17f355ea68635b3f37961be871/href</a></iframe><p>This function is invoked in step function with following code. In this code the <em>QueryExecutionId </em>tracks sql inside AWS Athena, as well as &lt;<em>QueryExecutionId&gt;.csv </em>becomes the output file name that gets stored in s3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d70373a7e266d7355a2822a5552527c9/href">https://medium.com/media/d70373a7e266d7355a2822a5552527c9/href</a></iframe><p>Isthe source sql execution complete : In case of long running sql eventually we need to check whether the sql execution completed. If not the wait loop will continue. Below is the declaration of the step ( This code would have further addition later for the sake of variable discoverability).</p><pre>from stepfunctions.steps import Choice<br>check_src_sql_run_choice_state = Choice(state_id = &quot;Is the source sql execution complete?&quot;)</pre><p>Run inference job : Now that we have all the data we need with us we will process the data in the similar way that we did for training data using a lambda function, and once the data is processed we’ll call SageMaker endpoint with that data. Here is the code for the lambda function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45c3ba48915594b0c58e433ba270479a/href">https://medium.com/media/45c3ba48915594b0c58e433ba270479a/href</a></iframe><p>That lambda function is invoked using following Step function code with corresponding error handling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eec2801bf68f1e552ec79fcc7aefd16/href">https://medium.com/media/2eec2801bf68f1e552ec79fcc7aefd16/href</a></iframe><p>Now that all the downstream tasks are defined we can define the <em>check_src_sql_run_choice_state</em> <em>Choice</em> step using following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e81c7be3b9de6534b54adcb8d6b1c61/href">https://medium.com/media/5e81c7be3b9de6534b54adcb8d6b1c61/href</a></iframe><p>Now that we have defined all tasks, it’s time to chain them up to create the sequential structure in workflow. The last step <em>lambda_state_inference_job </em>isn’t chained as it is referenced by <em>check_src_sql_run_choice_state.</em></p><pre>inference_workflow_definition= Chain([<br>lambda_state_start_src_query,<br>wait_src_query_execution_job,<br>lambda_get_src_query_execution_status,<br>check_src_sql_run_choice_state<br>])</pre><p>Once the workflow definition is created it is time to create the workflow and render it to see whether it looks as planned.</p><pre>getvisittime_inference_workflow = Workflow(<br>name=&quot;ds-GetVisitTime-Inference-Workflow&quot;,<br>definition=inference_workflow_definition,<br>role=role_arn<br>)</pre><pre>getvisittime_inference_workflow.render_graph()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ya5Ln5cx4pxkqKlDJeOhlA.png" /></figure><p>We can now physically create this workflow using following code</p><pre>getvisittime_inference_workflow.create()</pre><p>or can update it using following code</p><pre>getvisittime_inference_workflow.update(definition=inference_workflow_definition,role=role_arn)</pre><p>In either case we should make the script wait for 30 seconds before these changes are updated in AWS end. We can enforce that with following code.</p><pre>time.sleep(30)</pre><p>Given that this workflow doesn’t have a component that requires a variable task name for each run, this workflow can be called from SageMaker Notebook, local jupyter notebook or from AWS CloudWatch Event as is. Below is the code.</p><pre>getvisittime_inference_workflow.execute(inputs={<br>&quot;bucketName&quot;: script_bucket,<br>&quot;srcSqlFile&quot;: src_sql_file,<br>&quot;endpointName&quot;: endpoint_name,<br>&quot;tgtBucket&quot; : script_bucket,<br>&quot;tgtKey&quot;: tgt_key<br>})</pre><p>How to cite this post</p><blockquote>Tanay Chowdhury, “AWS Step Function Inference Pipeline for Time Series Forecasting Model,” Analytics Vidhya (Medium), Jul 26, 2021. <a href="https://medium.com/analytics-vidhya/aws-step-function-inference-pipeline-for-time-series-forecasting-model-9d5cc3121f88">https://medium.com/analytics-vidhya/aws-step-function-inference-pipeline-for-time-series-forecasting-model-9d5cc3121f88</a></blockquote><p><strong>BibTeX:</strong></p><pre>@misc{chowdhury2021stepfunction,<br>  title  = {AWS Step Function Inference Pipeline for Time Series Forecasting Model},<br>  author = {Chowdhury, Tanay},<br>  year   = {2021},<br>  month  = {jul},<br>  note   = {Analytics Vidhya, Medium},<br>  url    = {https://medium.com/analytics-vidhya/aws-step-function-inference-pipeline-for-time-series-forecasting-model-9d5cc3121f88}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d5cc3121f88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/aws-step-function-inference-pipeline-for-time-series-forecasting-model-9d5cc3121f88">AWS Step Function Inference pipeline for Time Series Forecasting model</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Step Function Training Pipeline for Time series forecasting model using Tensorflow]]></title>
            <link>https://medium.com/geekculture/aws-step-function-pipeline-for-time-series-forecasting-model-using-tensorflow-d993abc10ddc?source=rss-3e6cf0cd7003------2</link>
            <guid isPermaLink="false">https://medium.com/p/d993abc10ddc</guid>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Tanay Chowdhury]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 08:40:32 GMT</pubDate>
            <atom:updated>2026-09-07T04:52:05.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Q7R9cVkdovxo1ZN-Wb4JjQ.jpeg" /></figure><p>I work with a recommendation engine that recommends the food recipe for a user and we send that using push notification to the user. However different users use the app during different time of the day and that too varies over a week and month. As part of this work I’ve created a deep learning model that could predict on a given day when the user is most likely to use the app. In this 2 part article I’ll emphasize more on that deep learning pipeline building part where part 1 covers the training pipeline and <a href="https://medium.com/@tanaychowdhury/aws-step-function-inference-pipeline-for-time-series-forecasting-model-9d5cc3121f88">part 2</a> covers the inferencing pipeline.</p><p>The end-to-end training pipeline will fetch the source data using sql, pre-process the data ,train a Tensorflow GRU model with the data and will create/update a SageMaker endpoint using the model.</p><h3>Features</h3><p>As part of this study my hypothesis is that the following list of features can help predict that on a certain date when a user will use the app. The features can be categorized in to 2 categories.</p><h4>Current features</h4><p>All these features should be calculated on the day of inference.</p><p><em>Day of the week </em>: Day of week of inferencing the hour of visit. <br><em>Day of the month </em>: Day of month of inferencing the hour of visit.<br><em>Day since last visit</em> : Number of days since last visit.</p><h4>Historical features</h4><p>All these features belong to the last usage of the user.</p><p><em>Total time spent</em> : Total time spent by the user in last visit.<br><em>Total page views</em> : Total number of page views by the user in last visit.<br><em>Type 1 page views</em> : Total # type 1 page views by the user in last visit.<br><em>Type 2 page views</em> : Total # type 2 page views by the user in last visit.<br><em>Type 3 page views</em> : Total # type 3 page views by the user in last visit.<br><em>Type 4 page views</em> : Total # type 4 page views by the user in last visit.<br><em>First visit hour</em> : The first visit hour of the day during the last visit.<br><em>Last visit hour </em>: The last visit hour of the day during the last visit.<br><em>Hourly num of visits</em> : Flag to determine if the hit is a new hourly visitor.<br><em>Day of the week</em> : Day of week of the last visit.<br><em>Day of the month</em> : Day of month of the last visit.<br><em>Month of the year </em>: Month of the year of the last visit.<br><em>Platform</em> : Users platform for last visit such as iOS or android or others.</p><h3><strong>Training Pipeline</strong></h3><p>The end-to-end training pipeline shown below is created using AWS Step function, which is a visual workflow service to automate AWS services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*le3OTJhYAfEo7HhLKIJRfQ.png" /></figure><p>As a note I use <a href="https://aws-step-functions-data-science-sdk.readthedocs.io/en/stable/">AWS Step Functions Data Science Python SDK</a> to create the workflow definition for AWS step function. AWS Step function will orchestrate the workflow by connecting to AWS Athena, AWS s3, AWS Lambda and AWS SageMaker services. Other than the code for AWS lambda all the python code discussed below has to be run either from a SageMaker notebook or a local jupyter python notebook.</p><p>All the libraries and environment variables are declared below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bf13c48cead50bffd296810f874279f/href">https://medium.com/media/9bf13c48cead50bffd296810f874279f/href</a></iframe><p>For the workflow to run with user input we need to define following values beforehand.</p><pre>execution_input = ExecutionInput(<br>schema={<br>&quot;PreprocessingJobName&quot;: str,<br>&quot;TrainingJobName&quot;: str,<br>&quot;EvaluationProcessingJobName&quot;: str,<br>&quot;ModelName&quot;: str,<br>&quot;EndpointName&quot;: str,<br>&quot;InputFilePath&quot;: str<br>})</pre><p><strong>Run source sql for training data: </strong>The is accomplished by creating a lambda function and eventually calling it from step function. Following is the code for the lambda function <em>ds-StartQueryExecution. </em>The function reads the sql file from a s3 location and runs the sql using <em>start_query_execution</em> api.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/746062afa6173b7ac2b32c176200f6dd/href">https://medium.com/media/746062afa6173b7ac2b32c176200f6dd/href</a></iframe><p>We call this lambda function in step function using following code, where <em>LambdaStep</em> invokes the lambda function and <em>Catch</em> step catches the failure and <em>Retry</em> reties the step in case of failure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/466e90c1e473b6bea2a4b54c541f4bc2/href">https://medium.com/media/466e90c1e473b6bea2a4b54c541f4bc2/href</a></iframe><p>The sql fired could be long running sql, so to track that we need do following tasks.</p><p>Wait for source sql execution : Create a Wait step in Step function.</p><pre>from stepfunctions.steps import Wait<br>wait_src_query_execution_job =  Wait(state_id=&quot;Wait for source sql execution - 30 sec&quot;,seconds=30)</pre><p>Check for source sql job : As the sql can run longer, its running status need to checked using a lambda function called <em>ds-GetQueryExecution </em>using<em> get_query_execution </em>api<em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3f6c17f355ea68635b3f37961be871/href">https://medium.com/media/6f3f6c17f355ea68635b3f37961be871/href</a></iframe><p>This function is invoked in step function with following code. In this code the <em>QueryExecutionId </em>tracks sql inside AWS Athena, as well as &lt;<em>QueryExecutionId&gt;.csv </em>becomes the output file name that gets stored in s3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d61cc2f185699fbb806e39e2c2aeddf/href">https://medium.com/media/8d61cc2f185699fbb806e39e2c2aeddf/href</a></iframe><p>Is the source sql execution complete : In case of long running sql eventually we need to check whether the sql execution completed. If not the wait loop will continue. Below is the declaration of the step ( This code would have further addition later for the sake of variable discoverability).</p><pre>from stepfunctions.steps import Choice<br>check_src_sql_run_choice_state = Choice(state_id = &quot;Is the source sql execution complete?&quot;)</pre><p>Copy source file to s3 : I came up with this step as I couldn’t pass a variable file name to downstream ML pipeline script. This step is dependent on lambda function <em>ds-CopyS3Content </em>and below is the code for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e47ba416951962848a9451ea1143ecb/href">https://medium.com/media/5e47ba416951962848a9451ea1143ecb/href</a></iframe><p>Here is the step function code to invoke the lambda function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df0a955d2f0848e21d431c67d88dd187/href">https://medium.com/media/df0a955d2f0848e21d431c67d88dd187/href</a></iframe><p>Also now that all the downstream tasks are defined we can finally code the Choice state that waits for input sql to complete and upon success starts copying the data to s3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07034a4c679f15af4049f3108d9beadd/href">https://medium.com/media/07034a4c679f15af4049f3108d9beadd/href</a></iframe><p>SageMaker pre-processing step : With the input data at our disposal we can start pre-processing it.</p><p>The 1st step to do that is to run the scikit-learn preprocessing script as a processing job, create a <em>SKLearnProcessor</em>, which lets you run scripts inside of processing jobs using the scikit-learn image provided by AWS SageMaker.</p><pre>sklearn_processor = SKLearnProcessor(<br>framework_version=&quot;0.20.0&quot;,<br>role=role_arn,<br>instance_type=&quot;ml.m5.xlarge&quot;,<br>instance_count=1,<br>max_runtime_in_seconds=1500,<br>)</pre><p>The 2nd step is to create a pre-processing script that would run inside SageMaker docker using <a href="https://aws.amazon.com/blogs/machine-learning/using-tensorflow-eager-execution-with-amazon-sagemaker-script-mode/">SageMaker script mode</a>. Like earlier python code this code snippet when run in jupyter creates a local python file <em>preprocessing_step.py</em> at given location using <em>%%writefile</em> jupyter command.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48f824d5f670d798ff890d7a19d78fbf/href">https://medium.com/media/48f824d5f670d798ff890d7a19d78fbf/href</a></iframe><p>This python script is created in a different location, so to transfer this we need following jupyter code. The code will also set the path for input and output during execution of this code inside SageMaker docker.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9ceffc5a69bb7752d200f50865213a8/href">https://medium.com/media/d9ceffc5a69bb7752d200f50865213a8/href</a></iframe><p>Eventually all these will be invoked by PreProcessingStep inside step function with following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f01d5045b0d9e4fc7b376567e7f4da37/href">https://medium.com/media/f01d5045b0d9e4fc7b376567e7f4da37/href</a></iframe><p>SageMaker Training Step : For training the model using the pre-processed data I again leveraged <a href="https://aws.amazon.com/blogs/machine-learning/using-tensorflow-eager-execution-with-amazon-sagemaker-script-mode/">SageMaker Script mode</a> and created following local python script called <em>training_step.py</em> using jupyter code block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ddfe609965afc889e0b9533c66b627/href">https://medium.com/media/98ddfe609965afc889e0b9533c66b627/href</a></iframe><p>Like earlier this script is created locally and hence to transfer it in s3 following code needs to be run.</p><pre>TRAINING_SCRIPT_LOCATION = &#39;get-visit-time/training_step.py&#39;</pre><pre>training_code = sagemaker_session.upload_data(<br>TRAINING_SCRIPT_LOCATION,<br>bucket=default_bucket,<br>key_prefix=&quot;get-visit-time/scripts&quot;,<br>)</pre><p>This script needs to be wrapped in a Tensorflow estimator provided by SageMaker using following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9be0243f3c0e83f4922834c9ffa56817/href">https://medium.com/media/9be0243f3c0e83f4922834c9ffa56817/href</a></iframe><p>This estimator is eventually called by a <em>TrainingStep</em> in Step Function and should be error handled using <em>Fail</em> step using following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f053820c50e6b7cc72efdbc61ba7a13/href">https://medium.com/media/1f053820c50e6b7cc72efdbc61ba7a13/href</a></iframe><p>Save Model : The model is saved here using following code</p><pre>model_step = ModelStep(<br>&quot;Save model&quot;, model=training_step.get_expected_model(), model_name=execution_input[&quot;ModelName&quot;],<br>instance_type=&quot;ml.m5.xlarge&quot;<br>)</pre><p>Create/Update Endpoint : Although the model is saved in previous step for sanity checking, we would rather create an endpoint for inferencing, and would update that during re-training using following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f2f8e0837695c14ca0c497cad621e24/href">https://medium.com/media/5f2f8e0837695c14ca0c497cad621e24/href</a></iframe><p>Once all of these individual tasks are created we need to add error handling <em>Catch</em> step to all of those using following code.</p><pre>catch_state_processing = Catch(<br>error_equals=[&quot;States.TaskFailed&quot;],<br>next_step=failed_state_sagemaker_processing_failure,<br>)</pre><pre>processing_step.add_catch(catch_state_processing)<br>training_step.add_catch(catch_state_processing)<br>model_step.add_catch(catch_state_processing)<br>endpoint_config_step.add_catch(catch_state_processing)<br>endpoint_step.add_catch(catch_state_processing)</pre><p>Now to create the full workflow 1st 4 tasks are chained using following code and that culminates into Choice state <em>check_src_sql_run_choice_state.</em></p><pre>full_workflow_graph= Chain([lambda_state_start_src_query,<br>                            wait_src_query_execution_job,<br>                            lambda_get_src_query_execution_status,<br>                            check_src_sql_run_choice_state<br>                            ])</pre><p>Upon Success the choice state points to <em>lambda_state_copy_source_s3_file_job.<br></em>Since choice state can’t be chained in step function we create another chain with <em>lambda_state_copy_source_s3_file_job </em>as the 1st task in the collection of tasks using following code.</p><pre>train_workflow_graph = Chain([lambda_state_copy_source_s3_file_job,<br>                              processing_step,<br>                              training_step,<br>                              model_step,<br>                              endpoint_config_step,<br>                              endpoint_step<br>                              ])</pre><p>Finally we define the workflow with following code.</p><pre>full_workflow = Workflow(<br>name=&quot;ds-GetVisitTime-Train-Workflow&quot;,<br>definition=full_workflow_graph,<br>role=role_arn,<br>)</pre><p>We can render the workflow definition using this code. This is a good way to validate whether your workflow is defined as thought.</p><pre>full_workflow.render_graph()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgeJanVTzLmN8Wef9HhwGw.png" /></figure><p>After this if we are creating the workflow for the 1st time we should run</p><pre>full_workflow.create()</pre><p>and for updating it we should run</p><pre>full_workflow.update(definition=full_workflow_graph,role=role_arn)</pre><p>we can execute the workflow immediately, however for the sync to happen with AWS it is better to make the code wait 30 seconds using following code.</p><pre>time.sleep(30)</pre><p>We can run the workflow directly from notebook using following code, where we need to use <em>uuid</em> library to generate unique names for SageMaker Preprocessing and Training job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd601710e309e87002af84d659d122fa/href">https://medium.com/media/fd601710e309e87002af84d659d122fa/href</a></iframe><p>However it is more realistic to schedule this in Production using a lambda function (<a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/Create-CloudWatch-Events-Scheduled-Rule.html">Calling the lambda function from AWS CloudWatch events</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c43f4e8204e72e07450657ab4f291ad/href">https://medium.com/media/8c43f4e8204e72e07450657ab4f291ad/href</a></iframe><p>The progress of the state machine execution could be found from AWS Step function console or from jupyter notebook using following command.</p><pre>execution.render_progress()</pre><p>This completes the end-to-end training process to fetch source data to create/update endpoint after training the model and inference using the model built here can be found in the <a href="https://medium.com/@tanaychowdhury/aws-step-function-inference-pipeline-for-time-series-forecasting-model-9d5cc3121f88">part 2</a> of this article. However this training pipeline can further be optimized to do following tasks.</p><ol><li>Run cross validation on training dataset.</li><li>Update the endpoint only when RMSE or MAE is better than certain threshold value.</li></ol><p><strong>If you’d like to cite this post:<br></strong><em>Tanay Chowdhury, “AWS Step Function Pipeline for Time Series Forecasting Model Using TensorFlow,” </em>Geek Culture<em> (Medium), Jul 26, 2021. </em><a href="https://medium.com/geekculture/aws-step-function-pipeline-for-time-series-forecasting-model-using-tensorflow-d993abc10ddc"><em>https://medium.com/geekculture/aws-step-function-pipeline-for-time-series-forecasting-model-using-tensorflow-d993abc10ddc</em></a></p><p><strong>BibTeX:</strong></p><pre>@misc{chowdhury2021stepfunctiontf,<br>  title  = {AWS Step Function Pipeline for Time Series Forecasting Model Using TensorFlow},<br>  author = {Chowdhury, Tanay},<br>  year   = {2021},<br>  month  = {jul},<br>  note   = {Geek Culture, Medium},<br>  url    = {https://medium.com/geekculture/aws-step-function-pipeline-for-time-series-forecasting-model-using-tensorflow-d993abc10ddc}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d993abc10ddc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/aws-step-function-pipeline-for-time-series-forecasting-model-using-tensorflow-d993abc10ddc">AWS Step Function Training Pipeline for Time series forecasting model using Tensorflow</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>