<?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 Noor Mohammad Yadallee on Medium]]></title>
        <description><![CDATA[Stories by Noor Mohammad Yadallee on Medium]]></description>
        <link>https://medium.com/@noor_yadallee?source=rss-f848f8f4c24c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3VDn-RWAefioJM6itAHjHw.png</url>
            <title>Stories by Noor Mohammad Yadallee on Medium</title>
            <link>https://medium.com/@noor_yadallee?source=rss-f848f8f4c24c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:17:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noor_yadallee/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[JAX Talks #4: Diffusion with JAX and Flax. Van Gogh styling from scratch]]></title>
            <link>https://medium.com/@noor_yadallee/jax-talks-4-diffusion-with-jax-and-flax-van-gogh-styling-from-scratch-1eb169c4703b?source=rss-f848f8f4c24c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eb169c4703b</guid>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Noor Mohammad Yadallee]]></dc:creator>
            <pubDate>Sun, 03 May 2026 19:33:06 GMT</pubDate>
            <atom:updated>2026-05-03T19:33:06.735Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s episode of war versus the magical black boxes that do what we want without telling us how it works: Diffusion models.</p><p>This article explores a specialized JAX and Flax implementation of a <strong>Denoising Diffusion Probabilistic Model (DDPM)</strong>, designed specifically for <strong>Van Gogh style transfer</strong> and optimized for <strong>Kaggle TPU v3–8</strong> hardware that is available for free (complete user verification to gain access to TPUs under Settings &gt; Accelerator in Kaggle notebooks).</p><p>Link to notebook: <a href="https://www.kaggle.com/code/noormy/jax-diffusion">https://www.kaggle.com/code/noormy/jax-diffusion</a></p><h3>Diffusion, what is it and why?</h3><p>At its core, a <strong>Diffusion Model</strong> is a type of generative artificial intelligence that learns to create data (like images or audio) by reversing a process of destruction.</p><p>While models like GANs (Generative Adversarial Networks) try to “guess” an image all at once, Diffusion models work like a sculptor — starting with a block of “noise” and gradually shaving away the static until a clear structure emerges.</p><p>The process is divided into two distinct phases:</p><h4>1. The Forward Process (Adding Noise)</h4><p>Imagine you have a clear photo of a landscape. In the forward process, the model incrementally adds tiny amounts of random Gaussian noise to the image over hundreds or thousands of steps.</p><ul><li>Eventually, the image is completely destroyed, leaving behind nothing but pure digital static.</li><li>This is a mathematical “Markov Chain” where each step only depends on the one before it.</li></ul><h4>2. The Reverse Process (Denoising)</h4><p>The “magic” happens during training. The model (usually a <strong>UNet</strong>) is shown a noisy image and asked to predict exactly how much noise was added at that specific step.</p><ul><li>By learning to predict and subtract that noise, the model essentially learns the “rules” of the data.</li><li>It learns that “this specific cluster of pixels looks like the edge of a petal” or “this blue gradient likely belongs in a sky.”</li></ul><h4>3. Sampling (Inference)</h4><p>Once trained, the model can generate something entirely new. You give it a piece of pure, random noise — which it has never seen before — and tell it to “denoise” it. Because it has learned the patterns of its training data (like the Van Gogh paintings in your notebook), it steers that random noise toward a recognizable image.</p><h3>Why are they popular now?</h3><p>Diffusion models have largely overtaken other generative methods because:</p><ul><li><strong>Stability:</strong> Unlike GANs, which are notoriously difficult to train and often “collapse,” diffusion models are mathematically stable.</li><li><strong>Quality:</strong> They produce incredibly high-quality, diverse results with fine-grained details.</li><li><strong>Flexibility:</strong> They are easy to “guide” using text prompts or, as in your current project, an existing image (<strong>img2img</strong>).</li></ul><h3>In our JAX Notebook:</h3><p>In our specific implementation, our model is learning the “distribution” of Van Gogh’s art. When we feed it a landscape photo with a <strong>strength</strong> of 0.6, you are essentially telling the model: <em>“Take this photo, destroy 60% of it with noise, and then use your knowledge of Van Gogh’s brushstrokes to rebuild those missing pieces.”</em></p><h3>The Architecture: A Functional Approach</h3><p>The heart of this notebook is a time-conditioned <strong>UNet</strong>. Unlike standard convolutional networks, this architecture must understand not just “what” an image is, but “when” it exists in the diffusion process.</p><h4>1. Timestep Embeddings</h4><p>To inform the model of the noise level, we utilize <strong>Sinusoidal Timestep Embeddings</strong>. This technique maps a scalar time value $t$ into a high-dimensional vector space using sine and cosine functions. This ensures the model can distinguish between early denoising (recovering coarse shapes) and late denoising (refining fine textures).</p><h4>2. The Building Blocks</h4><p>The implementation relies on three core components:</p><ul><li><strong>ResBlocks:</strong> Using GroupNorm and swish activations to maintain gradient flow.</li><li><strong>Self-Attention:</strong> Integrated at lower spatial resolutions to capture global stylistic coherence.</li><li><strong>Functional Transformations:</strong> Using flax.linen, the architecture remains modular and fully compatible with JAX’s functional paradigm.</li></ul><h3>The Physics of Style: DDPM &amp; DDIM</h3><p>The notebook implements the two fundamental processes of diffusion:</p><h4>1. The Forward Process (Markov Chain)</h4><p>Using a <strong>Cosine Noise Schedule</strong>, we incrementally add Gaussian noise to a Van Gogh painting until it is unrecognizable. By using a cosine schedule instead of a linear one, we ensure the “signal-to-noise” ratio drops more gracefully, preserving more useful information for the model to learn from during training.</p><h4>2. The Reverse Process (Inference)</h4><p>To turn a photograph into a painting, we use an <strong>img2img pipeline</strong>. We take a real-world photo, “backtrack” into the noise schedule by adding a controlled amount of noise, and then use the trained UNet to denoise it back toward the “Van Gogh manifold.”</p><p>To make this practical, the notebook implements a <strong>DDIM (Denoising Diffusion Implicit Models) Sampler</strong>. While standard DDPM requires 1,000 steps to generate an image, DDIM allows us to produce high-quality results in just 50 steps by skipping through the trajectory deterministically.</p><h3>Performance: Scaling on TPU v3–8</h3><p>The defining characteristic of this JAX implementation is its ability to scale seamlessly across all 8 cores of a <strong>Kaggle TPU v3–8</strong> using <strong>Parallel Mapping (</strong><strong>jax.pmap)</strong>. Unlike standard deep learning frameworks that often require complex boilerplate for distributed training, JAX treats multi-device execution as a functional transformation.</p><h4>How pmap Orchestrates Training</h4><ul><li><strong>Data Sharding</strong>: The input dataset is split across the 8 TPU cores, meaning each core processes a unique sub-batch of images simultaneously.</li><li><strong>Model Replication</strong>: The UNet parameters and the optimizer state are replicated across every device.</li><li><strong>Collective Communication</strong>: During the backward pass, the gradients calculated on each core are synchronized using a collective “all-reduce” operation (specifically jax.lax.pmean), ensuring that every device updates its local parameters identically.</li></ul><h4>Implementation Specifics in the Notebook</h4><p>The notebook utilizes pmap to transform the core training step into a multi-device operation:</p><ol><li><strong>Replicated State</strong>: The train_state is broadcast to all devices using flax.jax_utils.replicate.</li><li><strong>Transformed Step</strong>: The train_step function is wrapped in jax.pmap(axis_name=&#39;batch&#39;), which tells JAX to map the function over the first axis of the input arrays.</li><li><strong>Efficiency</strong>: By utilizing the High-Speed Interconnect (HSI) of the TPU pods, pmap allows for near-linear scaling, turning what would be a hours-long training process into one that converges in minutes.</li></ol><p>This notebook proves that with the right mathematical foundations and a powerful framework like JAX, you can recreate one of the most complex artistic styles in history using nothing but raw code and a few thousand TPU-accelerated gradients.</p><p>Whether you are adjusting the <strong>img2img_strength</strong> to find the perfect swirl or monitoring the <strong>MSE loss</strong> as the model learns to “paint,” this project brings the magic of diffusion out of the black box and into the light.</p><h3>References</h3><p><a href="https://arxiv.org/abs/2006.11239">Denoising Diffusion Probabilistic Models (Jonathan Ho, Ajay Jain, Pieter Abbeel</a>)</p><p><a href="https://arxiv.org/abs/2102.09672">Improved Denoising Diffusion Probabilistic Models (Alex Nichol, Prafulla Dhariwal</a>)</p><p><a href="https://arxiv.org/abs/2010.02502">Denoising Diffusion Implicit Models (Jiaming Song, Chenlin Meng, Stefano Ermon</a>)</p><p><a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need (Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin)</a></p><p><a href="https://arxiv.org/abs/1705.04058">Neural Style Transfer: A Review (Yongcheng Jing, Yezhou Yang, Zunlei Feng, Jingwen Ye, Yizhou Yu, Mingli Song)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcnOALC_BTeYM8-7rbIwvA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eb169c4703b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JAX talks #3: XGBoost in JAX from scratch for Kaggle House Prices ft.]]></title>
            <link>https://medium.com/@noor_yadallee/jax-talks-3-xgboost-in-jax-from-scratch-for-kaggle-house-prices-ft-c8ccc3aa18de?source=rss-f848f8f4c24c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ccc3aa18de</guid>
            <dc:creator><![CDATA[Noor Mohammad Yadallee]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 06:55:14 GMT</pubDate>
            <atom:updated>2025-12-31T06:55:14.778Z</atom:updated>
            <content:encoded><![CDATA[<h3>JAX talks #3: XGBoost in JAX from scratch for Kaggle House Prices ft. Equinox, and surprise tree stumps</h3><p>I am currently working on implementing the most common Machine Learning (ML) algorithms while also solving the most common entry level ML projects using JAX in <a href="https://github.com/Y-Noor/JAX">this repository</a>. This week’s challenge: solving <a href="https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques">House Prices — Advanced Regression Techniques</a> using XGBoost .</p><p><a href="https://colab.research.google.com/drive/1ss-FqpSzdo9VLzyL8AE_ZBhuKe7iAr4F?usp=sharing">As usual here is the colab where I worked :</a>D<a href="https://colab.research.google.com/drive/1ss-FqpSzdo9VLzyL8AE_ZBhuKe7iAr4F?usp=sharing">.</a></p><p>What I thought would be a walk in the park was actually quite the intellectual challenge. I had to relearn how the XGboost algorithm work and also watchout for certain pitfalls (that I probably dug for myself) such as how to make my algorithm use trees and not stumps while also manually doing calculus to check the second order derivative of the loss function (Hessian) to find computational shortcuts.</p><pre>print(f&quot;Training JAX-XGBoost (Strong Regularization: lambda={self.lambda_})&quot;)<br>        for i in range(self.n_estimators):<br>            G, H = preds - y, jnp.ones_like(y) <br>            s_f, s_t = np.zeros(2**self.max_depth - 1, dtype=int), np.zeros(2**self.max_depth - 1)<br>            l_v = np.zeros(2**self.max_depth)<br>            masks = [jnp.ones(n_samples, dtype=bool)]<br><br>            curr = 0<br>            for d in range(self.max_depth):<br>                nxt = []<br>                for m in masks:<br>                    f, t = self._find_best_split(X, G, H, self.bins, m)<br>                    s_f[curr], s_t[curr] = int(f), float(t)<br>                    nxt.append(m &amp; (X[:, int(f)] &lt;= float(t))); nxt.append(m &amp; (X[:, int(f)] &gt; float(t)))<br>                    curr += 1<br>                masks = nxt<br><br>            for j, m in enumerate(masks):<br>                l_v[j] = -jnp.sum(G[m]) / (jnp.sum(H[m]) + self.lambda_) if jnp.sum(m) &gt; 0 else 0.0<br><br>            tree = JAX_XGB_Tree(jnp.array(s_f), jnp.array(s_t), jnp.array(l_v), self.max_depth)<br>            preds += self.learning_rate * tree.predict(X)<br>            self.trees.append(tree)<br>            if (i+1) % 150 == 0:<br>                print(f&quot;  Round {i+1} RMSE: {jnp.sqrt(jnp.mean((preds-y)**2)):.5f}&quot;)</pre><p>G (Gradient): This is the first derivative of the loss function (preds−y).<br>H (Hessian): This is the second derivative. Since I am using Mean Squared Error (MSE), the second derivative is always 1. By using jnp.ones_like(y), I am telling the model that every single house has a Hessian weight of 1.0, bypassing the heavy computational cost of automatic differentiation. In other scenarios we would use something like <a href="https://docs.jax.dev/en/latest/_autosummary/jax.hessian.html">jax.hessian</a>` for automatically differentiating the function until we get its hessian.</p><h4>Problem number 1: mismatch between how JAX (and the underlying XLA compiler) works and how decision trees are constructed and traversed.</h4><p>JAX uses the <strong>XLA (Accelerated Linear Algebra)</strong> compiler, which thrives on <strong>static shapes</strong> and predictable, array-based operations.</p><ul><li>In <strong>deep learning </strong>a neural network has a fixed “shape” — we multiply a 1000 times 512 matrix by a 512 times 10 matrix every single time. XLA can optimize this perfectly.</li><li><strong>Tree Algorithms</strong> are inherently <strong>dynamic</strong> and <strong>irregular</strong>. As we build a tree, the data is partitioned into different buckets of varying sizes based on data-dependent conditions (e.g. if feature_x &gt; 0.5).</li></ul><p>Tree algorithms rely heavily on <strong>non-contiguous memory access</strong> and <strong>branching</strong>.</p><ul><li>When a data point traverses a tree, it jumps to different memory locations based on conditional splits.</li><li>GPUs and TPUs (which JAX is designed for) are optimized for “Streaming Multiprocessors” that perform the same operation on a large block of contiguous data simultaneously (SIMD).</li><li>The “if-else” logic of a tree causes <strong>thread divergence</strong>, where the hardware cores have to wait for each other because they are taking different paths through the tree. This negates the parallel processing power JAX is meant to harness.</li></ul><p>Lack of Native Support for Mutable State: JAX is built on a <strong>purely functional</strong> paradigm. In JAX, arrays are <strong>immutable</strong>.</p><ul><li><strong>Tree Building:</strong> Algorithms like XGBoost or LightGBM often update histograms or gain-scores in-place as they iterate through features and thresholds.</li><li><strong>The Conflict:</strong> In JAX, we cannot simply do tree[node] = new_split. We must create a new version of the entire structure using functional updates (like .at[idx].set()). While JAX handles this well for small updates, managing a complex, growing tree structure this way adds significant overhead and complexity.</li><li><strong>The fix: </strong><a href="https://docs.kidger.site/equinox/">Equinox</a>. I defined my trees as eqx.Module objects, transforming my model from a ‘black box’ Python class into a ‘transparent’ PyTree. This allowed me to keep the intuitive structure of an object-oriented model while satisfying JAX’s requirement for purely functional data. This effectively turned a complex, nested tree structure into something JAX could JIT-compile and vectorize without breaking a sweat. Equinox automatically tells JAX which parts to do math on and which parts to treat as fixed constants.</li></ul><pre>class JAX_XGB_Tree(eqx.Module):<br>    # Equinox tracks these arrays as &quot;PyTree leaves&quot;<br>    split_features: jnp.ndarray      <br>    split_thresholds: jnp.ndarray    <br>    leaf_values: jnp.ndarray         <br>    max_depth: int<br><br>    def predict(self, x: jnp.ndarray) -&gt; jnp.ndarray:<br>        # We use a vectorized &#39;walk&#39; through the tree<br>        # No mutable state, just pure array traversal<br>        ...</pre><p>Search vs. Math</p><ul><li><strong>XGBoost/Random Forest</strong> are essentially <strong>search algorithms</strong>. They are searching for the best threshold to split data. This involves lots of sorting, counting, and binning.</li><li><strong>JAX</strong> is a <strong>math library</strong>. It is optimized for gradients and linear algebra. While you <em>can</em> write a search algorithm in JAX using jax.lax.while_loop or jax.lax.cond, these &quot;low-level primitives&quot; are much harder to write and often slower than the highly optimized C++/CUDA kernels used by dedicated libraries like XGBoost.</li></ul><pre># This replaces nested loops over Features and Thresholds<br># vmap transforms &#39;get_gain&#39; into a parallel search grid<br>v_bins = vmap(get_gain, in_axes=(None, 0))<br>v_feats = vmap(v_bins, in_axes=(0, 0))<br><br># Computes gain for ALL features and ALL bins simultaneously</pre><h4>Problem number 2: not enough data</h4><p>This might have been a skill issue on my part but I found that I only had 1,460 rows of data and found it a small data set</p><p>To solve this I used <em>KFold </em>to ensure it hasn’t just memorized the training data, but has actually learned how to predict house prices in general.<br>How it works:<br>If you set n_splits=5, KFold divides your training data into 5 equal-sized blocks (folds). It then runs 5 different “mini-experiments”:<br>Experiment 1: Train on Folds 2,3,4,5 — Test on Fold 1<br>Experiment 2: Train on Folds 1,3,4,5 — Test on Fold 2<br>Experiment 3: Train on Folds 1,2,4,5 — Test on Fold 3<br>Experiment 4: Train on Folds 1,2,3,5 — Test on Fold 4<br>Experiment 5: Train on Folds 1,2,3,4 — Test on Fold 5<br><br>Without KFold: If I just did a single split (e.g., 80% train / 20% test), I might get “lucky” or “unlucky” depending on which houses ended up in my test set and my accuracy score wouldn’t be trustworthy.<br>With KFold: By rotating through the data 5 times, every single house gets a chance to be in the “validation set” exactly once. This gave me a much more stable and honest average score.</p><h4>Problem number 3: I wasn’t as good as I thought I was at building tree algorithms.</h4><p>Skill issue; nothing more, nothing less.</p><p>In the early iterations of this JAX-native project, our model relied on <strong>Decision Stumps</strong>. A stump is a decision tree with a depth of exactly one — it makes a single split on a single feature. I was getting RMSE ~0.150.</p><p>Boosting stumps is a valid form of Gradient Boosting, but it has a massive “intelligence ceiling.” Stumps are purely <strong>additive</strong>. They can learn that <em>“If Square Footage &gt; 2000, add $20k”</em> and <em>“If Neighborhood is CollgCr, add $10k.”</em></p><p>However, real estate is rarely that simple. It is a game of <strong>interactions</strong>. A massive house is only worth a premium <em>if</em> it is also in a good neighborhood and <em>if</em> it was built recently. This is a “multi-question” rule (If A, then if B, then if C). To capture this “synergy,” our model needed depth.</p><p>Implementing depth in JAX is significantly harder than in standard Python. In a typical tree, you use recursion to grow branches. But JAX’s JIT compiler prefers fixed-size structures and loops that it can “unroll.”</p><p>To move past stumps, I had to implement <strong>Level-Wise Growth</strong>. Instead of growing one branch at a time, we upgraded the algorithm to split every node at a specific depth simultaneously.</p><ol><li><strong>The Root:</strong> We start with a mask of all True (all houses).</li><li><strong>The Split:</strong> We find the best feature/threshold and create two new masks: Left = Mask &amp; (Value &lt;= Threshold) and Right = Mask &amp; (Value &gt; Threshold).</li><li><strong>The Depth:</strong> As we moved from Depth 1 to Depth 3, we iterated through these masks, “sieving” the houses deeper into the tree structure.</li></ol><p>The shift from Depth 1 to Depth 3 was the <strong>single most impactful change</strong> in the project’s history.</p><ul><li><strong>With Stumps:</strong> The model was stuck at an RMSE of ~0.150 because it couldn’t see how features worked together.</li><li><strong>With Multi-Depth Trees:</strong> The RMSE plummeted to ~0.123.</li></ul><p>By adding depth, we allowed the JAX engine to capture <strong>high-order interactions</strong>. It stopped looking at features in isolation and started understanding the “personality” of a house — how quality, size, and age combine to create value.</p><p>A stump only needs one feature and one threshold. A tree of depth k needs to store 2k-1 splits. We moved from single scalars to arrays to store the entire tree structure.</p><pre>class JAX_XGB_Tree(eqx.Module):<br>    # Instead of &#39;split_feature: int&#39;, we use arrays to hold every node<br>    split_features: jnp.ndarray      # Shape: (7,) for Depth 3<br>    split_thresholds: jnp.ndarray    # Shape: (7,)<br>    leaf_values: jnp.ndarray         # Shape: (8,) <br>    max_depth: int</pre><p>The “Binary Sieve” (The Level-Wise Growth)<br>This is the “Search” part of the algorithm. Instead of finding one best split for the whole dataset, we iterate through the depth, creating masks that act like a sieve to filter data into smaller and smaller subsets.</p><pre># Start with every house at the Root<br>node_masks = [jnp.ones(n_samples, dtype=bool)]<br><br>curr_node_idx = 0<br>for d in range(self.max_depth): # The loop that creates depth<br>    next_masks = []<br>    for m in node_masks:       # Iterate through every node at the current level<br>        # FIND BEST SPLIT only for the houses in this specific mask &#39;m&#39;<br>        f, t = self._find_best_split(X, G, H, self.bins, m)<br>        <br>        s_feats[curr_node_idx], s_thrs[curr_node_idx] = int(f), float(t)<br>        <br>        # SIEVE: Create masks for the children (Left/Right)<br>        next_masks.append(m &amp; (X[:, int(f)] &lt;= float(t))) # Left child mask<br>        next_masks.append(m &amp; (X[:, int(f)] &gt; float(t)))  # Right child mask<br>        <br>        curr_node_idx += 1<br>    node_masks = next_masks # Move to the next level down</pre><p>The Masked Gain Search (The Interaction Logic)<br>For a tree to have depth, the split at “Level 2” must know what happened at “Level 1.” We updated the Gain formula to ignore any houses that didn’t reach the current node using the mask.</p><pre>@partial(jit, static_argnums=(0,))<br>def _find_best_split(self, X, G, H, bins, mask):<br>    def get_gain(feat_idx, threshold):<br>        # m_l and m_r represent the subset of the subset<br>        m_l = (X[:, feat_idx] &lt;= threshold) &amp; mask <br>        <br>        # Calculate G and H only for houses that reached THIS branch<br>        G_l, H_l = jnp.sum(G * m_l), jnp.sum(H * m_l)<br>        <br>        # ... standard XGBoost Gain math ...</pre><p>The Vectorized Traversal (The Prediction)<br>When it’s time to predict, a house can’t just look at one rule. It has to “walk” down the tree. We used Node Indexing Math (2 * node_idx + 1 + go_right) to navigate the arrays without using Python branching.</p><pre>def predict(self, x: jnp.ndarray) -&gt; jnp.ndarray:<br>    @jit<br>    def walk_tree(sample):<br>        node_idx = 0<br>        for _ in range(self.max_depth): # Step through the levels<br>            f = self.split_features[node_idx]<br>            t = self.split_thresholds[node_idx]<br>            <br>            # Determine direction<br>            go_right = sample[f] &gt; t<br>            <br>            # Binary tree indexing logic:<br>            # Move to the left child or right child in the flat array<br>            node_idx = 2 * node_idx + 1 + go_right.astype(jnp.int32)<br>            <br>        return self.leaf_values[node_idx - (2**self.max_depth - 1)]<br>    return vmap(walk_tree)(x)</pre><p>This is not a state of the art solution (SOTA) and the results is around the top 40% mark on the kaggle leaderboard. I will challenge myself to be ranked as high as possible with a future model but that’s another article :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tt-y0XoGVwByl-h_8rC4Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ccc3aa18de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JAX talks #2: JAX vs NumPy - There’s a new kid on the block]]></title>
            <link>https://medium.com/@noor_yadallee/jax-talks-2-jax-vs-numpy-theres-a-new-kid-on-the-block-86f6cde2da10?source=rss-f848f8f4c24c------2</link>
            <guid isPermaLink="false">https://medium.com/p/86f6cde2da10</guid>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google-deepmind]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Noor Mohammad Yadallee]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 22:06:38 GMT</pubDate>
            <atom:updated>2025-12-02T22:06:38.435Z</atom:updated>
            <content:encoded><![CDATA[<p><em>NumPy has long been the King of Python libraries for linear algebra. But in the era of LLMs and massive parallel computing, a challenger has arrived. JAX isn’t just a NumPy alternative — it’s a compiler that gives your Python code superpowers. Here is why you might need to switch.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6nHSeTcNOZqexIhp5jo1Q.png" /></figure><h4>What makes JAX tick?</h4><p>JAX provides a set of functional transformations that truly feel like magic when used correctly. These transformations often take in a function and return a new and improved function that now has super powers.</p><p><strong>jax.jit</strong></p><p>When you wrap a function in jax.jit, you are asking JAX to watch the function run once, trace its abstract logic, and then fuse that logic into a solid diamond of machine code via XLA (Accelerated Linear Algebra).</p><p>It freezes the volatile Python logic into a static, computational graph. It fuses operations together — combining a multiplication and an addition into a single hardware instruction — eliminating the overhead of Python entirely.</p><pre>import jax<br>import jax.numpy as jnp<br><br>def selu(x, alpha=1.67, lambda_=1.05):<br>  return lambda_ * jnp.where(x &gt; 0, x, alpha * jnp.exp(x) - alpha)<br><br>x = jnp.arange(1000000)<br>%timeit selu(x).block_until_ready()<br># &gt;&gt;&gt;649 μs ± 2.74 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)<br><br># jax.jit the function<br>selu_jit = jax.jit(selu)<br><br># Pre-compile the function before timing...<br>selu_jit(x).block_until_ready()<br><br>%timeit selu_jit(x).block_until_ready()<br># &gt;&gt;&gt;649 μs ± 2.74 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)</pre><p>jax.jit can also be used as a decorator</p><pre># While loop conditioned on x and n with a jitted body.<br><br>@jax.jit<br>def loop_body(prev_i):<br>  return prev_i + 1<br><br>def g_inner_jitted(x, n):<br>  i = 0<br>  while i &lt; n:<br>    i = loop_body(i)<br>  return x + i<br><br>g_inner_jitted(10, 20)</pre><p>The jit compiler leverages caching in order to increase the overall performance of the code. There is an initial startup overhead due to the first calls made but the compilations made are the stored and reused in the future.</p><p>Suppose we define f = jax.jit(g). Upon defining the function, the initial execution triggers the compilation process and caches the resulting XLA executable. All future calls bypass this overhead by retrieving the pre-compiled code directly from the cache.</p><p>We must not treat jax.jit as a big red button that makes everything goes fast, because it cannot. It traces your logic, maps out operations and freezes everything into a static graph. If there is something that cannot be frozen such as a runtime valuesjax.jit will fail.</p><pre>@jax.jit<br>def f(x):<br>    if x &gt; 0:  # &lt;--- Error!<br>        return x<br>    else:<br>        return 0</pre><p>JAX will crash. Why? Because during tracing, x is not a number like 5 or -5. It is an abstract Tracer object with no concrete value. Python asks, “Is this Tracer greater than zero?” and JAX has to answer, “I don’t know yet; I’m just building the graph.”</p><p><strong>The Workaround:</strong> You must use JAX’s specific control flow operators (like jax.lax.cond or jax.lax.scan), which bake the logic into the graph rather than resolving it in Python.</p><p>The Mandelbrot set fractal (zn+1 = zn² + c) is a good illustration of this power due to the high computational power needed to deal with the large number of computations born from the multiplications and addition operations needed during each iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*1F7FbW0UnHiS-60kHuxOkw.png" /><figcaption>32 iteration mandelbrot fractal</figcaption></figure><p>The entire code is available in this <a href="https://colab.research.google.com/drive/1pURIqAsYwsaCtyOyDHCLmayiVqccEYb9#scrollTo=LG8qE0UDlXuk">colab notebook</a>.</p><p>We have compared the performance of a pure NumPy implementation vs a JAX implementation and here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*kjNPAzoE1a9IguvyOW9tEQ.png" /><figcaption>Comparison for computation of mandelbrot fractals</figcaption></figure><p><strong>jax.grad</strong></p><p>Computing gradients is a critical part of modern machine learning methods, and jax.grad makes it easy to compute higher-order derivatives,</p><p><a href="https://docs.jax.dev/en/latest/_autosummary/jax.grad.html#jax.grad">jax.grad()</a> takes a function and returns a function. If you have a Python function f that evaluates the mathematical function , then jax.grad(f) is a Python function that evaluates the mathematical function ∇𝑓 . That means grad(f)(x) represents the value ∇𝑓(𝑥). Since jax.grad() operates on functions, you can apply it to its own output to differentiate as many times as you like:</p><pre>import jax<br>import jax.numpy as jnp<br>from jax import grad<br><br>grad_tanh = grad(jnp.tanh)<br>print(grad_tanh(2.0))<br>print(grad(grad(jnp.tanh))(2.0))<br>print(grad(grad(grad(jnp.tanh)))(2.0))<br><br>#&gt;&gt;&gt; 0.070650816<br>#&gt;&gt;&gt; -0.13621868<br>#&gt;&gt;&gt; 0.25265405</pre><p>To illustrate this in a practical manner as well as show the performance gain as well as the number of lines till working prototype (if that’s a metric you care about) here is an implementation of a Multi Layer Perceptron in pure NumPy vs using JAX in this <a href="https://colab.research.google.com/drive/1pURIqAsYwsaCtyOyDHCLmayiVqccEYb9#scrollTo=oRy1OIDSnn6e">colab </a>(still the same link but under Round 2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko3rziWBcBFZi56MJOgxiw.png" /><figcaption>MLP NumPy— execution time 91.7954s</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7jixFH9gD6RNjjhCsntoQ.png" /><figcaption>MLP JAX — execution time 49.3866s</figcaption></figure><p><strong>jax.vmap</strong></p><p>Humans think in loops. We write code that says:<br><em>“Take the first number, add 5. Now take the second number, add 5. Now the third…”</em></p><p>To a computer, this is inefficient. It is like a grocery clerk scanning 100 cans of soup one by one. <em>Beep. Beep. Beep.</em></p><p><em>Auto-vectorization</em> is when the compiler looks at your loop and realizes it can cheat.It sees that you are doing the exact same math to a long list of numbers. So, without you asking, it rewrites your instructions. Instead of “add 5 to this one,” it issues a command: <em>“Take these 8 numbers and add 5 to all of them simultaneously.”</em></p><p>It transforms the grocery clerk’s scanner into a wide-beam laser that scans 8 cans of soup in a single flash.</p><p>JAX natively provides automatic vectorization via the jax.vmap transformation. Lets see a scenario where vmap’s superpowers are on full display:</p><p>Imagine you’re a developer working for a drone delivery startup. Your task is to implement a simulation component that estimates the fuel consumption and time taken for a single drone flight between a depot and a customer location. You’ve been given a simplified function to calculate these metrics for a single flight</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*8BqySrMgYJEV9CZqkHoKaA.png" /><figcaption>Drone flight calculation code</figcaption></figure><p>Now, the head of operations comes to you with a request: “We’ve got a list of <strong>50,000</strong> potential customer delivery routes and their corresponding package weights. We need to quickly run a simulation for all of them to estimate total fuel needs and operational time for the day.”</p><p>Results for round 3 of NumPy vs jax (still available in the <a href="https://colab.research.google.com/drive/1pURIqAsYwsaCtyOyDHCLmayiVqccEYb9#scrollTo=PDTWDmwdU_vV">colab</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*UV984d2TxUI3ghiCTqukaw.png" /><figcaption>JAX annihilates NumPy circa 2025</figcaption></figure><p>This is just a glimpse of the power of JAX and there is still the parallelization function transformations such as jax.pmapthat have not yet been covered.</p><p>jax.pmap compiles a function using XLA (similar to jax.jit) and then executes it in parallel across multiple XLA devices, such as multiple GPUs or TPU cores but this is an article for another day (NumPy has been seen fleeing from a <em>back door</em> access)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOWTQQHqHeWvpjFMhqDP4A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f6cde2da10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JAX talks #1: Google’s secret sauce for Gemini, Waymo and Nobel Prizes]]></title>
            <link>https://medium.com/@noor_yadallee/jax-talks-1-googles-secret-sauce-for-gemini-waymo-and-nobel-prizes-478051fa45c2?source=rss-f848f8f4c24c------2</link>
            <guid isPermaLink="false">https://medium.com/p/478051fa45c2</guid>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Noor Mohammad Yadallee]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 21:42:40 GMT</pubDate>
            <atom:updated>2025-11-16T21:42:40.671Z</atom:updated>
            <content:encoded><![CDATA[<p>Google’s current dominance in the AI landscape isn’t a sudden achievement; it’s the direct result of years of intensive, large-scale experience forged in the crucible of real-world challenges through iterations of frameworks like TensorFlow.</p><p>As AI research progressed, the models and datasets ballooned from gigabytes to petabytes, demanding a computational paradigm shift. Google was uniquely positioned at this frontier, dealing with massive, unprecedented scales that pushed the limits of existing technology.</p><p>The company realized that to continue innovating at this dizzying pace, it needed more than just an incrementally better tool. It required an ecosystem that brought speed, flexibility, and composability. Researchers and production engineers alike needed to quickly prototype novel architectures and seamlessly transition those ideas into globally deployed products.</p><p>These demands became the north star for Google to build JAX and its ecosystem.</p><h3>What is JAX?</h3><p>It is a high-performance numerical computing library for accelerator (i,e GPUs and TPUs) oriented array computation which means performing operations on entire arrays (or multi-dimensional arrays, like matrices and tensors) at once, rather than processing each element individually using explicit loops.<br>It is also used for scientific computing, Machine Learning (ML), simulations and anything that leverages Linear Algebra.</p><p>JAX has a number of key concepts that make it what it is, one of which are function transformations (often just called a “transformation”). A transformation basically is a <strong>higher-order function</strong> that takes one or more functions as input and returns a new, transformed function as output.</p><p>Instead of taking data and producing data, JAX transformations take your Python functions and produce <em>new </em>functions that have enhanced capabilities, often related to performance, differentiation, or parallelism.</p><p>JAX is also the heartbeat of a vivid and rapidly expanding ecosystem that is built on top of it.</p><h3>The value proposition of JAX</h3><p>The core value proposition of JAX is its ability to deliver <strong>high-performance, scalable, and flexible numerical computing</strong> by fundamentally transforming the way Python code is executed.</p><h3>Who uses JAX?</h3><p>JAX is used by various Google teams such as DeepMind and Waymo to bring State of The Art performance to their products. Here we have some code repositories and research papers that showcase how JAX has been used:</p><ul><li><a href="https://arxiv.org/abs/2312.11805">Gemini: A Family of Highly Capable Multimodal Models</a></li><li>The paper that birthed Visual Language Models <a href="https://arxiv.org/pdf/2010.11929">An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale</a></li><li><a href="https://waymo.com/blog/2023/10/waymo-advances-ai-research-with-our-multifunctional-waymax-simulator">Waymo’s simulator</a> is built on JAX</li><li>Nobel prize winning model <a href="https://github.com/google-deepmind/alphafold">AlphaFold</a> uses JAX</li></ul><h3>Foundational principles of JAX</h3><p><strong>XLA (Accelerated Linear Algebra)</strong> is a specialized compiler developed by Google to drastically improve the speed and efficiency of numerical computations, particularly those involving linear algebra, across various hardware accelerators like <strong>GPUs</strong> and <strong>TPUs</strong>.</p><p>XLA provides a significant performance boost through two main mechanisms:</p><ol><li><strong>Optimization and Execution:</strong> XLA eliminates interpreter overhead by compiling high-level mathematical operations directly into highly optimized, <strong>device-specific machine code</strong>. This enables aggressive optimizations, such as <strong>operator fusion</strong> (combining multiple operations into a single kernel), which results in substantially faster execution speeds on CPUs, GPUs, and TPUs. It also improves <strong>memory efficiency</strong> by carefully optimizing memory allocation and reuse.</li><li><strong>Hardware Portability and Specialization:</strong> XLA acts as a unified compilation layer. It ensures that machine learning models can run efficiently on diverse hardware without requiring users to make manual, hardware-specific code changes. It generates code that is precisely <strong>tailored to the target device</strong>, maximizing hardware utilization and overall performance.</li></ol><p><strong>Just in time compilation: </strong>JAX’s JIT compilation is achieved through a rigid, multi-stage compiler workflow. This process begins with <a href="https://docs.jax.dev/en/latest/tracing.html"><em>tracing</em></a>, where the high-level Python function is abstractly executed using <a href="https://docs.jax.dev/en/latest/tracing.html"><em>tracers</em> </a>to capture the computation as a static, pure internal graph called jaxpr(pronounced jaxper). JAX’s jit is called using @jax.jitdecorator and runs the function once using tracers and<strong> </strong>captures the sequence of computational operations into an intermediate representation, a computational graph. This graph must be static so JAX create constraints such as dynamic conditions must be avoided and all functions must be pure else we will not get the performance benefits we desire.</p><pre>&quot;&quot;&quot;<br>Code to view jaxpr for a function func1<br>&quot;&quot;&quot;<br><br>from jax import make_jaxpr<br>import jax.numpy as jnp<br>def func1(first, second):<br>  temp = first + jnp.sin(second) * 3.<br>  return jnp.sum(temp)<br>print(make_jaxpr(func1) (jnp.zeros(8), jnp.ones(8)))</pre><pre>&quot;&quot;&quot;<br>Resulting jaxpr for func1<br>&quot;&quot;&quot;<br><br>{lambda; a:f32[8] b:f32[8]. let<br>  c:f32[8] = sin b<br>  d:f32[8] = mul c 3.0:f32[]<br>  e:f32[8] = add a d<br>  f:f32[] = reduce_sum[axes=(0,) out_sharding=None] e<br>in (f,) }</pre><p>This jaxpr is then passed to the XLA compiler infrastructure, where it is translated into the <strong>High-Level Optimizer (HLO)</strong> Intermediate Representation (IR), which represents the program as a tensor-centric computational graph.</p><p>The XLA compiler then executes intensive, target-specific optimizations, such as <strong>Operator Fusion</strong>, on this HLO graph to generate highly efficient machine code tailored for hardware accelerators like GPUs and TPUs. This process combines multiple mathematical operations into a single device kernel, thereby eliminating redundant memory transfers and maximizing hardware utilization.</p><p>Crucially, this compilation process views the forward computation and the complex derivative operations required for auto-differentiation (the backward pass) as a single, unified HLO graph, guaranteeing that the resulting compiled binary is comprehensively optimized across the entire workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*IyaFdqiuRDtApP-8GJUD5Q.png" /><figcaption>Compilation flow</figcaption></figure><p>This compilation process allows us to overcome one of interpreted Python’s main weaknesses: speed. Python is merely the “front end” and Jax delegates the heavy, performance-critical numerical work to the XLA compiler that runs directly on the accelerators. This enables JAX code to have performance similar to or even better than the speed demon that is C++ for certain use cases. This performance is often seen in Numerical/Array Computing.</p><p><strong>Automatic differentiation </strong>is leveraged using composable <em>function</em><strong><em> </em></strong><em>transformations</em> built upon <em>functional programming principles</em>. This design allows it to compute exact derivatives efficiently for virtually any function written in JAX/NumPy, including those with complex Python control flow.</p><p><strong>Familiarity First (The NumPy API): </strong>JAX provides a NumPy-like API, accessible through jax.numpy. This API aims to be largely compatible with the standard NumPy API, allowing users familiar with NumPy to easily transition to JAX in order to build high-performance numerical computing and machine learning, particularly on accelerators like GPUs and TPUs. Since it is also used through python, the speed at which teams will iterate and develop solutions is exponentially faster than solutions in other languages such as C++.</p><h3>Is it all sunshine and rainbows?</h3><h4>Steep learning curve and mental model shift</h4><p>JAX’s pursuit of maximum performance is predicated on a strict <strong>functional programming paradigm</strong>, which fundamentally alters how developers approach code structure, state management, and debugging.</p><p>Some shifts developers need to get used to:</p><ul><li><strong>Mandate of Functional Purity:</strong> JAX functions that are to be transformed (e.g., JIT-compiled or differentiated) must be “pure,” meaning their output is determined exclusively by their input parameters, and they must have <strong>no side effects</strong>. This is a major departure from common imperative practices.</li><li><strong>Explicit State Management (PyTrees):</strong> Since functions cannot mutate state in place, all mutable data — such as model weights, batch normalization statistics, or optimizer states — must be explicitly bundled into data structures called PyTrees (Python Trees). This PyTree is passed <em>into</em> the function as an argument, and a <em>new</em> PyTree containing the updated state is returned. This process is architecturally clean but adds manual complexity for tasks that are hidden automatically in object-oriented frameworks.</li></ul><h4>JIT/Tracing Limitations</h4><p>The performance benefits of JAX are contingent upon the Just-In-Time (JIT) compilation process, which converts Python code into a static computational graph (JAXPR) that the XLA compiler can optimize. This process imposes constraints on the structure of the Python code:</p><ul><li><strong>Initial Compilation Overhead:</strong> The aggressive compilation process — which includes tracing, generating JAXPR, and XLA kernel fusion — is computationally expensive and can introduce a <strong>significant latency</strong> during the <em>first</em> execution of a JIT-compiled function. For small functions or scenarios where the compiled function is called infrequently, this compilation cost may entirely outweigh the subsequent execution speed benefits.</li><li><strong>Static Shapes Requirement:</strong> JIT compilation relies on the assumption that the shape and data type of input arrays are <strong>static and known at the time of tracing</strong>. If the function is called with inputs of different shapes, the JAX tracing process must trigger a <strong>re-compilation</strong> of a new kernel, causing unexpected and undesirable delays in performance.</li><li><strong>Restricted Control Flow:</strong> Python control flow structures like if, elif, and while loops are problematic if the decision logic depends on the <em>value</em> of a JAX array. If the control flow is dependent on an array&#39;s value, it must be resolved during the initial trace, leading to inefficient or incorrect compilation. Developers must instead use JAX-specific, functional control flow primitives like jax.lax.cond and jax.lax.scan to ensure the entire operation can be compiled into a single, static kernel.</li><li><strong>Silent Side Effects:</strong> If an impure function containing side effects (such as Python print statements or global variable mutations) is JIT-compiled, the side effects will only execute during the <strong>initial tracing</strong>,. On subsequent high-speed calls using the cached XLA kernel, these side effects will be skipped entirely. This can lead to unexpected behavior and complicate debugging. Furthermore, stateful Python objects like <strong>iterators</strong> are incompatible with JIT and its control-flow primitives.</li></ul><h4>Ecosystem Maturity and Complexity</h4><p>JAX is the core engine, but it requires surrounding libraries to function as a complete machine learning framework.</p><ul><li><strong>Modularization and Fragmentation:</strong> JAX deliberately focuses on being a high-performance numerical computation and differentiation library. It does not natively provide high-level abstractions for defining neural networks, layers, or optimizers. Instead, developers must adopt a specialized, modularized ecosystem (e.g., Flax, Haiku, or Equinox for models, and Optax for optimization). While offering flexibility, this approach is more complex for users accustomed to integrated, all-in-one frameworks.</li><li><strong>Smaller Community and Fewer Resources:</strong> Compared to more established frameworks like PyTorch, JAX has been available for a shorter time and has a smaller overall community. This historically means <strong>fewer pre-trained models, tutorials, and ready-made solutions</strong> for specific domain tasks (like extensive computer vision or NLP model collections).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATgsPsRVM4ZquRlEpk_T5A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478051fa45c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>