<?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 Pankaj Merisha on Medium]]></title>
        <description><![CDATA[Stories by Pankaj Merisha on Medium]]></description>
        <link>https://medium.com/@pankajmerisha?source=rss-414802f5960b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KfLi2ggZYRk4xFpA</url>
            <title>Stories by Pankaj Merisha on Medium</title>
            <link>https://medium.com/@pankajmerisha?source=rss-414802f5960b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:33:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pankajmerisha/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[From 10 Billion Rows to a 25-Minute Training Loop: Contextual Bandits in Production]]></title>
            <link>https://engg.inmobi.com/from-10-billion-rows-to-a-25-minute-training-loop-contextual-bandits-in-production-eaa9ae50c866?source=rss-414802f5960b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaa9ae50c866</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Pankaj Merisha]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 11:47:34 GMT</pubDate>
            <atom:updated>2026-06-08T13:31:25.702Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How InMobi’s ads team wrestled a decades-old machine learning library into a modern cloud training pipeline — and what we learned the hard way.</em></p><p>Imagine you’re running a casino with n slot machines. Each pays out at a different rate, and you don’t know which ones are best. Your job is to find out as fast as possible — without losing too much money while you figure it out.</p><p>This is, roughly speaking, the problem our team was solving for advertisers. Except instead of slot machines, we had n different bid price multipliers. And instead of one casino, we had millions of them — one for every unique combination of app, country, ad exchange, operating system, ad format, and device type.</p><p>We call each unique combination a <strong>segment</strong>. A segment might be “US users, Android phones, gaming apps, banner ads.” Every segment has its own sweet spot: the bid level where the advertiser wins enough auctions without overpaying. Get it right and the budget stretches further. Get it wrong and you’re either burning money on easy wins, or losing auctions you actually wanted.</p><p>The algorithm we used is called a <strong>Contextual Bandit</strong> — specifically, an open-source library called Vowpal Wabbit (VW). What followed was one of the more instructive engineering journeys of our careers.</p><h3>The Business Problem: Real-Time Auction Bidding</h3><p>When someone opens an app, a real-time auction runs in milliseconds. Publishers use <strong>ad exchanges</strong> — real-time marketplaces — to sell the right to show an ad to that user. Advertisers submit bids. The highest bidder wins and pays exactly their bid (first-price auction).</p><p>As the platform operating on behalf of advertisers, we control the bid. Our base bid for any given user/app/placement comes from click-rate and conversion-rate prediction models. But “is this the right bid level for <em>this specific market segment</em>?” is a harder question — the one the contextual bandit answers.</p><p>We defined <strong>n bid multipliers</strong>: 0.25×, 0.30×, 0.50×, 0.65×, 0.75×, 0.90×, 1.0×, 1.25×, 1.50×, 1.75×, 2.0×, 2.5×, 3.0×, 4.0×, 5.0×. Applied to the base bid, these scale our aggressiveness in each segment. The bandit’s job: for each segment, learn which multiplier achieves the right win rate without overspending.</p><h3>What Is a Contextual Bandit?</h3><p>The slot machine problem above is the classic <strong>multi-armed bandit</strong>: you pull arms, observe rewards, and gradually learn which arms pay best. The “contextual” part means you have <em>information before each pull</em> — context about the user, the app, the time of day — and you use that to make smarter choices instead of treating every pull the same.</p><p>In our case:</p><ul><li><strong>Context</strong> = features of the ad opportunity: country, app bundle, OS, ad format, exchange, hour of day</li><li><strong>Arms</strong> = the n bid multipliers (0.25× through 5.0×)</li><li><strong>Reward</strong> = whether we won the auction and at what cost</li></ul><p>The key challenge: you only ever observe the reward for the arm you <em>chose</em>. You bid 0.90×, you win or lose — you never know what would have happened at 1.25×. The model has to learn from this <strong>partial feedback</strong> — one outcome per auction — rather than seeing all arm outcomes simultaneously. This is the fundamental bandit problem.</p><p><strong>Vowpal Wabbit</strong> is an open-source library originally built at Yahoo! Research, later adopted by Microsoft Research. Designed for large-scale online learning — reading examples one at a time, updating weights, moving on — it has native support for contextual bandit problems, importance-weighted training, and several exploration strategies. It’s also, as we discovered, a surprisingly demanding collaborator.</p><h3>System Architecture: The Big Picture</h3><p>Before diving into each engineering problem, here’s the complete system. Every piece of complexity in this article exists to make this pipeline run reliably every hour at production scale. <em>(Note: this diagram describes the V1 system, where the n arms are relative bid multipliers. The arm design later evolved to n absolute price ranges — that evolution is covered later in the article.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uq72J7HAD0TaKG57HGehpQ.png" /></figure><p>Five steps, running every hour. The rest of this article is the story of how we made each step work.</p><h3>The Scale Problem: 10 Billion Training Examples Per Day</h3><p>Our ad system participates in hundreds of millions of real-time auctions every day. Every auction running through the exploration system produces a training signal: we chose a bid multiplier, we won or lost, and that result needs to feed back into the model.</p><p>By end of day: <strong>~10 billion training examples</strong>.</p><p>VW is a sequential learner — it reads data line by line, one example at a time. Running VW on 10 billion lines would take days. We needed it to run in under an hour.</p><h4>The Fix: Aggregate First, Then Train</h4><p>The key insight: most of those 10 billion events are repetitive. The same combination of (US, Android, RTB exchange, gaming app, banner ad, bid multiplier 0.90×) might appear 50,000 times in a single day. We don’t need to show VW 50,000 identical examples — we can show it <em>one</em> example with a weight of 50,000.</p><p>We used <strong>Apache Spark</strong> to collapse 10 billion rows into roughly 8 million aggregated rows before VW saw any of it.</p><pre>Spark Input (~10 billion rows/day):<br>country | os      | app_bundle    | exchange | multiplier | won? | spend<br>US      | android | com.game.a    | RTB      | 0.90×      | yes  | $0.003<br>US      | android | com.game.a    | RTB      | 0.90×      | no   | $0<br>US      | android | com.game.a    | RTB      | 0.90×      | yes  | $0.004<br>... × 49,997 more rows<br>Spark Output (~8 million rows/day):<br>country | os      | app_bundle    | exchange | multiplier | wins   | spend  | total_auctions<br>US      | android | com.game.a    | RTB      | 0.90×      | 17,832 | $53.20 | 50,000<br>                          ↑<br>                1,250× compression - days of VW runtime → minutes</pre><p>But VW needs to know this single row represents 50,000 original events — otherwise the model treats one aggregated row the same as one individual auction, wildly underweighting high-traffic segments. That’s where <strong>importance weights</strong> come in.</p><p>In VW’s training format, you prefix an example with a weight N: that tells the optimizer: <em>&quot;scale the gradient update for this example by N.&quot;</em> The aggregated count becomes the weight:</p><pre># VW CB_ADF format: one block per training example<br># shared:  context features (same for all arms)<br># |Action: one line per arm (n total)<br># The chosen arm line carries: weight:cost:sampling_probability<br>shared |Context country=US os=android app=com.game.a format=BANNER hour=14<br>|Action multiplier=0.25<br>|Action multiplier=0.50<br>50000:0.47:0.067 |Action multiplier=0.90   ← chosen 50,000 times; cost=0.47; prob=6.7%<br>|Action multiplier=1.25<br>|Action multiplier=1.50<br>... (n arms total)</pre><p>A single VW training block represents 50,000 real-world auction outcomes. The importance weight (50,000) scales the gradient update proportionally — the same as seeing 50,000 separate identical examples.</p><p>This is the correct approach for aggregated bandit data. The general importance weight mechanism is documented in VW’s input format spec, but its application to pre-aggregated CB data is not prominently covered — it’s one of those patterns that only becomes obvious after you’ve spent time reading the source and the mailing list archives.</p><h4>Exploiting Bid Monotonicity to Multiply Training Signal</h4><p>After aggregation we still had a data sparsity problem. Aggregation solved the volume problem — VW could now finish training in under 30 minutes. But it surfaced a new issue: most (arm, segment) combinations still had zero direct observations. The bandit can only explore a handful of arms per segment per hour, and low-traffic inventory — emerging markets, niche app categories, brand-new exchanges — might see only one or two arm trials in an entire day. The signal existed; it just wasn’t reaching the right places.</p><p>The fix came from an auction physics constraint: <strong>in a first-price auction, win rate is non-decreasing with bid amount.</strong> If arm 10 (lower bid level) lost on a given inventory segment, arms 0–9 (lower bids) would also lose on that same segment. A cheaper bid cannot win when a more expensive one already failed.</p><p>We exploited this in an addCorrelation step applied before converting to VW format. The idea in plain terms:</p><pre># Pseudo-code: cross-arm signal propagation<br>for each (arm, cost, probability, bid_count) in training_data sorted by arm_id ascending:<br>    emit (arm, cost, probability, bid_count)   # always keep the original observation<br>    if arm WON (cost &lt; 1.0):<br>        # A lower bid won → higher bid arms on this segment are at least as viable<br>        for each higher_arm that also has a WIN record:<br>            emit (higher_arm, cost=this_arm.cost, probability=higher_arm.prob,<br>                  bid_count=this_arm.bid_count)   # share this arm&#39;s win signal upward<br>        # This arm ALSO has a LOSS record (it sometimes lost):<br>        # A higher bid losing → lower bids definitely lose<br>        for each lower_arm that has a LOSS record:<br>            emit (lower_arm, cost=1.0, probability=lower_arm.prob,<br>                  bid_count=this_arm.loss_bid_count)   # reinforce loss signal downward</pre><p>Two propagation directions:</p><p><strong>Downward loss propagation.</strong> If arm N lost, all lower arms (0 through N−1) that have their own loss records get additional synthetic loss samples, weighted by arm N’s bid count. VW doesn’t need to independently explore arm 3 to know it would lose when arm 10 already lost — the loss signal flows down automatically.</p><p><strong>Upward win propagation.</strong> If arm N won at cost C, higher arms that also have observed wins pick up arm N’s cost as an additional training signal. Win information flows upward to reinforce viable bid levels in adjacent ranges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYisSKzOAMAVLqm96Wu7yw.png" /></figure><p>The effect: a single observation at arm 10 generates training gradients for multiple arms in the same sweep. Sparse segments — those where only one or two arms were ever explored — receive inference about neighboring arms for free, without additional auction exposure. This was the bridge between 10-billion-row raw data and the model learning stable policies for low-traffic inventory.</p><p>The data pipeline was working. Signal was propagating across arms. The model had training data at a scale it could handle. But we still hadn’t answered the fundamental question underneath all of it: what exactly were we asking VW to <em>optimize</em>? Training is only as good as the loss function you give it, and ours needed work.</p><h3>The Cost Function Problem: Teaching VW What “Good” Means</h3><p>VW minimizes <strong>cost</strong>. Lower cost = better arm. We had to design a cost function capturing our real objective: find the bid multiplier where a segment’s win rate converges to the right level — not too high (burning budget), not too low (missing auctions). This took three iterations.</p><h4>Version 1: Too Simple</h4><pre># Linear combination of competing objectives with a normalizing constant C<br># Naive baseline: assumes bid_rate and win_rate contribute equally<br># Fails when objectives are correlated — higher bid always increases win rate,<br># so the model collapses to a single dominant strategy<br>cost = C - (bid_rate + win_rate)</pre><p>The model learned to always pick the highest multiplier. If you bid more, you win more. Obvious in hindsight. It burned campaign budgets in testing.</p><h4>Version 2: Win Rate Distance Penalty</h4><pre># Exponential penalty on deviation from target — steeper than linear, recovers faster<br># win_count term introduces data-volume awareness: larger samples → stronger signal<br># Flaw: treats win_rate as a point estimate regardless of sample size<br># win_rate=0.75 from n=4 is weighted identically to n=4000 — statistically unsound<br>cost = exp(λ · |win_rate - target| · win_count / N₀)</pre><p>This penalized arms that deviated from a target win rate. But it was unstable for segments with sparse data. Three wins out of four auctions looks identical mathematically to 3,000 wins out of 4,000 — both 75% win rate — but our confidence is completely different. Small-count segments were rewarded or punished on the basis of noise.</p><h4>Version 3: Bayesian Win Rate (What Shipped)</h4><pre># Bayesian smoothing with Beta(α, β) prior — stabilizes estimates under sparse data<br># Beta(1,1) = uniform prior; adjust α, β to encode domain knowledge about baseline rates<br>smoothed_metric = (successes + α) / (trials + α + β)<br><br># Map distance-from-target to an exploration signal<br># Arms far from threshold (either direction) → high certainty → exploit<br># Arms near threshold → high uncertainty → explore<br>y = 1.0 / (abs(smoothed_metric - target) + ε)<br><br># Exponential reward shaping: smooth, bounded [0,1], tunable via γ<br># Mathematically equivalent to a survival function of an Exp(γ) distribution<br>reward = 1 - exp(-γ · y)<br>cost   = 1 - reward</pre><p>The Bayesian smoothing is the critical piece. Adding +1 to wins and +2 to the denominator (a Beta(1,1) prior) means:</p><ul><li><strong>New segment, 0 wins out of 1 auction</strong>: wr = (0+1)/(1+2) = 0.33 — uncertain, not written off as 0%</li><li><strong>Mature segment, 1,000 wins out of 1,000 auctions</strong>: wr = 1001/1002 ≈ 0.999 — high confidence</li></ul><p>Without smoothing, a single loss on a brand-new segment made it look definitively bad (0% win rate), and the model stopped exploring it. With smoothing, new segments start at a neutral 33% estimate and converge to truth as data accumulates.</p><p>With the Bayesian cost function, the training signal finally made sense. The model had a stable, well-calibrated objective and wouldn’t write off new segments on flimsy evidence. We thought we were done with the fundamentals. Then we noticed something we’d been glossing over: high-traffic mature segments and brand-new segments were both being fed into the same softmax temperature — the same λ — and that uniform treatment was silently hurting performance in opposite directions on both ends.</p><h3>The Lambda Problem: One Exploration Rate for Everything</h3><p>Vowpal Wabbit’s built-in exploration strategy is <strong>softmax</strong>: instead of always choosing the highest-predicted arm (greedy), it samples arms with probability proportional to predicted reward, modulated by a temperature parameter λ (lambda). This is the same temperature parameter from language model softmax — just expressed inversely:</p><pre>P(arm_i) ∝ exp(λ × predicted_reward_i)<br>λ = 0     →  uniform distribution across all arms   (pure exploration)<br>λ → ∞     →  all probability on the single best arm  (pure exploitation)<br>λ = 1     →  moderately exploratory (better arms favored, others still sampled)</pre><p><strong>VW accepts one global λ for the entire training run.</strong> Our problem: we needed <em>different</em> λ values for different segments.</p><ul><li><strong>High-traffic segment</strong> (“US users, Android, gaming apps”): millions of historical auction outcomes. We know what works. High λ — exploit the best arms.</li><li><strong>Brand-new segment</strong> (just-launched app, never explored): no data at all. Low λ — explore broadly across all arms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgK1gPdYzbZJoS9625FU3w.png" /></figure><p>With a single global λ, we’d either over-explore mature segments (wasting budget re-testing arms evaluated hundreds of thousands of times) or under-explore new ones (betting everything on the first arm we tried).</p><h4>Failed Approach: One VW Process Per Segment</h4><pre>def run_command(command):<br>    with os.popen(command) as f:<br>        return f.readlines()<br># Naive fix: invoke VW once per segment with its own lambda<br>for segment, lambda_val, example_text in training_data:<br>    cmd = f&quot;echo &#39;{example_text}&#39; | /tmp/vw --cb_explore_adf --softmax --lambda {lambda_val}&quot;<br>    prediction = run_command(cmd)   # returns empty - os.popen doesn&#39;t wait</pre><p>Two problems killed this approach:</p><ol><li>os.popen() returns before VW finishes writing output — predictions came back empty every time</li><li>Spawning one VW process per segment — potentially millions of subprocess launches — added hours of overhead just from process creation and startup</li></ol><p>The Databricks notebook timed out repeatedly.</p><h4>The Fix: Per-Segment Lambda Encoded in the Data</h4><p>The solution: encode each segment’s lambda value directly into the shared context line of the training data. VW’s --cb_explore_adf format reads a per-example lambda prefix from the shared line, applying different softmax temperatures to different examples within a single training run:</p><pre># High-traffic, well-understood segment: lambda=5 (exploit strongly)<br>5 shared |Context country=US hour=14 app=com.game.a os=android exchange=RTB<br>|Action multiplier=0.25<br>|Action multiplier=0.50<br>50000:0.47:0.067 |Action multiplier=0.90<br>...<br># Brand-new segment: lambda=0.5 (explore broadly across all arms)<br>0.5 shared |Context country=JP hour=02 app=com.new.app os=ios exchange=ADX<br>|Action multiplier=0.25<br>12:0.9:0.067 |Action multiplier=0.50<br>...</pre><p>One VW invocation handles the entire dataset with the right exploration-exploitation balance baked per-segment into the data. At prediction time, the notebook strips the lambda prefix back out before parsing VW’s output:</p><pre>def parseData(data):<br>    inputData, predictionData = data<br>    # Strip the per-segment lambda embedded in the shared line<br>    vwlambda = inputData.split(&quot;:&quot;)[1].split(&quot; &quot;)[0]<br>    inputData = inputData.replace(&quot;:&quot; + vwlambda, &quot;&quot;)<br>    ...</pre><p>Why Doubly Robust (--cb_type dr)?</p><p>Bandit training is fundamentally an <em>off-policy learning</em> problem: you train on data collected under a historical policy, but want to learn an improved policy. IPS (Inverse Propensity Scoring) handles this unbiasedly — it reweights each observation by 1/probability_of_choosing_this_arm — but introduces high variance when sampling probabilities are low. DR (Doubly Robust) adds a learned reward model as a control variate. If <em>either</em> estimator is correct, the DR estimate is consistent. In practice, DR roughly halves variance compared to IPS alone.</p><h3>From Bid Multipliers to Bid Ranges</h3><p>The V1 system went into production. It worked — measurably better than the hand-tuned bid correction rules it replaced, with the model adapting to each segment’s traffic patterns without human intervention. But certain inventory types kept getting mis-priced: new app categories, emerging markets, places where the upstream click and conversion models were weakest. The more we dug into these failures, the more we saw they all traced back to a hidden assumption baked into the n-multiplier design itself. Multipliers are relative to a base bid, and that base bid comes from separate click-rate and conversion-rate prediction models. If those upstream models misjudge a new app category or an unfamiliar market, the bandit faithfully scales an already-wrong anchor. Fifteen different multipliers of a bad number are still a bad number.</p><p>The next iteration replaced the ’n’ relative multipliers with ‘<strong>n’ absolute bid price ranges</strong>. Instead of asking “how aggressively should we bid relative to our model’s estimate?”, the question became “what is the right absolute price for this inventory?”</p><pre>Arm   0:  [$0.010 – $0.014 CPM]   ← low-bid territory<br>Arm   1:  [$0.015 – $0.019 CPM]<br>Arm   2:  [$0.019 – $0.024 CPM]<br>  ...<br>Arm  65:  [$1.00  – $1.19  CPM]<br>  ...<br>Arm n:  [$20.00 – $21.90 CPM]   ← aggressive territory</pre><p>Arms are spaced densely at the low end (where small price differences separate winning from losing) and coarser at the top. The bandit learns “this app+country+format combination typically clears around $0.15–$0.20 CPM” directly from auction outcomes — no upstream model required as anchor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_8-9YERTfzsv-rxk5rK1A.png" /></figure><p>The monotonicity optimization from the scale section becomes even more critical here: with ’n’ arms and sparse exploration, cross-arm signal propagation is the only practical way to learn stable policies for most of the arm space.</p><h4>The Winner’s Curse Problem</h4><p>With n arms, data per arm is much sparser. But there’s a subtler problem: <strong>in a first-price auction, winning only tells you that you bid enough — not whether you overbid.</strong></p><p>If arm 65 wins ($1.00–$1.19 CPM), you don’t know whether the clearing price was $0.60 (you overbid by 70%) or $1.15 (you barely squeaked through). The binary win/lose signal can’t distinguish “efficient win” from “wasteful win.”</p><h4>Modeling Win Price Distributions with IGMN</h4><p>We added an <strong>Incremental Gaussian Mixture Network (IGMN)</strong> layer to each arm. IGMN is an online variant of Gaussian mixture learning — it updates cluster means, variances, and weights as new winning bids arrive, without storing history.</p><pre># Per arm: a small set of Gaussian clusters tracking winning bid distribution<br># Example — Arm 65 after some learning:<br># Cluster A: mean=$1.03 CPM, variance=tiny  → comfortable wins (clearing well below ceiling)<br># Cluster B: mean=$1.17 CPM, variance=tiny  → tight wins (barely clearing)<br># When a new winning bid arrives at $1.04 CPM:<br># 1. Compute Mahalanobis distance to each cluster<br># 2. Assign to nearest cluster<br># 3. Update: mean, variance, weight (online EM step)<br># 4. If no cluster is close enough: spawn a new cluster</pre><p>Each arm maintains 2–3 clusters initialized at key price points within its range. As real auction data flows in, the clusters shift to reflect where winning bids actually land.</p><p>This gives the cost function information beyond binary win/lose:</p><ul><li><strong>Win clustered at the low end of the arm’s range</strong> → winning comfortably; this bid level is efficient. Adjusted win rate increases.</li><li><strong>Win clustered at the high end</strong> → barely clearing the market; overbidding risk. Adjusted win rate reflects the tighter margin.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sazZoGyPnVftWk9D72au3g.png" /></figure><p>VW now receives a training signal that distinguishes <em>how</em> an arm won, not just <em>whether</em> it won. The model learns to prefer arms where wins are clean over arms where wins are marginal — tighter bid optimization, without the upstream dependency on base bid accuracy.</p><h3>The Distributed Training Dead End: SynapseML</h3><p>While we were redesigning the arm architecture from multipliers to absolute price ranges, we were also asking a parallel question: could we distribute the VW training itself? The aggregated dataset was around 8 million rows and single-node training on the Databricks driver was finishing in under 25 minutes — comfortably fast enough. But the instinct to scale horizontally is hard to resist, especially when you’re already running on a cluster. We ran the experiment.</p><p>Microsoft’s <strong>SynapseML</strong> library ships a Spark-native version of Vowpal Wabbit that parallelizes training across a cluster. Multiple workers each train on a data shard, then average their weight vectors to produce a single model. We tried it.</p><p>The blocker was a VW flag called --invert_hash.</p><p>When VW trains, it converts all feature names into 32-bit integer hashes for speed — the hash of &quot;country=US&quot; might be 1,847,392. The model stores weights indexed by these integers. At serving time, the ad serving layer needs to know <em>which hash corresponds to which feature</em> to compute score = Σ weight[feature] for each bid request. --invert_hash is a separate VW pass that outputs a human-readable feature-name → weight file.</p><p>SynapseML’s distributed VW doesn’t support --invert_hash. Workers average raw float arrays in memory across machines — the hash-to-name mapping is never recorded anywhere, so there&#39;s no way to reconstruct it after averaging. The GitHub issue tracking this was filed and closed as &quot;won&#39;t fix.&quot;</p><p>Distributed VW was out. We stayed single-node on the Databricks driver — which turned out to be the right call anyway, because the Spark aggregation step had already shrunk the problem to a size where single-node was perfectly adequate.</p><h3>The Actual Databricks Training Notebook</h3><p>With distributed training ruled out, the design was settled: single-node VW on the Databricks driver, updating hourly, warm-starting from the previous hour’s model. Here is exactly what that loop looked like in practice — how all the pieces assembled into a working system.</p><p><em>Note: the code below shows the V1 implementation, where arms are encoded as bid multiplier values (0.25×, 0.90×, 1.25×, etc.). V2 changed arm feature representation to absolute price ranges, but kept the same training loop, warm start pattern, and quality gate.</em></p><p>The notebook ran <strong>hourly</strong> — the bandit needs to update its exploration policy as new data arrives through the day, not just once at midnight.</p><h4>Getting the VW Binary onto the Cluster</h4><p>VW is a compiled C++ binary. Databricks clusters don’t have it pre-installed, and the Python vowpalwabbit pip package doesn&#39;t expose the low-level flag control we needed. Solution: pin a specific binary version in cloud storage, copy it to the driver&#39;s local filesystem on each run.</p><pre># VW binary stored at a pinned version in cloud storage<br># Copying to /tmp makes it available as a local executable on the driver<br>dbutils.fs.cp(<br>    &quot;/mnt/storage/vw-binary/vw-production&quot;,<br>    &quot;file:///tmp/vw&quot;<br>)<br>run_command(&quot;chmod a+x /tmp/vw&quot;)<br># Every run — across cluster restarts, driver replacements, Databricks upgrades —<br># uses the same binary. No surprise behavioral changes from library updates.</pre><h4>Training: Fresh Start vs. Warm Start</h4><p>Each hourly run checks whether a trained model from the previous hour exists. If it does, training picks up where it left off. If not (first-ever run, or a manual reset), it starts fresh.</p><pre>if size == 0 or modelStartOver == &quot;true&quot;:<br>    # Fresh start: initialize from random weights<br>    vwCommand = (<br>        &quot;/tmp/vw&quot;<br>        &quot; --data &quot; + trainingTextDataLocalPath +<br>        &quot; --final_regressor &quot; + newCbModelFileLocalPath +<br>        &quot; --hash all --bit_precision 28&quot;     # 2^28 ≈ 268M hash buckets for feature storage<br>        &quot; -k&quot;                                # clear weight file before writing<br>        &quot; --passes 5&quot;                        # 5 full sweeps over training data<br>        &quot; --holdout_period 7&quot;                # hold out every 7th example to detect overfitting<br>        &quot; --onethread&quot;                       # single-threaded (driver node only, no workers)<br>        &quot; --cb_explore_adf&quot;                  # contextual bandit with per-arm features<br>        &quot; -q CH -q CA -q HA -q RA&quot;          # quadratic feature interactions<br>        &quot; --cb_type dr&quot;                      # Doubly Robust cost estimation<br>        &quot; --save_resume&quot;                     # save optimizer state for next warm start<br>    )<br>else:<br>    # Warm start: load previous hour&#39;s model, continue from there<br>    vwCommand = (<br>        &quot;/tmp/vw&quot;<br>        &quot; --data &quot; + trainingTextDataLocalPath +<br>        &quot; --initial_regressor &quot; + oldCbModelFileLocalPath +   # last hour&#39;s weights + optimizer state<br>        &quot; --final_regressor &quot; + newCbModelFileLocalPath +<br>        &quot; --hash all --bit_precision 28&quot;<br>        &quot; -k --passes 5 --holdout_period 7 --onethread&quot;<br>        &quot; -q CH -q CA -q HA -q RA&quot;<br>        &quot; --cb_explore_adf --cb_type dr&quot;<br>        &quot; --save_resume&quot;<br>        &quot; --power_t 0&quot;                       # freeze learning rate schedule on warm starts<br>    )<br>run_command(vwCommand)</pre><p><strong>Understanding the key flags:</strong></p><p><strong>--cb_explore_adf</strong> — Contextual bandit with <em>action-dependent features</em> (&quot;ADF&quot;). In a standard bandit, arms are just indices with no features of their own — the model only uses context to decide which arm is best. With ADF, each arm has its own feature line and the model learns which <em>context × arm</em> combinations work well. This enables generalization: if 0.90× works well for US gaming apps, and UK gaming apps look similar in feature space, the model can transfer that learning without relearning from scratch.</p><p><strong>--cb_type dr</strong> — Doubly Robust estimation. In bandit training you only observe the outcome of the arm you <em>chose</em> — you never know what would have happened with the other 14. DR combines IPS (unbiased, high-variance) and DM (lower variance, potentially biased) using DM as a control variate for IPS. If either estimator is correct, the combined estimate is consistent. For data where some arms have low sampling probabilities, DR gives substantially lower-variance gradient estimates than IPS alone.</p><p><strong>-q CH -q CA -q HA -q RA</strong> — Quadratic feature interactions. VW creates pairwise interaction features for every pair from two specified namespaces:</p><ul><li>CH = Country × Hour (US at noon vs. US at midnight are different markets)</li><li>CA = Country × App (US gaming apps vs. JP gaming apps behave differently)</li><li>HA = Hour × App (a news app at 7am vs. 10pm has different win rate dynamics)</li><li>RA = Rest × App (OS, exchange, device type each interact with the specific app)</li></ul><p>Without these, the model can learn “US is high-traffic” and “noon is peak” separately — not that “US gaming apps at noon on Android” is its own distinct market segment with its own optimal bid level.</p><p><strong>--save_resume</strong> — Saves the optimizer&#39;s full state alongside model weights: per-feature adaptive learning rates, gradient accumulators, and pass count. Without this, a warm start loads stale weights but a fresh optimizer — equivalent to applying a high initial learning rate to already-trained weights, which destabilizes them.</p><p><strong>--power_t 0</strong> — Sets the learning rate decay exponent to 0. VW&#39;s schedule decays learning rate as (t₀ / (t₀ + t))^p where p is power_t and t is the cumulative example count. With power_t 0, this becomes (t₀ / (t₀ + t))⁰ = 1 — constant rate, no decay. During warm starts, t is already large, so with any nonzero power_t the learning rate approaches zero and new data barely moves the weights. Setting power_t 0 ensures each hourly run actually learns.</p><h4>The Warm Start Pattern</h4><p>Most production ML jobs restart from scratch each run: read all historical data, train to convergence, ship the model. We ran differently:</p><pre>Hour  0:  Random weights   → 5 passes on hour-0 data  → saved as cbmodel_h0<br>Hour  1:  Load cbmodel_h0  → 5 passes on hour-1 data  → saved as cbmodel_h1<br>Hour  2:  Load cbmodel_h1  → 5 passes on hour-2 data  → saved as cbmodel_h2<br>  ...<br>Hour 23:  Load cbmodel_h22 → 5 passes on hour-23 data → saved as cbmodel_h23<br><br>After 24 hours: model reflects a full day of cumulative learning<br>without ever storing or reprocessing more than one hour of data at a time.</pre><p>Weights improve continuously through the day. A segment that generates traffic in the afternoon has an updated policy by the next morning. There is no “cold start every midnight.”</p><h4>Automatic Model Rollback</h4><p>A bad hour of data — traffic spike, tracking partner outage, data quality blip — can produce a <em>worse</em> model if blindly accepted. We added a quality gate: evaluate both the new and old model on a held-out test hour, and revert if the new one regresses.</p><pre># Evaluate new model on held-out test data (test hour not used in training)<br>testOutputNew = run_vw_command(<br>    &quot;/tmp/vw --data /tmp/data_test.txt&quot;<br>    &quot; --initial_regressor /tmp/cbmodel&quot;         # new model<br>    &quot; -t&quot;                                        # test-only: no weight updates<br>    &quot; --hash all --bit_precision 28 -k --passes 1&quot;<br>    &quot; --onethread -q CH -q CA -q HA -q RA&quot;<br>    &quot; --cb_explore_adf --cb_type dr --holdout_off&quot;<br>)<br># Evaluate old model on the exact same held-out test data<br>testOutputOld = run_vw_command(<br>    &quot;/tmp/vw --data /tmp/data_test.txt&quot;<br>    &quot; --initial_regressor /tmp/cbmodelOld&quot;       # previous hour&#39;s model<br>    &quot; -t --hash all --bit_precision 28 -k --passes 1&quot;<br>    &quot; --onethread -q CH -q CA -q HA -q RA&quot;<br>    &quot; --cb_explore_adf --cb_type dr --holdout_off&quot;<br>)<br># VW prints &quot;average loss = X&quot; at the end of each run - lower is better<br>avgLossNew = float(re.search(r&quot;\naverage loss = (.*)\ntotal&quot;, testOutputNew).group(1))<br>avgLossOld = float(re.search(r&quot;\naverage loss = (.*)\ntotal&quot;, testOutputOld).group(1))<br># Silently revert if new model is worse - ~5–10% of hourly runs<br>if avgLossNew &gt; avgLossOld:<br>    run_command(&quot;mv /tmp/cbmodelOld /tmp/cbmodel&quot;)</pre><h4>Serving: Pre-Baked Probabilities, Not Online Inference</h4><p>This is the architectural insight that made single-node viable — and the key difference from our other models.</p><p>Our other prediction models (which estimate click and conversion rates) export a <strong>weight vector</strong>. At bid time, the serving layer computes score = dot(feature_vector, weights) for whatever ad opportunity arrives — fully general inference on arbitrary inputs. These models need --invert_hash to produce named feature weight files.</p><p>The bandit is different. It doesn’t score <em>arbitrary</em> inputs — it scores a <strong>fixed, enumerable set of segments</strong>. Because the segment space is finite and known in advance, all inference can happen offline in the training notebook. The output isn’t weights — it’s arm probabilities, precomputed for every known segment.</p><pre># Run VW in prediction mode on all currently active segments<br>predictionCommand = (<br>    &quot;/tmp/vw&quot;<br>    &quot; --data &quot; + textDataForPredictionLocalPath +<br>    &quot; --initial_regressor /tmp/cbmodel&quot;<br>    &quot; --testonly&quot;                          # read-only, no weight updates<br>    &quot; --cb_explore_adf&quot;<br>    &quot; --softmax --lambda 1&quot;               # convert scores to probabilities<br>    &quot; --predictions &quot; + rawPredictionFile  # write arm_index:prob for each segment<br>)<br>run_command(predictionCommand)</pre><pre>def parseData(data):<br>    inputData, predictionData = data<br>    # Strip per-segment lambda embedded in the shared line<br>    vwlambda = inputData.split(&quot;:&quot;)[1].split(&quot; &quot;)[0]<br>    inputData = inputData.replace(&quot;:&quot; + vwlambda, &quot;&quot;)<br>    # Recover the arm list from the feature block ordering<br>    # Arms were encoded as &quot;|Action multiplier=0.90&quot;, &quot;|Action multiplier=1.25&quot;, etc.<br>    actionList = inputData.replace(&quot;\n&quot;, &quot;&quot;).split(&quot;|Action multiplier=&quot;)[1:]<br>    # Parse shared context features into CSV format for the prediction feed<br>    sharedData = inputData.split(&quot;\n&quot;)[0]<br>    sharedData = (sharedData<br>        .replace(&quot;shared |Context &quot;, &quot;&quot;)<br>        .replace(&quot;country=&quot;, &quot;&quot;).replace(&quot;hour=&quot;, &quot;&quot;)<br>        .replace(&quot;os=&quot;, &quot;&quot;).replace(&quot;app=&quot;, &quot;&quot;)<br>        .replace(&quot;exchange=&quot;, &quot;&quot;).replace(&quot;format=&quot;, &quot;&quot;))<br>    sharedData = sharedData.strip().replace(&quot; &quot;, &quot;,&quot;)<br>    # Map VW&#39;s 0-indexed arm number → the actual bid multiplier value<br>    finalArmProbList = []<br>    for armProb in predictionData.split(&quot;,&quot;):<br>        arm_idx = int(armProb.split(&quot;:&quot;)[0])<br>        prob    = armProb.split(&quot;:&quot;)[1]<br>        action  = actionList[arm_idx]      # e.g. &quot;0.90&quot;, &quot;1.25&quot;, &quot;2.50&quot;<br>        finalArmProbList.append(action + &quot;:&quot; + prob)<br>    return sharedData + &quot;,&quot; + &quot;$&quot;.join(finalArmProbList)<br><br># Parallel parsing across all available driver CPUs<br>pool = multiprocessing.Pool(multiprocessing.cpu_count())<br>fullPredictionData = pool.map(parseData, dataList)</pre><p>The resulting prediction feed written to cloud storage:</p><pre># segment features → arm:probability pairs ($ separated, ordered highest→lowest prob)<br>country,hour,os,app,format,exchange,arms<br>US,14,android,com.game.app,BANNER,RTB,0.90:0.41$1.25:0.28$0.75:0.17$1.50:0.09$0.65:0.03$...<br>JP,02,ios,com.new.app,INTERSTITIAL,ADX,0.25:0.12$0.30:0.11$0.50:0.11$0.65:0.10$0.75:0.10$...</pre><p>At bid time, the serving layer looks up the segment, reads the arm distribution, and samples. <strong>No model weights. No dot product. No VW at serving time.</strong> Just a hash map lookup and a weighted random draw. The entire bandit decision adds under 0.1ms to bid latency regardless of model complexity.</p><p>And — critically — no --invert_hash required. The cbmodel file stays in VW&#39;s internal binary format on the driver; we never need to deserialize it into named feature weights. Precomputing predictions offline is what unlocked the whole architecture and sidestepped the SynapseML blocker entirely.</p><h3>What We Learned</h3><ol><li><strong>Scale the data before you scale the training.</strong> The 1,250× compression from Spark aggregation was the real unlock. We spent weeks trying to make VW handle raw data faster — distributed training, hardware upgrades, format optimizations. The right move was to reduce the problem before VW ever saw it. Ten billion events aggregated to eight million, trained with a fast sequential learner, beats any distributed-training engineering applied to the raw problem.</li><li><strong>Importance weights are underrated — and underspecified.</strong> VW’s per-example weighting is what makes training on aggregated bandit data statistically valid. Without it, the optimizer treats one aggregated row (50,000 events) the same as one individual observation — wildly wrong gradient estimation. The N:cost:probability format in CB_ADF enables this; the general importance weight mechanism is documented in VW&#39;s input format spec, but its application to pre-aggregated bandit data is not prominently covered.</li><li><strong>Doubly Robust is worth the complexity.</strong> Bandit training is fundamentally off-policy: you train on data from a historical policy and want to improve on it. IPS is unbiased but high-variance — noisy gradients mean slow convergence, especially when some arms have low sampling probabilities. DR’s control variate roughly halves variance compared to IPS in practice. For a model updating hourly on one hour of data, variance reduction directly translates to faster convergence and better per-hour policies.</li><li><strong>Not every problem needs distributed training.</strong> After aggregation, our dataset fit comfortably on a single driver node. SynapseML had fundamental blockers we couldn’t work around. But more importantly: a single process is deterministic, debuggable, has no shuffle step, requires no inter-worker coordination, and doesn’t fail when one of twelve workers hits a memory limit. The operational simplicity of one process has real value that distributed-training enthusiasm often discounts.</li><li><strong>Match your output format to your training system before you commit.</strong> We built most of the SynapseML integration before discovering that --invert_hash — required by our serving layer&#39;s weight-file format — wasn&#39;t supported in distributed mode. The serving constraint should have been the first question. Had we started from &quot;what does serving need to consume?&quot; we would have arrived at the pre-baked prediction architecture immediately and saved weeks.</li><li><strong>Warm starting is underused in production ML.</strong> Retraining from scratch daily throws away within-day learning and creates a cold-start every morning. Hourly warm starts — enabled by --save_resume (preserves adaptive optimizer state) and --power_t 0 (keeps the learning rate effective when the pass counter is large) — let the model accumulate learning continuously. A segment that appears in afternoon data has an updated policy by the next morning, not the next midnight reset.</li><li><strong>Arm design matters as much as algorithm design.</strong> The jump from n relative bid multipliers to n absolute price ranges produced a qualitatively better system — not because the bandit algorithm changed, but because the problem formulation improved. Multipliers carry upstream model error forward; absolute price ranges let the bandit discover market clearing prices from scratch. And once you commit to absolute ranges, adding Gaussian mixture modeling of the win price distribution converts a binary win/lose signal into a richer signal that distinguishes comfortable wins from marginal ones. The arm design is the model design.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaa9ae50c866" width="1" height="1" alt=""><hr><p><a href="https://engg.inmobi.com/from-10-billion-rows-to-a-25-minute-training-loop-contextual-bandits-in-production-eaa9ae50c866">From 10 Billion Rows to a 25-Minute Training Loop: Contextual Bandits in Production</a> was originally published in <a href="https://engg.inmobi.com/">InMobi Technical Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Train LightGBM on Billions of Rows — Without Losing Your Mind]]></title>
            <link>https://engg.inmobi.com/how-to-train-lightgbm-on-billions-of-rows-without-losing-your-mind-fd6cd2f5931e?source=rss-414802f5960b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd6cd2f5931e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Pankaj Merisha]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 08:49:32 GMT</pubDate>
            <atom:updated>2026-08-19T10:29:31.468Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practitioner’s guide to distributed LightGBM on Spark/SynapseML: silent failures, infrastructure gotchas, and what we learned training on 16 billion rows at InMobi.</em></p><h3>1. The Challenge: Why This Problem Exists</h3><p>Every time you see an ad on your phone, there’s an auction happening in under 100 milliseconds. Hundreds of advertisers are competing for that impression. To win, a bidder needs to answer: <em>How much is this impression worth to me?</em></p><p>At InMobi, our DSP (Demand-Side Platform) participates in billions of these auctions every day. The answer to “how much to bid?” depends on three ML predictions:</p><ul><li><strong>CTR (Click-Through Rate):</strong> Will this user click the ad?</li><li><strong>CVR (Conversion Rate):</strong> If they click, will they convert?</li><li><strong>MBW (Minimum Bid to Win):</strong> What’s the floor price for this auction?</li></ul><p>These predictions feed directly into the bid formula. A miscalibrated CTR model doesn’t just hurt one impression — it propagates across every auction that advertiser enters, potentially misspending millions of dollars or missing profitable impressions entirely.</p><p>Here’s where LightGBM fits in the system: A bid request arrives from an ad exchange. Our PreSPO layer applies targeting and fraud filters. The ML scoring layer — running CTR, CVR, and MBW models — produces a predicted bid price. PostSPO selects and serves the winning creative. Every win and loss event flows back through Kafka and Flink into GCS as raw training data: roughly 16 billion rows per day. That data feeds the next day’s training run, and the cycle repeats.</p><p>The training pipeline — Spark + SynapseML + LightGBM — is what this article is about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbI8Yx96Zh8xEOYHWWoG4w.png" /></figure><h4>Why LightGBM?</h4><p>We evaluated several options:</p><ul><li><strong>Neural networks (DNN):</strong> Strong for learning entity embeddings (user IDs, creative IDs) and sequential signals — but our dataset was already-engineered tabular features with manageable cardinality. For that regime, GBDTs consistently win on accuracy, training speed, and debuggability.</li><li><strong>XGBoost:</strong> Depth-wise tree growth — less efficient on large sparse feature spaces.</li><li><strong>Logistic Regression:</strong> Too simple; misses feature interactions that matter for bid pricing.</li><li><strong>LightGBM:</strong> Leaf-wise tree growth, native GOSS and EFB for scale, battle-tested on tabular data with many sparse features.</li></ul><p>Ad-tech features are fundamentally tabular and sparse — thousands of features like publisher ID, device type, geography, user recency — with strong non-linear interactions. LightGBM handles this natively, and its sampling algorithms make billion-row training feasible without throwing away signal.</p><h4>Why 16 Billion Rows?</h4><p>Because that’s how many events we process in a single training window. Each row is one auction event — an impression, click, or install — with roughly 30 associated features. Models need to be retrained daily to capture shifting user behavior and market dynamics. Yesterday’s CTR distribution is already partially stale by today.</p><p>We considered sub-sampling. But every percentage point of model quality loss translates to real revenue impact across billions of bids. So the choice was: learn how to train on everything, or leave signal on the table.</p><h3>2. What Changes at Billion Scale</h3><p>The algorithm doesn’t change. The <em>consequences of every decision</em> do.</p><p>On a 100K-row laptop dataset, training takes seconds. Bad parameters? Rerun in 30 seconds. Memory is never a constraint. If something goes wrong, you see an error immediately.</p><p>At 16 billion rows:</p><ul><li>Training takes hours. A wrong config means 4+ hours of compute wasted.</li><li>Memory math gets brutal. Allocate wrong, and workers OOM silently.</li><li>Distributed coordination adds failure modes that don’t exist in local training.</li><li>Silent failures — where the job “succeeds” but produces a useless model — become a real risk.</li></ul><p>In distributed LightGBM on Spark, every boosting iteration involves: each executor building local histograms over its data partition, a network reduce-scatter to merge histograms across workers, and a global split decision. Then repeat 150 times. At 16B rows across 50 executors, the coordination overhead and memory footprint dominate wall-clock time. Any misconfiguration that’s harmless at small scale becomes catastrophic here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJdn3N6OdaeaxBXW_xT9ng.png" /></figure><h3>3. The First Wall: The 2.1 Billion Row Limit</h3><p>We hit this before we even got to parameter tuning. And we almost didn’t notice.</p><h4>The Silent Failure</h4><p>Stock LightGBM’s C++ core uses <strong>int32_t</strong> as its internal type for row indexing. int32 max is 2,147,483,647 — roughly 2.1 billion. When your dataset exceeds that:</p><ul><li>You don’t get an error.</li><li>Training doesn’t crash.</li><li>The job completes and reports success.</li><li>Your model has 1 tree instead of 150.</li></ul><p>The output looks completely normal until you inspect the training logs and notice <strong>num_iterations: 1</strong> where you expected 150. The model is essentially useless — and nothing in the standard output tells you anything went wrong.</p><blockquote>If you are running SynapseML LightGBM on more than 2 billion rows with a stock pip install, your training silently produces a 1-tree model. Always check the iteration count in training logs.</blockquote><p>This was independently hit by other users — SynapseML issue #2014 describes the exact scenario: 13 billion rows, 30 features, model stops after iteration 0. Closed without a confirmed fix.</p><h4>Why It Happens: The GitHub Trail</h4><p>The problem is in LightGBM’s C++ core, not in any config. The row index type is hardcoded as <strong>int32_t</strong>. When row count exceeds <strong>INT32_MAX</strong>, indexing wraps around silently.</p><p>Two PRs were opened to fix this:</p><ul><li><strong>LightGBM core PR #5540:</strong> Adds a CMake compile-time flag <strong>USE_DATASET_INT64</strong> that switches <strong>data_size_t</strong> from <strong>int32_t</strong> to <strong>int64_t</strong>. Stalled since 2022 — CI failures on CUDA and macOS, original author stepped away. Never merged.</li><li><strong>SynapseML PR #1684:</strong> The matching change to make SynapseML’s <strong>DatasetAggregator</strong> handle int64 row counts. Open for three years and closed without merging in February 2026.</li></ul><h4>The Fix: Build LightGBM with USE_DATASET_INT64</h4><p>There is no config workaround. The fix requires recompiling LightGBM from source with the unmerged PR applied. We forked both LightGBM and SynapseML, applied the relevant PRs, and built everything into a Docker image.</p><p><strong>Step 1 — Build LightGBM with int64 and SWIG Java bindings:</strong></p><pre>git clone --recursive &lt;your-fork&gt;/LightGBM.git /LightGBM-master/<br>cd /LightGBM-master/ &amp;&amp; git checkout &lt;int64-branch&gt;<br>export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64/<br>cmake -DUSE_SWIG=ON -DUSE_DATASET_INT64=ON /LightGBM-master/<br>make -j$(nproc)<br>cp /LightGBM-master/lightgbmlib.jar /LightGBM-master/build/lightgbmlib.jar</pre><p>The two critical flags: <strong>-DUSE_DATASET_INT64=ON</strong> switches <strong>data_size_t</strong> from <strong>int32_t</strong> to <strong>int64_t</strong>. <strong>-DUSE_SWIG=ON</strong> generates the Java bindings SynapseML uses at runtime.</p><p><strong>Step 2 — Build SynapseML against the custom LightGBM:</strong></p><pre>git clone --recursive &lt;your-fork&gt;/SynapseML.git /SynapseML/<br>cd /SynapseML/ &amp;&amp; git checkout &lt;int64-branch&gt;<br>export SBT_OPTS=&quot;-Xms512M -Xmx2G -Xss4M -XX:MaxMetaspaceSize=1G&quot;<br>sbt clean assembly<br>cp /SynapseML/target/scala-2.12/synapseml-assembly-*.jar /opt/spark/jars/<br>sbt &quot;set test in assembly := {}&quot; packageSynapseML</pre><p><strong>Step 3 — Install the Python wheel:</strong></p><pre>pip install /SynapseML/target/scala-2.12/generated/package/python/synapseml-0.0.0.dev1-py2.py3-none-any.whl</pre><p><strong>Full Dockerfile:</strong></p><pre>FROM apache/spark-py:v3.4.0<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    swig git cmake wget openjdk-11-jdk ant ca-certificates-java gcc curl<br>RUN mkdir /LightGBM-master \<br>    &amp;&amp; git clone --recursive &lt;your-fork&gt;/LightGBM.git /LightGBM-master/ \<br>    &amp;&amp; cd /LightGBM-master/ &amp;&amp; git checkout &lt;int64-branch&gt; \<br>    &amp;&amp; export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64/ \<br>    &amp;&amp; cmake -DUSE_SWIG=ON -DUSE_DATASET_INT64=ON /LightGBM-master/ \<br>    &amp;&amp; make -j$(nproc) \<br>    &amp;&amp; cp /LightGBM-master/lightgbmlib.jar /LightGBM-master/build/lightgbmlib.jar<br>RUN git clone --recursive &lt;your-fork&gt;/SynapseML.git /SynapseML/ \<br>    &amp;&amp; cd /SynapseML/ &amp;&amp; git checkout &lt;int64-branch&gt; \<br>    &amp;&amp; export SBT_OPTS=&quot;-Xms512M -Xmx2G -Xss4M -XX:MaxMetaspaceSize=1G&quot; \<br>    &amp;&amp; sbt clean assembly \<br>    &amp;&amp; cp /SynapseML/target/scala-2.12/synapseml-assembly-*.jar /opt/spark/jars/ \<br>    &amp;&amp; sbt &quot;set test in assembly := {}&quot; packageSynapseML<br>RUN pip install /SynapseML/target/scala-2.12/generated/package/python/synapseml-0.0.0.dev1-py2.py3-none-any.whl</pre><p>With the patched build, use <strong>dataTransferMode=&quot;bulk&quot;</strong> — it&#39;s the stable path with the int64 fix validated.</p><blockquote>A note on streaming mode: SynapseML made streaming the default in v1.0.12. Whether the int32 overflow affects streaming in the same way hasn’t been conclusively demonstrated in upstream issues. If starting fresh, test streaming with your actual data volume and verify iteration count before trusting the output.</blockquote><h3>4. Getting Training to Actually Run</h3><p>With the int32 limit addressed, we still had to survive the training run itself. Three more problems surfaced here.</p><h4>Memory Math You Cannot Skip</h4><p>LightGBM’s histogram algorithm stores binned feature values as <strong>uint8_t</strong> — 1 byte per value — instead of the 4-byte floats your input data uses. But at 16B rows, even 1 byte per value adds up fast:</p><pre>~16B rows × 30 features × 1 byte  ≈  480 GB  (data buffers, across cluster)<br>Gradient buffers: 16B × 2 × 4 bytes  ≈  128 GB<br>Rough total:  600 GB – 1 TB  (distributed across all workers)</pre><blockquote>Use a 10% sample to benchmark memory before running the full dataset. The footprint depends heavily on max_bin, num_leaves, and data sparsity. Scale linearly from there.</blockquote><h4>Autoscaling Will Break Your Job</h4><p>Spark’s dynamic resource allocation is standard practice. We had it enabled. LightGBM does not support it during training.</p><p>LightGBM’s distributed mode runs a <strong>NetworkInit</strong> phase at the start of training that establishes a fixed network topology — all executors register their endpoints with the driver. Once that handshake completes, LightGBM assumes the worker set is constant for the duration of training.</p><p>If autoscaling removes an executor mid-training, the driver’s connection count is wrong and the job deadlocks. Confirmed by maintainer @imatiach-msft in SynapseML issue #319: <em>“LightGBM currently does not support adding new executors/machines dynamically after NetworkInit.”</em></p><p><strong>Fix:</strong> Set <strong>spark.dynamicAllocation.enabled=false</strong> on the cluster before training. If you&#39;re on spot or preemptible instances, use on-demand nodes for training jobs.</p><h4>Partition Skew Hurts Model Quality</h4><p>In distributed training, each executor holds a partition of the data and builds local histograms. If your minority class — say, clicks in a CTR model where click rates are 0.1% to 1% — is concentrated in a few partitions, most workers see almost no positive examples. The gradient picture is uneven across workers. Splits found in early rounds may not generalize well.</p><p><strong>Fix:</strong> Repartition with stratification by label before training. <strong>repartition()</strong> alone doesn&#39;t stratify — use a sort-repartition by class or an explicit stratified split before calling <strong>.fit()</strong>.</p><h4>The numTasks Trap</h4><p>LightGBM opens one network endpoint per task/partition. If your <strong>numTasks</strong> config doesn&#39;t match what Spark actually launches, the driver waits for connections that never arrive.</p><p>A common source of miscounting: in Spark client mode, the driver is counted as an executor by Spark’s resource manager, but LightGBM should not include it. SynapseML prints a warning — <em>“IN CLIENT MODE, using executors — 1 when calculating num tasks”</em> — but manually overriding <strong>numTasks</strong> without accounting for this offset reproduces the bug.</p><p><strong>Fix:</strong> Let SynapseML auto-calculate <strong>numTasks</strong>. Only override for port-binding failures, using <strong>numExecutors × tasksPerExecutor - 1</strong> in client mode.</p><h3>5. Why LightGBM Can Do This at All: Histograms, GOSS, and EFB</h3><p>Once training was running, we needed to understand <em>why</em> it worked at this scale — because the same mechanisms that make LightGBM fast are the ones you’re tuning when you touch the hyperparameters.</p><h4>Histogram-Based Learning</h4><p>Traditional gradient boosting finds splits by scanning raw feature values — O(data × features) per tree. LightGBM instead buckets continuous features into discrete bins (typically 255 bins) and builds histograms. Finding the best split then costs O(bins × features). Since bins is much smaller than data — 255 bins versus 16 billion rows — this is the central reason LightGBM can handle our scale at all.</p><h4>GOSS: Gradient-Based One-Side Sampling</h4><p>Not all 16 billion training examples contribute equally to each boosting round. Well-trained examples have small gradients — the model already handles them well. Under-trained examples have large gradients — they’re where the model has room to improve.</p><p>GOSS exploits this asymmetry:</p><ul><li>Sort all instances by absolute gradient, descending.</li><li>Keep the top <em>a%</em> (large-gradient instances) in every round.</li><li>From the remaining instances, randomly sample <em>b%</em>.</li><li>Re-weight those sampled instances by <strong>(1-a)/b</strong> to preserve the data distribution.</li><li>Train on a% plus b% of the data — not 100%.</li></ul><p>At 16B rows, GOSS is the difference between a feasible training time and an impossible one. To enable: set <strong>boosting_type=&quot;goss&quot;</strong> and tune <strong>top_rate</strong> (the a%) and <strong>other_rate</strong> (the b%). Don&#39;t mix GOSS with bagging parameters — GOSS handles data sampling internally.</p><h4>EFB: Exclusive Feature Bundling</h4><p>Ad-tech feature spaces are often wide and sparse. Features like <strong>is_ios_user</strong>, <strong>is_android_user</strong>, <strong>is_tablet_user</strong> are mutually exclusive — only one is non-zero for any given impression. EFB detects these and bundles them into a single synthetic feature column, reducing the effective feature count and speeding up histogram building.</p><p>One implementation detail not documented anywhere: the conflict threshold is hardcoded as <strong>num_data / 10000</strong> in <strong>dataset.cpp</strong> and isn&#39;t user-configurable. At billions of rows the threshold is high, so features need very low actual conflict rates to qualify for bundling.</p><h3>6. Hyperparameter Tuning at Scale</h3><p>The rule at scale: <strong>tune structure first, regularization second, sampling third.</strong></p><h4>Tree Structure: Control Complexity First</h4><pre>num_leaves = 31       # primary complexity control<br>max_depth = -1        # unlimited; num_leaves is the real constraint<br>min_data_in_leaf = 20 # default — almost always too low at scale</pre><p><strong>num_leaves</strong> is the main lever. LightGBM grows leaf-wise — it always splits the leaf with the highest gain, regardless of tree symmetry.</p><p>The <strong>min_data_in_leaf</strong> trap: the default of 20 is statistically meaningless at 16B rows. A leaf built on 20 out of 16 billion examples carries almost no signal. At this scale, values in the <strong>500 to 5000 range</strong> produce better-supported leaf estimates.</p><h4>Regularization: Prevent Overfitting</h4><pre>lambda_l1 = 0.0    # L1 regularization on leaf weights<br>lambda_l2 = 0.0    # L2 regularization on leaf weights<br>min_sum_hessian_in_leaf = 0.001</pre><p>With billions of rows, LightGBM has enormous capacity to memorize rare patterns. <strong>lambda_l1</strong> and <strong>lambda_l2</strong> are your first defense. <strong>min_sum_hessian_in_leaf</strong> acts as a lower bound on how statistically well-supported a split must be before it&#39;s created.</p><h4>Sampling: Speed vs Accuracy</h4><pre>bagging_fraction = 1.0  # fraction of training data per tree<br>bagging_freq = 0        # 0 = disabled; N = resample every N iterations<br>feature_fraction = 1.0  # fraction of features per tree</pre><p>At scale, set <strong>bagging_fraction=0.5</strong> to <strong>0.8</strong> with <strong>bagging_freq=5</strong>. This cuts training time and acts as a strong regularizer. If using GOSS, don&#39;t set bagging parameters — GOSS handles sampling internally.</p><h4>Class Imbalance: Use scale_pos_weight, Not is_unbalance</h4><pre>is_unbalance = False       # NOT recommended for production<br>scale_pos_weight = 100.0   # preferred: neg_count / pos_count</pre><p><strong>is_unbalance=True</strong> is tempting but dangerous. The official LightGBM docs explicitly warn it results in <em>&quot;poor estimates of the individual class probabilities.&quot;</em> At InMobi, raw scores feed into bid pricing formulas that multiply probability by value — an uncalibrated probability gives wrong bid prices across every auction.</p><h4>boost_from_average: Small Flag, Meaningful Impact</h4><pre>boost_from_average = True  # adjusts initial score to the class mean</pre><p>On imbalanced data, this meaningfully accelerates convergence — the model starts from a calibrated baseline. One caveat: this silently does nothing with a custom Python objective function (issue #7193). For custom objectives, set the initial score via <strong>dataset.set_init_score()</strong>.</p><h4>Categorical Features</h4><p>SynapseML auto-detects columns processed with Spark’s <strong>StringIndexer</strong>. For numeric columns that are semantically categorical but lack this metadata, declare them explicitly:</p><pre>classifier.setCategoricalSlotNames([&quot;country_code&quot;, &quot;device_type&quot;, &quot;exchange_id&quot;])<br>max_cat_threshold = 32  # max categories before using a default split<br>cat_smooth = 10.0       # smoothing for rare categories (increase to 50-100)<br>cat_l2 = 10.0           # L2 regularization on categorical splits</pre><h4>Monotonicity Constraints</h4><pre># Features: [bid_price, ad_quality_score, user_recency_days]<br>monotone_constraints = [1, 1, -1]  # 1=increasing, -1=decreasing<br>monotone_constraints_method = &quot;intermediate&quot;</pre><h3>7. Infrastructure: Hardware Matters More Than Hyperparameters</h3><p>After getting the configuration right, we noticed something surprising: switching VM types had more impact on training time than any hyperparameter we tuned.</p><h4>Why LightGBM is CPU-Bound</h4><p>LightGBM’s inner loop — histogram building and split finding — is pure CPU computation running on every boosting round across every worker. It’s not I/O bound (data is already in memory) and not network bound (histogram reduce-scatter is fast relative to compute). Raw CPU throughput and cache efficiency dominate.</p><h4>The HPC Benchmark</h4><p>We tested Azure H-series HPC VMs (high-frequency Intel Xeon) against standard D-series VMs on the same training job:</p><ul><li><strong>Standard D-series:</strong> ~6 hours training time at baseline cost.</li><li><strong>HPC H-series:</strong> ~2 hours training time, ~5x lower total cost per run.</li></ul><p>The higher per-node cost of HPC VMs is more than offset by the shorter runtime. If your training jobs run for hours on standard VMs, benchmark one run on an HPC-class SKU before spending days on hyperparameter tuning. You may get more improvement from the hardware switch.</p><h3>8. Practical Troubleshooting and Key Takeaways</h3><h4>Starting Configuration</h4><pre>params = {<br>    # Structure<br>    &quot;num_leaves&quot;: 63,<br>    &quot;max_depth&quot;: -1,<br>    &quot;min_data_in_leaf&quot;: 500,   # much higher than default 20<br># Learning<br>    &quot;num_iterations&quot;: 500,<br>    &quot;learning_rate&quot;: 0.05,<br>    &quot;early_stopping_round&quot;: 50,<br>    &quot;boost_from_average&quot;: True,<br>    # Regularization<br>    &quot;lambda_l1&quot;: 0.1,<br>    &quot;lambda_l2&quot;: 1.0,<br>    &quot;min_sum_hessian_in_leaf&quot;: 0.001,<br>    # Sampling<br>    &quot;feature_fraction&quot;: 0.8,<br>    &quot;bagging_fraction&quot;: 0.8,<br>    &quot;bagging_freq&quot;: 5,<br>    # Objective<br>    &quot;objective&quot;: &quot;binary&quot;,<br>    &quot;metric&quot;: &quot;auc&quot;,<br>    &quot;scale_pos_weight&quot;: 100,  # replace with actual neg/pos ratio<br>    # Diagnostics<br>    &quot;verbosity&quot;: 1,<br>    &quot;is_provide_training_metric&quot;: True,<br>}</pre><h4>Common Errors</h4><p><strong>Training logs show 1 iteration instead of N</strong></p><p><strong>Fix:</strong> int32 row index overflow. Your dataset exceeds 2.1B rows on a stock build. No config workaround — requires the <strong>USE_DATASET_INT64</strong> custom wheel from Section 3.</p><p><strong>java.lang.IllegalArgumentException: Index 0 follows 0 and is not strictly increasing</strong></p><p><strong>Fix:</strong> Vectorized Parquet reader incompatibility.</p><pre>spark.config(&quot;spark.sql.parquet.enableVectorizedReader&quot;, &quot;false&quot;)</pre><p><strong>Job hangs indefinitely during initialization</strong></p><p><strong>Fix:</strong> Partition count mismatch with <strong>numTasks</strong>, or autoscaling changed the cluster mid-job. Set <strong>spark.dynamicAllocation.enabled=false</strong> and verify numTasks versus actual Spark task count.</p><p><strong>BarrierJobUnsupportedRDDChainException</strong></p><p><strong>Fix:</strong> <strong>useBarrierExecutionMode=True</strong> is incompatible with your pipeline. Disable it — only use it for NetworkInit port-binding failures.</p><p><strong>Model is worse than expected despite training completing</strong></p><p><strong>Fix:</strong> Check for partition skew. Repartition with stratification by label before training.</p><h3>Key Takeaways</h3><p><strong>Silent failures are the most dangerous kind.</strong> A job that completes and produces a 1-tree model with a normal exit code costs you hours of compute and possibly a bad model in production before anyone notices. Build iteration count checks into your pipeline.</p><p><strong>The algorithm is the easy part.</strong> The hard parts are distributed coordination (autoscaling, NetworkInit, numTasks), memory math, and partition skew — none of which appear in LightGBM documentation. Most of what we learned came from GitHub issue threads, not the official docs.</p><p><strong>Hardware matters more than hyperparameters at this scale.</strong> We got more training time reduction from switching VM families than from all hyperparameter tuning combined. Don’t skip the hardware benchmark.</p><p><strong>GOSS is underused.</strong> For anyone training at scale with imbalanced data, <strong>boosting_type=&quot;goss&quot;</strong> is the most impactful single parameter change. The quality difference versus full bagging is marginal in our experience.</p><p><strong>Check your iteration count. Always.</strong> Before trusting any model output from a large-scale LightGBM run, verify in the training logs that completed iterations match your <strong>num_iterations</strong> setting. One line of logging that could have saved us hours.</p><p><em>This post is based on production learnings from running LightGBM at InMobi’s DSP, where we train multi-billion-row models daily for real-time bid pricing. SynapseML uses 0.x/1.x versioning. The executionMode parameter in older SynapseML APIs has been replaced by dataTransferMode in v1.0.12+, where streaming is now the default.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd6cd2f5931e" width="1" height="1" alt=""><hr><p><a href="https://engg.inmobi.com/how-to-train-lightgbm-on-billions-of-rows-without-losing-your-mind-fd6cd2f5931e">How to Train LightGBM on Billions of Rows — Without Losing Your Mind</a> was originally published in <a href="https://engg.inmobi.com/">InMobi Technical Blogs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>