<?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 Harshita Sharma on Medium]]></title>
        <description><![CDATA[Stories by Harshita Sharma on Medium]]></description>
        <link>https://medium.com/@harshitasharma_ai?source=rss-a97a7ac74ac9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JtlmG97_-RgTb9xuiY2RYw.jpeg</url>
            <title>Stories by Harshita Sharma on Medium</title>
            <link>https://medium.com/@harshitasharma_ai?source=rss-a97a7ac74ac9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:56:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshitasharma_ai/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 Docker Image to Self-Retraining Model: CI/CD for MLOps with Evaluation Gates]]></title>
            <link>https://medium.com/@harshitasharma_ai/from-docker-image-to-self-retraining-model-ci-cd-for-mlops-with-evaluation-gates-384a4dd0875b?source=rss-a97a7ac74ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/384a4dd0875b</guid>
            <category><![CDATA[aiops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Harshita Sharma]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 09:31:01 GMT</pubDate>
            <atom:updated>2026-11-29T09:31:01.605Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2: automated pipelines, PySpark environments, versioned libraries and multi-stage, multi-cloud deployment</em></p><h3>Where we left off</h3><p>In Part 1 we opened up docker build: layers, dependency resolution, wheels, and what happens when pip has to compile. We ended with a clean, reproducible training image tagged with a git commit.</p><p>An image on its own doesn’t retrain anything, though. Someone still has to run it, decide whether the new model is any good, and get it safely into production. If that someone is a person with a notebook, you have a process that works until the day they go on holiday.</p><p>This post turns that image into a system that retrains itself and refuses to ship a worse model. We’ll cover:</p><ul><li>the <strong>three loops</strong> of ML automation: CI, continuous training (CT) and CD;</li><li>packaging shared code as a <strong>versioned library</strong> and publishing it safely;</li><li>keeping <strong>Python environments consistent on PySpark</strong> clusters;</li><li><strong>evaluation gates</strong> that block bad models automatically;</li><li><strong>multi-stage deployment</strong> from dev to staging to production;</li><li>staying portable across <strong>different runtimes and clouds</strong>.</li></ul><p>It’s written for data scientists who are comfortable with models but new to the plumbing around them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPJ9rits7DGBLJkcM60Kyg@2x.png" /></figure><h3>Three loops, not one</h3><p>The biggest mental shift from software CI/CD is that ML systems change for <strong>two</strong> reasons: someone changes the <em>code</em>, or the world changes the <em>data</em>. Google’s MLOps guide splits the automation into three practices: continuous integration (CI), continuous delivery (CD) and <strong>continuous training (CT)</strong>. I find it easiest to think of them as three loops:</p><p><em>[Image: the three loops: CI for code, CT for models, CD for deployment]</em></p><ul><li><strong>CI (the code loop).</strong> Triggered by a pull request or merge. Runs linting, unit tests and data-validation tests, builds the image and library, and smoke-trains on a sample. Produces a tested, versioned image and wheel.</li><li><strong>CT (the model loop).</strong> Triggered by a schedule, a drift alert or new labelled data. Runs the <em>already-tested</em> image on fresh data, evaluates the result, applies the gate and registers the model. Produces a new model version, or a rejected one.</li><li><strong>CD (the deployment loop).</strong> Triggered by a model passing the gate, or a release tag. Promotes dev → staging → prod with a canary, monitoring and rollback. Produces a model serving real traffic.</li></ul><p>Keeping them separate is what makes failures easy to explain. If a retrain produces a worse model, you know the cause is the <strong>data</strong>, because the code and environment are exactly the image CI already tested. If CI fails, it’s the <strong>code</strong>. Mixing the two loops (“just retrain in the PR pipeline”) makes every failure a guessing game.</p><p>Google describes maturity in three steps: level 0 (everything manual), level 1 (the training pipeline is automated, so CT exists) and level 2 (the <em>pipeline itself</em> is delivered by CI/CD). This post is about getting to level 2.</p><h3>Step 1: put shared code in a versioned library</h3><p>Most ML projects start as notebooks that copy-paste the same feature functions. Then training computes a feature one way and the serving API computes it slightly differently, and the model quietly degrades. This is <strong>training/serving skew</strong>, one of the classic forms of ML technical debt.</p><p>The fix is boring and effective: move shared logic (feature engineering, data validation, metrics) into a small Python package, and have <em>every</em> consumer install the same version.</p><pre>churn-ml/<br>  src/churn_features/        # the library: features, validation, metrics<br>  pipelines/train.py         # training entry point (uses the library)<br>  pipelines/evaluate.py<br>  serving/app.py             # serving API (uses the same library)<br>  tests/<br>  pyproject.toml<br>  requirements.lock          # exact pins for the image<br>  Dockerfile<br>  .github/workflows/</pre><h3>Publishing it safely</h3><ol><li><strong>Declare it</strong> in pyproject.toml with a name, a version (SemVer: MAJOR.MINOR.PATCH) and dependency <em>ranges</em>, because a library has to coexist with other packages.</li><li><strong>Build</strong> a wheel and sdist with python -m build, then install the wheel into a clean environment and run the tests against <em>it</em>, not your source folder.</li><li><strong>Publish from CI, never from a laptop</strong>, on a git tag such as v1.4.0. For internal code, publish to a private index (Artifactory, Nexus, Azure Artifacts, AWS CodeArtifact, GitLab).</li><li><strong>Use trusted publishing instead of stored API tokens</strong> where your index supports it. PyPI’s trusted publishing uses OpenID Connect: GitHub Actions proves its identity and receives a short-lived token, so there’s no long-lived secret to leak. PyPI also recommends restricting releases to a dedicated GitHub environment, which can require manual approval.</li></ol><pre># .github/workflows/release-lib.yml (outline)<br>on:<br>  push:<br>    tags: [&quot;v*&quot;]<br>jobs:<br>  publish:<br>    runs-on: ubuntu-latest<br>    environment: pypi            # can require a reviewer&#39;s approval<br>    permissions:<br>      id-token: write            # required for trusted publishing<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: pip install build &amp;&amp; python -m build<br>      - run: pip install dist/*.whl pytest &amp;&amp; pytest<br>      - uses: pypa/gh-action-pypi-publish@release/v1</pre><p>Versions are immutable: you never overwrite 1.4.0, you release 1.4.1. That&#39;s what lets the training image and the serving image pin churn-features==1.4.0 and know they are running identical feature code.</p><h3>Step 2: Python environments on PySpark (the part that bites)</h3><p>On a single machine there is one Python. On a Spark cluster there are many: the <strong>driver</strong> runs your script, and every <strong>executor</strong> starts its own Python workers to run UDFs and pandas code. They all need the same Python version and the same packages, or you get errors such as a worker reporting a different Python version than the driver, or an ImportError that only appears on executors.</p><p>Four rules prevent most of the pain:</p><ol><li><strong>Match </strong><strong>pyspark to the cluster&#39;s Spark version.</strong> The client library in your image or CI must be the same major/minor version as the cluster.</li><li><strong>Pin </strong><strong>pandas and </strong><strong>pyarrow together.</strong> pandas UDFs move data through Arrow, so incompatible versions break at runtime, not at install time.</li><li><strong>Treat your library as a wheel</strong>, built once in CI, and install that exact file on the cluster.</li><li><strong>Test locally with a real (tiny) Spark session</strong> in CI, not just mocked pandas.</li></ol><h3>Four ways to ship the environment</h3><ul><li><strong>Managed runtimes (Databricks, EMR, Dataproc).</strong> Pick a pinned runtime version, which fixes Python, Spark and the base libraries together. Then install your own wheel as a job or cluster library. This is the simplest option and the most common.</li><li><strong>Packed environments.</strong> The Spark docs describe shipping a packed Conda environment (conda-pack), a virtualenv (venv-pack) or a PEX file. The archive is passed with --archives (or spark.archives) and unpacked on the executors. The simple --py-files route can&#39;t include wheels with native code, which rules it out for most data-science stacks.</li><li><strong>Container images on Kubernetes.</strong> Build one image containing Python, pyspark and your libraries, and use it for both the driver and the executors (spark.kubernetes.container.image). This is Part 1&#39;s Docker discipline applied to a whole cluster.</li><li><strong>Spark Connect.</strong> A thin client talks to a remote Spark server. Databricks describes session-level dependency management for Spark Connect with Conda, venv or PEX, so clients don’t need the full Spark installation.</li></ul><pre># Packed virtualenv shipped to YARN or Kubernetes executors<br>python -m venv pyspark_venv &amp;&amp; source pyspark_venv/bin/activate<br>pip install -r requirements.lock dist/churn_features-1.4.0-py3-none-any.whl venv-pack<br>venv-pack -o pyspark_venv.tar.gz</pre><pre>export PYSPARK_DRIVER_PYTHON=python<br>export PYSPARK_PYTHON=./environment/bin/python<br>spark-submit --archives pyspark_venv.tar.gz#environment pipelines/train.py</pre><h3>Testing PySpark code in CI</h3><pre># tests/conftest.py<br>import pytest<br>from pyspark.sql import SparkSession</pre><pre>@pytest.fixture(scope=&quot;session&quot;)<br>def spark():<br>    return (SparkSession.builder.master(&quot;local[2]&quot;)<br>            .appName(&quot;tests&quot;).getOrCreate())</pre><pre># tests/test_features.py<br>from churn_features.features import add_tenure_bucket</pre><pre>def test_tenure_bucket(spark):<br>    df = spark.createDataFrame([(1,), (25,)], [&quot;tenure_months&quot;])<br>    out = add_tenure_bucket(df).collect()<br>    assert [r.tenure_bucket for r in out] == [&quot;new&quot;, &quot;loyal&quot;]</pre><p>A local two-core session is slow to start (a few seconds) but catches schema, null-handling and UDF errors long before they reach a cluster.</p><h3>Step 3: the CI loop, testing code before it can train anything</h3><p>CI answers one question: <em>is this code safe to train with?</em> It never answers “is this model good?”. That’s the CT loop’s job.</p><p>What to test (Google’s <em>ML Test Score</em> paper lists 28 tests across data, model, infrastructure and monitoring; these are the ones worth starting with):</p><ul><li><strong>Unit tests</strong> for feature functions, metrics and data-validation rules.</li><li><strong>Schema and data tests</strong>: expected columns and types, value ranges, null rates, on a small fixture dataset.</li><li><strong>Image tests</strong>: the image builds, imports work, and the entry point starts.</li><li><strong>A smoke-train</strong>: train on about 1,000 rows inside the image and check that a model artefact appears and predicts the right shape. This catches broken pipelines in minutes rather than after a three-hour cluster run.</li></ul><pre># .github/workflows/ci.yml (outline)<br>on: [pull_request, push]<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: actions/setup-python@v5<br>        with: { python-version: &quot;3.11&quot; }<br>      - run: pip install -r requirements.lock -e . pytest ruff<br>      - run: ruff check .<br>      - run: pytest tests/                       # includes local-Spark tests</pre><pre>  build:<br>    needs: test<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: python -m pip install build &amp;&amp; python -m build      # wheel<br>      - run: docker build -t $REGISTRY/churn-train:${{ github.sha }} .<br>      - run: docker run $REGISTRY/churn-train:${{ github.sha }} python -m pipelines.train --sample<br>      - run: docker push $REGISTRY/churn-train:${{ github.sha }}  # only after the smoke-train passes</pre><p>The output of CI is an <strong>immutable artefact</strong>: an image tagged with the commit SHA (plus the library wheel). Every later stage uses that exact artefact. Nothing is rebuilt between staging and production.</p><h3>Step 4: the CT loop, automated retraining with evaluation gates</h3><p>The retraining pipeline is a short, boring sequence of steps, and boring is the goal:</p><ol><li><strong>Trigger</strong>: a schedule (weekly), a drift alert from monitoring, or enough new labelled data.</li><li><strong>Validate the data</strong>: schema, volume and null-rate checks. A broken upstream table should stop the run here, not produce a confidently wrong model.</li><li><strong>Train</strong> using the CI-tested image, recording the data snapshot, the commit SHA and the hyperparameters.</li><li><strong>Evaluate</strong> the candidate (the <em>challenger</em>) on a fixed evaluation set, alongside the current production model (the <em>champion</em>) and a simple baseline.</li><li><strong>Gate</strong>: if the challenger isn’t good enough, the step exits with a non-zero code and the pipeline stops.</li><li><strong>Register</strong> the passing model as a new version with a challenger alias, ready for CD.</li></ol><h3>Writing the gate</h3><p>Decide the rules <strong>before</strong> you see the results, and write them down in code:</p><pre># pipelines/evaluate.py<br>import sys, mlflow</pre><pre>FLOOR, TOLERANCE = 0.80, 0.005</pre><pre>challenger = evaluate(candidate_model, eval_set)       # e.g. AUC<br>champion   = evaluate(load_alias(&quot;churn&quot;, &quot;champion&quot;), eval_set)<br>baseline   = evaluate(rule_based_baseline, eval_set)</pre><pre>mlflow.log_metrics({&quot;challenger&quot;: challenger, &quot;champion&quot;: champion, &quot;baseline&quot;: baseline})</pre><pre>reasons = []<br>if challenger &lt; FLOOR:                  reasons.append(&quot;below absolute floor&quot;)<br>if challenger &lt; champion - TOLERANCE:   reasons.append(&quot;worse than champion&quot;)<br>if challenger &lt;= baseline:              reasons.append(&quot;does not beat baseline&quot;)</pre><pre>if reasons:<br>    print(&quot;GATE FAILED:&quot;, &quot;; &quot;.join(reasons))<br>    sys.exit(1)          # the pipeline stops; nothing is registered<br>print(&quot;GATE PASSED&quot;)</pre><p>Three details make the difference between a gate and a decoration:</p><ul><li><strong>It fails closed.</strong> A non-zero exit stops everything downstream. No “register with a warning” and no automatic retry of a deliberate failure.</li><li><strong>It checks more than one metric.</strong> Add slice metrics (per region, per customer segment), latency and model size. A model that’s better on average but much worse for one segment is a regression.</li><li><strong>It never moves the goalposts.</strong> If the gate fails, the fix is better data or code, not a lower threshold.</li></ul><h3>Where to run it</h3><p>Any orchestrator that runs containers on a schedule works: Databricks Workflows, Airflow, Kubeflow or Vertex AI Pipelines, Azure ML pipelines, SageMaker Pipelines, or a scheduled GitHub Actions workflow for small models. The logic above doesn’t change. Only the scheduler around it does.</p><h3>Step 5: multi-stage deployment, dev → staging → prod</h3><p>Three environments is the common setup, each isolated with its own workspace or account, data access and credentials:</p><ul><li><strong>Dev</strong>: data scientists experiment, with read access to production-like data and freedom to break things.</li><li><strong>Staging</strong>: an exact rehearsal of production. Integration tests run here against realistic data.</li><li><strong>Prod</strong>: only automation deploys here. No humans make manual changes.</li></ul><h3>Deploy code or deploy models?</h3><p>There are two ways to move ML through these stages:</p><ul><li><strong>Deploy models</strong>: train once in dev, then promote the <em>model artefact</em> through staging to prod.</li><li><strong>Deploy code</strong>: promote the <em>training pipeline code</em>, and let it train in each environment (so production models are trained on production data, by production jobs).</li></ul><p>Databricks recommends deploy code in most situations: unit and integration tests run in dev, and the final round of testing happens in staging. Deploy models can make sense when training is very expensive or production data can’t be used for retraining. Either way, the rule is the same: <strong>promote an artefact, never rebuild it</strong>. The image tested in staging is the image that runs in prod.</p><h3>Configuration per environment, not code per environment</h3><p>The code is identical everywhere; only the configuration changes (catalog or schema names, cluster sizes, schedules, permissions). On Databricks, Asset Bundles express this as <strong>targets</strong> in a single databricks.yml. Databricks has since renamed them <em>Declarative Automation Bundles</em>, but the databricks bundle commands and existing configuration files are unchanged.</p><pre># databricks.yml (outline)<br>bundle:<br>  name: churn-ml<br>targets:<br>  dev:<br>    mode: development<br>    workspace: { host: https://dev-workspace-url }<br>  staging:<br>    workspace: { host: https://staging-workspace-url }<br>  prod:<br>    mode: production<br>    workspace: { host: https://prod-workspace-url }</pre><p>Outside Databricks, the same idea is Helm values files (values-dev.yaml, values-prod.yaml) or Terraform workspaces.</p><h3>Promotion, approvals and rollback</h3><pre># .github/workflows/deploy.yml (outline)<br>jobs:<br>  staging:<br>    environment: staging<br>    steps:<br>      - run: databricks bundle deploy -t staging<br>      - run: databricks bundle run integration_tests -t staging<br>  prod:<br>    needs: staging<br>    environment: production       # configure required reviewers in GitHub<br>    steps:<br>      - run: databricks bundle deploy -t prod</pre><p>GitHub (and GitLab and Azure DevOps) environments can require a named reviewer before the production job runs. That’s your human approval step, recorded in the audit log.</p><p>Once a model is in production, release it gradually:</p><ul><li><strong>Shadow</strong>: the challenger receives a copy of live traffic, but its predictions aren’t used. This is a safe way to compare behaviour.</li><li><strong>Canary</strong>: 5–10% of traffic goes to the challenger. Watch the metrics, then increase.</li><li><strong>Blue/green</strong>: switch all traffic at once, and switch back instantly if something breaks.</li></ul><p><strong>Rollback</strong> should be one command: point the champion alias back to the previous model version and redeploy. If rollback needs a retrain or a rebuild, it isn&#39;t a rollback.</p><h3>Step 6: different runtimes and multiple clouds</h3><p>The same model often has to run in several places: a laptop, a CI runner, a Spark cluster for batch scoring, a Kubernetes service for real-time predictions, and sometimes more than one cloud. The trick is to separate <strong>what must be identical</strong> from <strong>what is allowed to differ</strong>.</p><h3>Keep these portable (build once, run anywhere)</h3><ul><li><strong>Container images</strong> (OCI standard): runnable on AKS, EKS, GKE, on-prem Kubernetes or a laptop.</li><li><strong>Python wheels</strong> of your library, from one private index (or one mirrored to each cloud).</li><li><strong>Model artefacts in an open format</strong>: an MLflow model, ONNX, or Safetensors for LLMs, plus the exact library version needed to load it.</li><li><strong>Pipeline definitions as code</strong>: Helm charts, Terraform, bundle files, workflow YAML.</li></ul><h3>Let these differ, through configuration only</h3><ul><li>Storage paths (s3://, abfss://, gs://). Read them from config, and use URI-aware libraries such as fsspec so code doesn&#39;t hard-code a cloud.</li><li>Identity and secrets: each cloud’s IAM. Authenticate CI to every cloud with <strong>OIDC workload identity federation</strong> rather than long-lived keys; Databricks also recommends workload identity federation for CI/CD authentication.</li><li>Compute shapes, GPU types, autoscaling limits.</li><li>Managed services (registry, serving, feature store). Wrap them behind a thin interface if you truly need to switch.</li></ul><h3>Batch, streaming and real-time are different runtimes too</h3><ul><li><strong>Batch scoring</strong> (Spark job, nightly): load the model once per executor, score in large Arrow batches, write to a table.</li><li><strong>Streaming</strong> (Structured Streaming, Kafka): the same scoring function, applied per micro-batch.</li><li><strong>Real-time</strong> (REST/gRPC service): the same model and feature library behind an API with latency SLOs, autoscaling and canaries.</li></ul><p>Because the feature code lives in one versioned library, all three compute features identically, so training/serving skew can’t creep in.</p><h3>A word of caution on multi-cloud</h3><p>Running the <em>same</em> workload actively on several clouds is expensive: duplicated pipelines, data-egress costs and more ways to fail. Most teams are better served by being <em>portable</em> (able to move) than <em>active</em> everywhere. Train where the data lives, and keep images, wheels and model formats standard so moving is a configuration change, not a rewrite.</p><h3>Where AIOps and LLMOps fit</h3><p>Two terms get mixed up with MLOps, so it’s worth being precise.</p><p><strong>AIOps</strong> was coined by Gartner in 2016 and means <em>AI for IT operations</em>: using machine learning on logs, metrics and events to detect anomalies, correlate alerts and find root causes. It’s a <em>consumer</em> of the pipeline in this post. An anomaly-detection model for your infrastructure still needs CI, CT, gates and staged deployment like any other model. AIOps tools can also feed the CT loop, for example by raising the drift or incident alert that triggers a retrain.</p><p><strong>LLMOps</strong> applies the same three loops to large language model applications, with different artefacts:</p><ul><li>What changes most often is the <em>prompt</em>, the retrieval index or a fine-tuned adapter, so these need versioning and CI just like code.</li><li>The evaluation gate uses LLM-specific checks: an exact-match or rubric score on a golden question set, faithfulness of answers to retrieved context, safety checks, plus latency and cost per request.</li><li>A fine-tuned LoRA adapter merged into the base model is registered like any other model version, and promoted through the same dev → staging → prod path.</li></ul><p>The principle carries over unchanged: <strong>nothing reaches production without passing an automated, pre-agreed gate.</strong></p><h3>Key takeaways</h3><ul><li>Run <strong>three separate loops</strong>: CI tests code, CT retrains on new data, CD promotes models. Keep them separate so every failure has a clear cause.</li><li>Put shared feature code in a <strong>versioned library</strong>, published from CI (with trusted publishing where you can), so training and serving can’t drift apart.</li><li>On <strong>PySpark</strong>, the driver and every executor need the same Python environment. Use a pinned managed runtime, a packed environment, or one container image for the whole cluster, and test with a local Spark session in CI.</li><li>Make the <strong>evaluation gate fail closed</strong>, with rules written before results exist: floor, champion, baseline, slices.</li><li><strong>Promote artefacts, never rebuild them</strong>, through dev → staging → prod, with configuration per environment, a human approval for prod, gradual rollout and one-command rollback.</li><li>Stay <strong>portable</strong> with standard images, wheels and model formats, and keep cloud-specific details in configuration.</li></ul><p><em>Next in the series: monitoring the model once it’s live: drift, alerts that actually fire, and closing the loop back to retraining.</em></p><h3>References and further learning</h3><h3>Research papers</h3><ul><li>Sculley et al., <a href="https://proceedings.neurips.cc/paper/2015/file/86df7dcfd896fcaf2674f757a2463eba-Paper.pdf">Hidden Technical Debt in Machine Learning Systems</a>, NeurIPS 2015: the paper that started the conversation about ML maintenance costs.</li><li>Breck et al., <a href="https://research.google/pubs/the-ml-test-score-a-rubric-for-ml-production-readiness-and-technical-debt-reduction/">The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction</a>, IEEE Big Data 2017: 28 concrete tests and monitoring checks.</li><li>Kreuzberger, Kühl, Hirschl, <a href="https://arxiv.org/abs/2205.02302">Machine Learning Operations (MLOps): Overview, Definition, and Architecture</a>, IEEE Access 2023: principles, components, roles and a reference architecture.</li><li>Shankar et al., <a href="https://arxiv.org/abs/2209.09125">Operationalizing Machine Learning: An Interview Study</a>, 2022: 18 ML engineers on velocity, validation and versioning.</li></ul><h3>Guides and documentation</h3><ul><li>Google Cloud, <a href="https://docs.cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning">MLOps: Continuous delivery and automation pipelines in machine learning</a>: CI, CD and CT, and MLOps levels 0–2.</li><li>Google Cloud, <a href="https://services.google.com/fh/files/misc/practitioners_guide_to_mlops_whitepaper.pdf">Practitioners guide to MLOps (whitepaper, PDF)</a>.</li><li>Databricks, <a href="https://www.databricks.com/sites/default/files/2023-07/the-big-book-of-mlops.pdf">The Big Book of MLOps (PDF)</a>, <a href="https://docs.databricks.com/aws/machine-learning/mlops/mlops-workflow">MLOps workflows</a>, <a href="https://docs.databricks.com/machine-learning/mlops/deployment-patterns/">Model deployment patterns</a>, <a href="https://docs.databricks.com/machine-learning/mlops/mlops-stacks.html">MLOps Stacks</a> and <a href="https://docs.databricks.com/aws/en/dev-tools/ci-cd/flows">CI/CD workflows with bundles</a>.</li><li>Apache Spark, <a href="https://spark.apache.org/docs/4.0.0/api/python/tutorial/python_packaging.html">Python Package Management</a>: conda-pack, venv-pack and PEX for PySpark.</li><li>Databricks blog, <a href="https://databricks.com/blog/2020/12/22/how-to-manage-python-dependencies-in-pyspark.html">How to Manage Python Dependencies in PySpark</a> and <a href="https://www.databricks.com/blog/python-dependency-management-spark-connect">Python Dependency Management in Spark Connect</a>.</li><li>Python Packaging Authority, <a href="https://packaging.python.org/en/latest/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/">Publishing package releases using GitHub Actions</a> and PyPI, <a href="https://docs.pypi.org/trusted-publishers/">Trusted Publishers</a>.</li><li>Martin Fowler / ThoughtWorks, <a href="https://martinfowler.com/articles/cd4ml.html">Continuous Delivery for Machine Learning (CD4ML)</a> †</li></ul><h3>Videos and courses</h3><ul><li>TechWorld with Nana, <a href="https://www.youtube.com/watch?v=R8_veQiYBjI">GitHub Actions Tutorial: Basic Concepts and CI/CD Pipeline with Docker</a> (32 min).</li><li>Elle O’Brien (DVC), <a href="https://dvc.org/blog/first-mlops-tutorial">MLOps Tutorial #1: Intro to continuous integration for ML</a>: automated training and evaluation reports with GitHub Actions.</li><li>Elle O’Brien at TMLS, <a href="https://classcentral.com/course/youtube-elle-o-brien-adapting-continuous-integration-and-continuous-delivery-for-ml-340500">Adapting Continuous Integration and Continuous Delivery for ML</a>.</li><li>Krish Naik, <a href="https://classcentral.com/course/youtube-mlops-github-action-with-cicd-pipeline-one-shot-tutorial-308358">MLOps GitHub Actions with CI/CD Pipeline Tutorial</a>.</li><li>Microsoft AI Show, <a href="https://learn.microsoft.com/en-us/shows/ai-show/mlops-feature-dive-cicd-with-github-actions">MLOps feature dive: CI/CD with GitHub Actions</a> (Azure ML).</li><li>Noah Gift, <a href="https://www.youtube.com/watch?v=PUXhWZQW8BI">MLOps Platforms From Zero: Databricks, MLflow/MLRun/SKLearn</a> (2.5 h; CI/CD setup and model registration on Databricks).</li><li>CNCF, <a href="https://classcentral.com/course/youtube-webinar-mlops-automation-with-git-based-ci-cd-for-ml-240347">MLOps Automation with Git-Based CI/CD for ML</a> (Kubernetes and Kubeflow).</li><li>DataTalksClub, <a href="https://github.com/DataTalksClub/mlops-zoomcamp">MLOps Zoomcamp</a>: a free course covering experiment tracking, orchestration, deployment, monitoring and best practices (CI/CD, IaC).</li></ul><h3>AIOps background</h3><ul><li>Wikipedia, <a href="https://en.wikipedia.org/wiki/AIOps">AIOps</a>: the 2016 Gartner origin of the term and how it differs from DevOps.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=384a4dd0875b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A data scientist’s walkthrough of safe softmax, online softmax, tiling and GPU memory]]></title>
            <link>https://medium.com/@harshitasharma_ai/a-data-scientists-walkthrough-of-safe-softmax-online-softmax-tiling-and-gpu-memory-0f2770339a5a?source=rss-a97a7ac74ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f2770339a5a</guid>
            <category><![CDATA[transformer-model]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Harshita Sharma]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 13:51:52 GMT</pubDate>
            <atom:updated>2026-11-28T14:03:22.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>FlashAttention from First Principles</h3><blockquote>A data scientist’s walkthrough of safe softmax, online softmax, tiling and GPU memory</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wspcPp2vi-0TErJsbW-9GQ@2x.png" /></figure><h3>Why attention is the bottleneck</h3><p>Every large language model is built on attention, and attention has an uncomfortable property: its cost grows with the <strong>square</strong> of the sequence length. Double the context from 8k to 16k tokens and the attention matrix gets four times bigger.</p><p>For years the standard fix was to approximate attention: sparse patterns, low-rank tricks, linear attention. <strong>FlashAttention</strong> took a different route. It computes <em>exactly</em> the same result as standard attention, with the same maths and no approximation, yet runs several times faster and uses far less memory. The trick isn’t fewer calculations. It’s <strong>less data movement</strong>.</p><p>This post walks through why that works, building up from first principles:</p><ol><li>what standard attention computes, and why it’s slow on a GPU;</li><li>the GPU memory hierarchy, and why “memory-bound” is the real enemy;</li><li><strong>safe softmax</strong> and <strong>online softmax</strong>, the small mathematical trick that makes everything else possible;</li><li>the tiled forward pass, the recomputing backward pass, and how FlashAttention-2, -3 and -4 pushed it further.</li></ol><p>It’s written as a companion to Umar Jamil’s excellent (and very long) video, <a href="https://www.youtube.com/watch?v=zy8ChVd_oTM"><em>Flash Attention derived and coded from first principles with Triton (Python)</em></a>. The video goes all the way to a working Triton kernel, including the backward pass. This post gives you the core ideas in one sitting, and at the end there’s a map of which video chapters to watch for each idea.</p><h3>Standard attention, and the N×N problem</h3><p>For one attention head, with a sequence of N tokens and head dimension d, we have three matrices Q (queries), K (keys) and V (values), each of shape N × d. Attention is:</p><pre>S = Q · Kᵀ / √d          shape N × N   (how much each token attends to each other token)<br>P = softmax(S)  row-wise  shape N × N   (each row sums to 1)<br>O = P · V                 shape N × d   (weighted mix of values)</pre><p>(Multi-head attention runs this independently for every head, then concatenates and projects the outputs. FlashAttention only changes the three lines above. The projections around them stay ordinary matrix multiplications.)</p><p>The inputs and output are N × d, which is small. The problem is the two <strong>N × N</strong> matrices in the middle. Some quick arithmetic for one sequence of 8,192 tokens:</p><ul><li>8,192 × 8,192 ≈ 67 million entries per head;</li><li>at 2 bytes each (fp16/bf16), that’s about <strong>134 MB per head</strong>;</li><li>with 32 heads, about <strong>4.3 GB for a single layer</strong>, and training keeps P around for the backward pass.</li></ul><p>A straightforward implementation computes these in separate GPU steps, and each step writes its full result out to GPU memory and reads it back:</p><ol><li>compute S = QKᵀ and <strong>write</strong> S to memory;</li><li><strong>read</strong> S, apply softmax, <strong>write</strong> P;</li><li><strong>read</strong> P and V, compute O, <strong>write</strong> O.</li></ol><p>The maths is cheap. Shuttling hundreds of megabytes back and forth is not. To see why that matters so much, we need to look at how GPU memory is organised.</p><h3>A GPU has two kinds of memory, and one is far faster</h3><p>A GPU isn’t one big pool of memory. For our purposes it has two levels (more levels showed in image below):</p><ul><li><strong>HBM</strong> (high-bandwidth memory): the “80 GB” on the spec sheet. Large, but relatively slow to reach, at a couple of terabytes per second on an A100.</li><li><strong>SRAM</strong> (on-chip shared memory): a small scratchpad inside each streaming multiprocessor, only a couple of hundred kilobytes each, but roughly an order of magnitude faster than HBM.</li></ul><p>Every calculation happens on data sitting in registers and SRAM. Anything else has to be fetched from HBM first, and results have to be written back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5ZYe5CdwPTm9i5hB5-lNA@2x.png" /></figure><h3>Compute-bound vs memory-bound</h3><p>Whether a GPU operation is fast depends on its <strong>arithmetic intensity</strong>: how many calculations it does for each byte it moves.</p><ul><li>A big matrix multiplication reuses every loaded number many times. It’s <strong>compute-bound</strong>: the tensor cores are the limit, which is good.</li><li>Softmax, masking, dropout and scaling touch each number once or twice. They’re <strong>memory-bound</strong>: the cores sit idle waiting for HBM.</li></ul><p>A rough way to see it: an A100 can do around 300 trillion bf16 operations per second but move only about 2 trillion bytes per second from HBM. An operation needs roughly 150 calculations per byte before compute becomes the limit. Softmax does a handful.</p><p>Standard attention is dominated by memory-bound steps on huge N × N matrices. So its runtime is set by how many bytes travel between HBM and the chip, not by how many FLOPs it does.</p><h3>The idea in one sentence</h3><p>If we could keep the N × N matrices <strong>on-chip</strong>, computing S, the softmax and the multiplication by V block by block in SRAM, and only ever write the small N × d output to HBM, the memory traffic would collapse. The FlashAttention paper calls this being <strong>IO-aware</strong>.</p><p>There’s one obstacle: softmax needs to see a <em>whole row</em> before it can normalise anything. The next section is how FlashAttention gets around that.</p><h3>The key trick: from safe softmax to online softmax</h3><h3>Step 1: safe softmax</h3><p>The textbook softmax of a row x₁ … xₙ is exp(xᵢ) divided by the sum of all exp(xⱼ). Implemented literally, it breaks. In fp16 the largest representable number is 65,504, and exp(12) is already about 162,755. A single attention score above about 11 overflows to infinity.</p><p>The fix is to subtract the row’s maximum m before exponentiating. Because softmax is unchanged when you shift every input by the same constant, the result is identical, but every exponent is now ≤ 0, so every exp(·) is between 0 and 1:</p><pre>m = max(x)<br>softmax(x)ᵢ = exp(xᵢ − m) / Σⱼ exp(xⱼ − m)</pre><p>This is <strong>safe softmax</strong>. But look at what it needs: one pass over the row to find m, a second pass to compute the denominator ℓ = Σ exp(xⱼ − m), and a third to normalise. Three passes over a row that, in attention, is N numbers long, and which we’d like never to store at all.</p><h3>Step 2: online softmax</h3><p>Online softmax (Milakov &amp; Gimelshein, 2018) computes the max and the denominator <strong>in a single pass</strong>, by correcting the running sum whenever the maximum changes.</p><p>Keep two running values: the max so far, m, and the sum so far, ℓ, computed <em>relative to that max</em>. When a new element (or a new block of elements) arrives:</p><pre>m_new = max(m_old, max of new block)<br>ℓ_new = ℓ_old · exp(m_old − m_new)  +  Σ_new exp(xⱼ − m_new)</pre><p>The factor <strong>exp(m_old − m_new)</strong> is the whole idea. Everything already added into ℓ was scaled by exp(−m_old). Multiplying by exp(m_old − m_new) re-expresses it relative to the new max, exactly as if we’d known m_new from the start. If the max didn’t change, the factor is exp(0) = 1 and nothing happens.</p><h3>A worked example</h3><p>Take one row of scores arriving in two blocks: [1, 3] then [5].</p><ol><li><strong>After block 1:</strong> m = 3, and ℓ = exp(1−3) + exp(3−3) = 0.135 + 1 = <strong>1.135</strong>.</li><li><strong>Block 2 arrives</strong> with a 5, so the max rises: m_new = 5. Rescale the old sum by exp(3−5) = 0.135, giving 1.135 × 0.135 = 0.154. Add the new term exp(5−5) = 1. So ℓ = <strong>1.154</strong>.</li><li><strong>Check against computing it all at once:</strong> exp(1−5) + exp(3−5) + exp(5−5) = 0.018 + 0.135 + 1 = <strong>1.154</strong>. ✓</li></ol><p>Same answer, but we never needed the whole row at once. That’s what lets attention be computed in tiles.</p><h3>Step 3: carry the output along too</h3><p>Attention needs more than the denominator: it needs the weighted sum of values, O = Σ softmax(x)ⱼ · Vⱼ. The same trick works. Keep a running <em>unnormalised</em> output and rescale it with the same factor:</p><pre>O_new = O_old · exp(m_old − m_new)  +  Σ_new exp(xⱼ − m_new) · Vⱼ<br>final output = O / ℓ</pre><p>Forget the rescaling and the result is simply <strong>wrong</strong>, not slower. Every earlier block would be weighted as if the old max were still the max.</p><h3>The FlashAttention forward pass, tile by tile</h3><p>With online softmax in hand, the algorithm almost writes itself. Split Q into row blocks of size B_r, and K and V into blocks of size B_c, small enough that a block of each fits in SRAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hBYAUjpOT1WBDC9k1GI8g@2x.png" /></figure><p>For each block of queries (different blocks run in parallel on different streaming multiprocessors):</p><pre>load Q_i into SRAM<br>m = −∞,  ℓ = 0,  O = 0            # running max, running sum, running output (per row)</pre><pre>for each block j of keys/values:<br>    load K_j, V_j into SRAM<br>    S   = Q_i · K_jᵀ / √d            # a small B_r × B_c tile, never written to HBM<br>    m_new = max(m, rowmax(S))<br>    P   = exp(S − m_new)              # unnormalised probabilities for this tile<br>    ℓ   = ℓ · exp(m − m_new) + rowsum(P)<br>    O   = O · exp(m − m_new) + P · V_j<br>    m   = m_new</pre><pre>O_i = O / ℓ                            # normalise once, at the end<br>write O_i to HBM                       # the only large write<br>write L_i = m + log(ℓ) to HBM          # one number per row, kept for the backward pass</pre><p>Compare this with the three-step version earlier:</p><ul><li><strong>S and P never exist in HBM.</strong> Each B_r × B_c tile is created, used and discarded inside SRAM.</li><li><strong>Extra memory is linear, not quadratic</strong>: two numbers per row (m and ℓ) instead of an N × N matrix.</li><li><strong>Everything is fused into one kernel</strong>: matmul, scaling, masking, softmax and the second matmul happen in a single pass.</li><li><strong>The FLOPs are the same</strong> (a little more, in fact). What shrinks is HBM traffic, and since attention was memory-bound, that’s what sets the speed.</li></ul><p>Causal (decoder) attention gets a bonus: tiles entirely above the diagonal would be fully masked, so they’re skipped altogether, which saves roughly half the work.</p><p>The original paper reported 2–4× wall-clock speedups over optimised baselines, up to 10–20× memory savings, and no approximation. That combination is why it was adopted so quickly.</p><p>Under the hood, the inner lines map onto <strong>block matrix multiplication</strong>: Q_i · K_jᵀ and P · V_j are ordinary small matmuls that tensor cores are very good at. Umar Jamil’s video spends a full chapter on block matrix multiplication before the forward pass, and it’s worth watching if the tiling still feels like magic.</p><h3>The backward pass: recompute instead of remember</h3><p>Training needs gradients, and the gradients of attention depend on P, the N × N probability matrix we carefully never stored. Standard implementations save P during the forward pass precisely so the backward pass can use it. That’s where much of their memory goes.</p><p>FlashAttention makes a counter-intuitive trade: <strong>recompute P during the backward pass instead of storing it.</strong> Recomputing costs extra FLOPs, but reading a stored N × N matrix back from HBM costs more time. On a memory-bound operation, doing more maths to move fewer bytes is a win.</p><p>What makes recomputation cheap is the one extra number per row saved in the forward pass: the <strong>logsumexp</strong> L = m + log(ℓ). With it, any tile of P can be rebuilt exactly, in one step, with no running max:</p><pre>S_ij = Q_i · K_jᵀ / √d<br>P_ij = exp(S_ij − L_i)          # already normalised, thanks to L</pre><p>Then the gradients follow from the chain rule, tile by tile (dO is the gradient flowing back into the output):</p><pre>dV  = Pᵀ · dO<br>dP  = dO · Vᵀ<br>D   = rowsum(dO ∘ O)            # one number per row, precomputed<br>dS  = P ∘ (dP − D)              # the softmax Jacobian, simplified<br>dQ  = dS · K / √d<br>dK  = dSᵀ · Q / √d</pre><p>(∘ is element-wise multiplication.) The line for dS is where the softmax Jacobian, which would naively be a huge matrix per row, collapses into something cheap. Deriving it is a satisfying exercise, and the video works through it step by step, from Jacobians of matrix multiplication to the Jacobian through the softmax.</p><p>Storing L instead of m and ℓ separately is one of the small refinements introduced with FlashAttention-2, and the video has a dedicated chapter on this “logsumexp trick”.</p><h3>FlashAttention-2, -3 and -4: same idea, better fit to the hardware</h3><p>The core algorithm (tiling plus online softmax plus recomputation) hasn’t changed since 2022. Each new version re-fits it to how GPUs actually execute work.</p><p><strong>FlashAttention-2 (2023).</strong> The first version reached only 25–40% of an A100’s theoretical peak, while plain matrix multiplications get much closer. FlashAttention-2 fixed this with three changes:</p><ul><li>fewer non-matmul operations (for example, normalising once at the end);</li><li>parallelising over the sequence length, not just batch and heads, so long sequences with small batches still fill the GPU;</li><li>splitting work between warps so they communicate less through shared memory.</li></ul><p>The result was about 2× faster than the original, reaching 50–73% of the A100’s peak. It also added support for head dimensions up to 256, and for multi-query and grouped-query attention.</p><p><strong>FlashAttention-3 (2024).</strong> FlashAttention-2 reached only about 35% utilisation on the newer H100. FlashAttention-3 targets Hopper GPUs. It overlaps data movement with computation using asynchronous tensor cores and the TMA unit, interleaves the matmul and softmax steps, and adds FP8 support with block quantisation. It’s 1.5–2× faster than FlashAttention-2 on H100, and its FP8 mode has 2.6× lower numerical error than a baseline FP8 attention.</p><p><strong>FlashAttention-4 (March 2026).</strong> This version redesigns the kernel for NVIDIA’s Blackwell GPUs, where tensor-core throughput has grown faster than the other units on the chip, so non-matmul work such as the exponentials becomes the new bottleneck. It co-designs the algorithm and the kernel pipeline to hide that work behind tensor-core matmuls. On a B200 in BF16 it reports up to 1.3× speedup over cuDNN 9.13 and 2.7× over Triton, reaching 1,613 TFLOPs/s (71% utilisation). It’s written in CuTe-DSL embedded in Python rather than C++ templates.</p><p>The lesson across all four: <strong>the maths stays fixed; the engineering follows the hardware.</strong> Online softmax is what made the whole family possible.</p><h3>Using it in practice, and what it doesn’t do</h3><p>You rarely call FlashAttention directly. It usually arrives through a library:</p><ul><li><strong>PyTorch</strong>: torch.nn.functional.scaled_dot_product_attention picks a fused, FlashAttention-style kernel automatically on supported NVIDIA GPUs when the inputs are fp16 or bf16 and the shapes are supported.</li><li><strong>Hugging Face Transformers</strong>: load a model with attn_implementation=&quot;flash_attention_2&quot; (requires the flash-attn package and a supported GPU).</li><li><strong>Serving engines</strong> such as vLLM, SGLang and TensorRT-LLM ship their own fused attention kernels built on the same ideas.</li><li><strong>The </strong><strong>flash-attn package itself</strong>, from the Dao-AILab repository, if you need the raw kernels.</li></ul><p>A practical note that ties back to Part 1 of this series: flash-attn contains CUDA code, so it must match your <strong>Python, PyTorch and CUDA versions</strong>. If no prebuilt wheel matches your environment, pip falls back to compiling it from source, which can take a very long time. Pin versions and use matching prebuilt wheels in your Docker images.</p><h3>What FlashAttention does not do</h3><ul><li><strong>It doesn’t reduce the FLOPs.</strong> Compute is still quadratic in sequence length. It removes the quadratic <em>memory traffic and storage</em>.</li><li><strong>It doesn’t change the results.</strong> It’s exact attention, up to normal floating-point rounding, which is why it can be swapped in without retraining.</li><li><strong>It doesn’t help much for short sequences.</strong> When N is small, the N × N matrices are small too, and other costs dominate.</li><li><strong>It isn’t a KV-cache optimisation.</strong> During generation, the memory problem is storing keys and values for every previous token. That’s handled by other ideas (PagedAttention, grouped-query attention, KV-cache quantisation), which work alongside FlashAttention-style kernels.</li></ul><h3>Key takeaways</h3><ul><li>Standard attention is slow because it’s <strong>memory-bound</strong>: it writes and reads huge N × N matrices through slow HBM, not because the maths is heavy.</li><li><strong>Safe softmax</strong> subtracts the row max to avoid overflow. <strong>Online softmax</strong> computes the max and sum in one pass by rescaling with exp(m_old − m_new) whenever the max grows.</li><li>That rescaling lets attention be computed <strong>tile by tile in fast SRAM</strong>, so S and P never touch HBM. Memory becomes linear in sequence length, and the result is exact.</li><li>The backward pass <strong>recomputes</strong> P from Q, K and one logsumexp value per row, trading cheap FLOPs for expensive memory reads.</li><li>FlashAttention-2, -3 and -4 keep the same maths and re-fit the kernel to each GPU generation (A100, H100, Blackwell).</li><li>In practice you get it through PyTorch SDPA, Transformers or your serving engine. Just make sure the CUDA wheels match your environment.</li></ul><h3>References and further learning</h3><h3>The video this post accompanies</h3><p>Umar Jamil, <a href="https://www.youtube.com/watch?v=zy8ChVd_oTM">Flash Attention derived and coded from first principles with Triton (Python)</a> (November 2024). A map of which chapters match this post:</p><ul><li><strong>Why it’s needed:</strong> Multi-Head Attention (3:10), Why Flash Attention (9:06).</li><li><strong>The softmax trick:</strong> Safe Softmax (12:50), Online Softmax (27:03), Online Softmax proof (39:44).</li><li><strong>Tiling:</strong> Block Matrix Multiplication (47:26), Flash Attention forward by hand (1:28:38) and from the paper (1:44:01).</li><li><strong>Writing the kernel:</strong> Intro to CUDA (1:50:53), Tensor Layouts (2:26:28), Intro to Triton (2:40:48), Flash Attention forward coding (2:54:26).</li><li><strong>Backward pass:</strong> LogSumExp trick in Flash Attention 2 (4:22:11), Derivatives, gradients and Jacobians (4:32:53), Jacobian through the Softmax (5:16:14), Flash Attention backwards from the paper (5:47:33) and coding (6:13:11).</li></ul><p>If you only have an hour, watch 0:00–1:00 for the motivation and the softmax derivations.</p><h3>Papers</h3><ul><li>Dao et al., <a href="https://arxiv.org/abs/2205.14135">FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness</a>, 2022.</li><li>Tri Dao, <a href="https://arxiv.org/abs/2307.08691">FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning</a>, ICLR 2024; blog: <a href="https://crfm.stanford.edu/2023/07/17/flash2.html">FlashAttention-2</a>.</li><li>Shah et al., <a href="https://arxiv.org/abs/2407.08608">FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision</a>, NeurIPS 2024; blog: <a href="https://pytorch.org/blog/flashattention-3/">PyTorch — FlashAttention-3</a>.</li><li>Zadouri et al., <a href="https://arxiv.org/abs/2603.05451">FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling</a>, 2026.</li><li>Milakov &amp; Gimelshein, <a href="https://arxiv.org/abs/1805.02867">Online normalizer calculation for softmax</a>, 2018: where online softmax comes from.</li><li>Vaswani et al., <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a>, 2017.</li></ul><h3>Code</h3><ul><li><a href="https://github.com/Dao-AILab/flash-attention">Dao-AILab/flash-attention</a>: the official implementation.</li><li>The Triton implementation from the video is in Umar Jamil’s GitHub (hkproj); the full link is in the video description.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f2770339a5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Docker Build Is Slow]]></title>
            <link>https://medium.com/@harshitasharma_ai/why-your-docker-build-is-slow-e5e6cdd72a3c?source=rss-a97a7ac74ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5e6cdd72a3c</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Harshita Sharma]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 08:00:51 GMT</pubDate>
            <atom:updated>2026-11-28T08:00:51.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Layers, Wheels and Compilation Explained.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1ATJgienVj_pGXba0wz2A@2x.png" /></figure><h3>The build that should have taken 30 seconds</h3><p>As a data scientist, my first Dockerfile looked harmless: a base image, pip install -r requirements.txt, copy the code, done. On my laptop it built in under a minute. On the CI server it took 20 minutes and then failed with gcc: command not found.</p><p>Nothing in my code had changed. What changed was <em>how</em> pip found my packages, and I had no idea, because I had never asked what docker build actually does.</p><p>This post is the explanation I wish I’d had. We’ll walk through what happens inside a Docker build, how pip resolves dependencies, what a <strong>wheel</strong> file is, and what “compilation” really means for a Python ML project. By the end you’ll know why builds get slow, why they break, and how to write Dockerfiles and CI pipelines that don’t.</p><h3>What docker build actually does</h3><p>Short version: Docker runs each line of your Dockerfile in order inside a temporary container, and saves the result of each line as a read-only filesystem snapshot called a <strong>layer</strong>. Your final image is just those layers stacked on top of each other.</p><p>Take this typical ML Dockerfile:</p><pre>FROM python:3.11-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY src/ src/<br>CMD [&quot;python&quot;, &quot;-m&quot;, &quot;src.train&quot;]</pre><p>Here’s what happens when you run docker build -t trainer:1.0 .:</p><ol><li><strong>The build context is sent.</strong> The . at the end means &quot;this folder&quot;. Docker packages it (minus anything in .dockerignore) and hands it to the build engine. Forget .dockerignore and you may be uploading gigabytes of data, notebooks and .git history on every build.</li><li><strong>FROM pulls the base image.</strong> python:3.11-slim already contains a minimal Linux and Python. Everything else is added on top.</li><li><strong>Each instruction creates a layer.</strong> COPY adds files; RUN starts a temporary container from the current layers, runs the command, and saves whatever changed on disk as a new layer.</li><li><strong>The cache decides what actually runs.</strong> Before executing a step, Docker checks whether it has already built this exact instruction, with the exact same inputs, on top of the exact same previous layers. If so, it reuses the cached layer instantly. The moment one step changes, <strong>that step and every step after it</strong> are rebuilt.</li><li><strong>The image is tagged.</strong> The stacked layers plus metadata (the CMD, environment variables, working directory) become trainer:1.0.</li></ol><h3>Why the order of lines matters so much</h3><p>Notice that we copy requirements.txt and install packages <em>before</em> copying the source code. Your code changes many times a day; your dependencies rarely do. With this order, editing train.py only invalidates the last two layers, and the build takes seconds. Copy the whole project first, and every one-line code change triggers a full reinstall of pandas, scikit-learn and friends.</p><h3>So where is the “compiling”?</h3><p>For a pure-Python project, mostly nowhere. A Docker build is really an <em>assembly</em> step: fetch a base OS, install packages, copy files. Real compilation only happens in a few situations, and the most common one is hidden inside that innocent pip install line. To understand it, we need to look at how pip picks and installs packages.</p><h3>How pip resolves your dependencies</h3><p>When pip sees requirements.txt, it has to solve a puzzle: find one version of <em>every</em> package (including the dependencies of your dependencies) that satisfies <em>all</em> the constraints at once.</p><ol><li><strong>Read your requirements</strong>, e.g. pandas&gt;=2.0, scikit-learn, mlflow.</li><li><strong>Ask the package index</strong> (PyPI, or your company’s private mirror) which versions exist, and read each candidate’s own requirements. scikit-learn needs numpy, scipy, joblib; mlflow needs a dozen more.</li><li><strong>Search for a compatible set.</strong> If two packages want incompatible versions of the same library, pip <em>backtracks</em>: it tries an older version of one package and checks again. This is why resolution can be slow, or end in a ResolutionImpossible error.</li><li><strong>Pick the right file for your machine.</strong> For each chosen version, pip prefers a pre-built <strong>wheel</strong> that matches your Python version, operating system and CPU. Only if none matches does it fall back to building from source. (More on this in a moment.)</li><li><strong>Install</strong> everything into site-packages.</li></ol><h3>The hidden problem: “latest” changes over time</h3><p>If your file says pandas&gt;=2.0, pip picks the newest pandas that fits <em>today</em>. Build the same Dockerfile next month and you may get different versions, and occasionally a different result from your model. The image is no longer reproducible.</p><p>The fix is to separate <em>what you want</em> from <em>what you install</em>:</p><pre># requirements.in: what you want (loose)<br>pandas&gt;=2.0<br>scikit-learn<br>mlflow</pre><pre># resolve once, on your machine, and commit the result<br>uv pip compile requirements.in -o requirements.txt   # or: pip-compile</pre><p>The generated requirements.txt pins <em>every</em> package, sub-dependencies included, to an exact version (optionally with hashes). The Docker build then just installs that exact list: no searching, no surprises, the same environment every time.</p><p>A useful rule of thumb: <strong>applications and Docker images lock exact versions; libraries you publish declare version ranges.</strong></p><h3>What is a wheel file, and why do we need it?</h3><p>A <strong>wheel</strong> (.whl) is a Python package that has already been built and is ready to install. Under the hood it&#39;s just a zip file containing the final files: Python modules, metadata, and for many data-science libraries, <strong>compiled binaries</strong> (.so files on Linux, .pyd on Windows).</p><p>Installing a wheel is basically unzipping it into site-packages. It takes seconds.</p><p>The alternative is a <strong>source distribution</strong> (sdist, usually a .tar.gz): the raw source code, which pip must <em>build on your machine</em> before it can install it.</p><h3>Why this matters so much for data science</h3><p>The libraries we rely on are fast because their core isn’t Python. numpy and scipy lean on C and Fortran; scikit-learn uses Cython; pandas has C extensions; PyTorch is C++ and CUDA; tokenizers is Rust. That code has to be translated into machine code for a specific operating system and CPU.</p><p>Wheels mean the package maintainers do that work <strong>once</strong>, on their build servers, for every common platform, so thousands of us don’t have to do it on every install.</p><h3>Reading a wheel’s name</h3><p>The filename tells pip exactly where a wheel can run:</p><pre>numpy-2.1.3-cp311-cp311-manylinux_2_17_x86_64.whl<br>  │     │     │     │            │<br>  │     │     │     │            └─ platform: Linux (glibc ≥ 2.17), x86-64 CPU<br>  │     │     │     └─ ABI: compiled against CPython 3.11&#39;s binary interface<br>  │     │     └─ Python tag: CPython 3.11<br>  │     └─ package version<br>  └─ package name</pre><p>A pure-Python package gets the tag py3-none-any: any Python 3, no binary interface, any platform.</p><p>pip compares these tags with your environment and picks the best match. <strong>If no wheel matches</strong>, perhaps because you’re on a brand-new Python version, an unusual CPU, or Alpine Linux (which uses musl instead of glibc), pip quietly downloads the sdist and starts compiling. That&#39;s exactly what happened to my 20-minute build.</p><h3>What actually happens during compilation</h3><p>When pip has to build a package from source, here’s the chain of events:</p><ol><li><strong>Download the sdist and read </strong><strong>pyproject.toml.</strong> This file declares which <em>build backend</em> the package needs: setuptools, Cython, scikit-build/CMake, meson-python, or maturin (for Rust).</li><li><strong>Create an isolated build environment.</strong> pip spins up a temporary virtual environment and installs those build tools, so the build doesn’t depend on whatever happens to be in your own environment.</li><li><strong>Generate C code (if the package uses Cython).</strong> Cython .pyx files, which look like Python with type hints, are translated into plain .c files. scikit-learn does a lot of this.</li><li><strong>Compile each C/C++ file.</strong> The compiler (gcc, clang, or nvcc for CUDA code):<br> — <strong>preprocesses</strong> the file, pulling in header files such as Python.h (the Python C API) and expanding macros;<br> — <strong>compiles</strong> it into an <strong>object file</strong> (.o) containing machine code for <em>your</em> CPU architecture.</li><li><strong>Link.</strong> The object files are joined together, along with any external libraries they need (the Python runtime, BLAS/LAPACK for linear algebra, CUDA libraries), into a single <strong>shared library</strong> such as _core.cpython-311-x86_64-linux-gnu.so. That file is what Python loads when you import the module.</li><li><strong>Package into a wheel and install it</strong>, exactly as if you’d downloaded a ready-made wheel.</li></ol><p>Every one of these steps can fail inside a slim container: no compiler installed (gcc: command not found), missing system headers (Python.h: No such file), or a missing system library (cannot find -lopenblas). Even when it works, compiling numpy or scipy can take many minutes.</p><h3>The other “compilation” you never notice</h3><p>Python itself also compiles: the first time a .py file is imported, it&#39;s turned into <strong>bytecode</strong> (the .pyc files in __pycache__). That isn&#39;t machine code, just a compact instruction format that the Python interpreter executes faster. It&#39;s automatic, quick, and almost never the source of build problems.</p><h3>Putting it into practice: Dockerfiles and CI for ML</h3><h3>1. Pick a base image that matches the wheels</h3><p>Use python:3.11-slim (Debian, glibc) rather than Alpine. Almost every data-science package ships manylinux wheels for glibc, so they install in seconds instead of compiling.</p><h3>2. Lock dependencies and install them before your code</h3><pre>FROM python:3.11-slim<br>WORKDIR /app<br># locked, exact versions; cached until this file changes<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY src/ src/<br>CMD [&quot;python&quot;, &quot;-m&quot;, &quot;src.train&quot;]</pre><h3>3. If something must compile, do it in a separate build stage</h3><p>A multi-stage build keeps compilers out of the image you ship:</p><pre># Stage 1: has a compiler; builds wheels once<br>FROM python:3.11-slim AS build<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends build-essential<br>COPY requirements.txt .<br>RUN pip wheel -r requirements.txt -w /wheels</pre><pre># Stage 2: no compiler; just unzips the finished wheels<br>FROM python:3.11-slim<br>COPY --from=build /wheels /wheels<br>RUN pip install --no-cache-dir /wheels/* &amp;&amp; rm -rf /wheels<br>COPY src/ /app/src/</pre><p>The final image is smaller, faster to pull, and has a smaller attack surface.</p><h3>4. Add a .dockerignore</h3><pre>.git<br>data/<br>notebooks/<br>mlruns/<br>__pycache__/</pre><h3>5. For GPU images, match CUDA too</h3><p>For PyTorch and similar libraries, the wheel must match the <strong>CUDA version</strong> as well as Python and the OS, and it usually comes from the framework’s own package index (use the install command from PyTorch’s install selector). A CUDA mismatch is the classic “works on my laptop, fails on the GPU node” bug.</p><h3>6. Test the image in CI, not just the code</h3><p>For Python, “testing the compilation” really means proving the built image works:</p><pre># .github/workflows/ci.yml (outline)<br>jobs:<br>  build-and-test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: docker build -t trainer:${{ github.sha }} .<br>      - run: docker run trainer:${{ github.sha }} python -c &quot;import src.train, sklearn, mlflow&quot;   # imports work<br>      - run: docker run trainer:${{ github.sha }} pytest tests/                                # unit tests<br>      - run: docker run trainer:${{ github.sha }} python -m src.train --sample                 # smoke-train on tiny data</pre><p>Tag images with the git commit SHA. Then every model you train can be traced back to the exact code and dependencies that produced it, which is the foundation of an automated retraining pipeline.</p><h3>Key takeaways</h3><ul><li>docker build runs your Dockerfile line by line and saves each result as a cached <strong>layer</strong>. Put things that change rarely (dependencies) before things that change often (code).</li><li>pip <strong>resolves</strong> dependencies by finding one compatible version of every package. Resolve once, commit a <strong>lock file</strong>, and make builds just install it.</li><li>A <strong>wheel</strong> is a pre-built, ready-to-unzip package. Its name tags (Python version, ABI, platform) decide whether pip can use it.</li><li>When no wheel matches, pip <strong>compiles from source</strong>: isolated build environment → Cython to C → preprocess and compile to object files → link into a .so → wheel. That&#39;s where slow and broken builds come from.</li><li>Use slim base images, multi-stage builds when compilation is unavoidable, CUDA-matched wheels for GPUs, and CI that tests the <em>image</em> (imports, unit tests, a smoke-train), not just the code.</li></ul><p>Once I understood these few mechanics, my 20-minute build went back to 40 seconds, and “works on my machine” stopped being a phrase I said out loud.</p><p><em>If this helped, follow along: next I’ll write about turning this image into an automated retraining pipeline with evaluation gates.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5e6cdd72a3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sub-word tokenizers]]></title>
            <link>https://medium.com/@harshitasharma_ai/sub-word-tokenizers-85323fb64aaf?source=rss-a97a7ac74ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/85323fb64aaf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[subword-models]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[text-analytics]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Harshita Sharma]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 12:53:22 GMT</pubDate>
            <atom:updated>2023-12-12T13:20:48.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-mRAYwmrFSV9SmaXiwyCw.jpeg" /><figcaption>Source: Dall-e</figcaption></figure><p>Why text encoding via sub-word tokenisation is important? <br>hy not creating a dictionary of each possible word (word-based tokenisation) and storing it, or mapping characters to unique ids (char-based tokenisation) sufficient?</p><p>The main advantage of a subword tokenizer is that it interpolates between word-based and character-based tokenization. Common words get a slot in the vocabulary, but the tokenizer can fall back to word pieces and individual characters for unknown words. So it helps with:<br>-&gt; Compression<br>-&gt; Handling OOV words</p><p><em>Different transformer-based models have different tokenization and encoding techniques, different ways of padding, and different special tokens.</em></p><blockquote>We will discuss the <strong>sub-word tokenization schemes</strong> used by these models.</blockquote><h3>Outline:</h3><ol><li><a href="#53d8">Byte-Pair Encoding (BPE)</a></li><li><a href="#c213">Byte-level BPE Tokenisation</a></li><li><a href="#eaa4">WordPiece</a></li><li><a href="#b4a3">Unigram</a></li><li><a href="#4361">SentencePiece tokenizer</a></li><li><a href="#d798">Open-ai tokenization &amp; encoding</a></li><li><a href="#d1af">Summary</a></li><li><a href="#5345">References</a></li></ol><p>So, let’s get started. below we will discuss the sub-word tokenizers (BPE, WordPiece, Unigram model, SentencePiece) with the idea, functioning, and list of models using these</p><h3>Byte-Pair Encoding (BPE)</h3><p><strong><em>Idea</em></strong>:</p><p>BPE is a type of sub-word tokenization that starts with a vocabulary of individual characters and iteratively merges the most frequently adjacent pair of symbols. BPE has been used in GPT-2 and RoBERTa.</p><p><strong><em>Functioning</em></strong>:</p><ul><li>It relies on pre-tokenization. So you probably need to standardize and split text on white space or any rule with regex pattern (but always segmenting on whitespace)</li><li>The first step is to use the frequency of characters and <strong>create a merge rule</strong> by iterating over the complete dataset.</li><li>For the above, split the words in chars. Initially, the tokens of the word are all of its characters plus the additional “&lt;/w&gt;”. the tokens for the word “play” are [“p”, “l”, “a”, “y”, “&lt;/w&gt;”] in order</li><li>For a sentence in training data: “We play Cricket. We also love to play Badminton”, splitting is done as: <br>{“We”:2, “play”:2, …} -&gt; {(“W”,”e”, 2), (“p”, “l”, “a”, “y”, 1), ..}<br>This way you can create a base vocabulary.</li><li>In each iteration, we count the frequency of each consecutive byte pair, find out the most frequent one, and merge the two byte-pair tokens into one token.</li><li>This way you have learned the merge symbols. This step has to be done until the base vocab size reaches the <strong><em>vocab_size</em></strong> provided as the <strong><em>hyperparameter</em></strong>. So the vocabulary contains base_vocab_size + number_of_merges</li></ul><p><strong><em>Used by models</em></strong> :</p><ul><li>GPT2, Roberta, XLM , Flare BERT</li></ul><p><strong><em>Flow:</em></strong></p><blockquote>Corpus (text to words) -&gt; Base_vocabulary (all chars in words)-&gt; freq_calculation (character frequency) -&gt; Merge Rule formation -&gt; Merge_symbols formed-&gt; Iterate last 3 steps until : base_vocab size + num of merges = “vocab_size” (hyper_param)</blockquote><h3>Byte-level BPE Tokenisation</h3><p>Idea:</p><p>Same as BPE. Only that gpt-2 introduced initialization of vocab with certain bytes</p><p><strong><em>Functioning</em></strong>:</p><ul><li>BPE (above) when using bytes to start with as its base_vocab.</li><li>256 base_tokens , 50k merges, end_of_sentence_token = 50,257 tokens in total</li></ul><p><strong><em>Used by models:</em></strong></p><ul><li>GPT-2</li></ul><h3>WordPiece:</h3><p><strong><em>Idea:</em></strong></p><p>The vocabulary is initialized with all the individual characters in the language, and then the most likely combinations of the symbols in the vocabulary are iteratively added to the vocabulary.</p><p><strong><em>Functioning:</em></strong></p><ul><li>Starts with every character present in the training data. Also includes double hashtag “##” if the word in the training data doesn’t start from that character</li><li>Training data corpus [{“this”, “is”, “the”, “word”, “corpus”}]</li></ul><pre>Corpus: [{&quot;this&quot;, &quot;is&quot;, &quot;the&quot;, &quot;word&quot;, &quot;corpus&quot;}]</pre><ul><li>Split in chars {(“t”, “##h”, “##i”, “##s”, 1), (“i”, “##s”, 1), ), (“t”, “##h”, “##e”, 1), (“w”, “##o”, “##r”, “##d”, 1), (“c”, “##o”, “##r”, “##p”, “##u”, “##s”}</li></ul><pre>Split in chars : {(&quot;t&quot;, &quot;##h&quot;, &quot;##i&quot;, &quot;##s&quot;, 1), (&quot;i&quot;, &quot;##s&quot;, 1), 1), (&quot;t&quot;, &quot;##h&quot;, &quot;##e&quot;, 1), (&quot;w&quot;, &quot;##o&quot;, &quot;##r&quot;, &quot;##d&quot;, 1), (&quot;c&quot;, &quot;##o&quot;, &quot;##r&quot;, &quot;##p&quot;, &quot;##u&quot;, &quot;##s&quot;,1)}</pre><ul><li>So, the base vocabulary will now contain unique instances of these symbols {“t”, “##h”, “##i”, “##s”, “##e”, “w”, “##o”, “##r”, “##d”, ..}</li></ul><pre>Base vocabulary: {&quot;t&quot;, &quot;##h&quot;, &quot;##i&quot;, &quot;##s&quot;, &quot;##e&quot;, &quot;w&quot;, &quot;##o&quot;, &quot;##r&quot;, &quot;##d&quot;, ..}</pre><ul><li>Now try to merge the symbol pair, and choose the one that maximizes the likelihood of training data once added to the vocabulary.</li><li>Merge <strong>“th”</strong> pair -&gt; {(“th”, “##i”, “##s”, 1), (“i”, “##s”, 1), (<strong>“th”</strong>, “##e”, 1),(“w”, “##o”, “##r”, “##d”, 1), (“c”, “##o”, “##r”, “##p”, “##u”, “##s”,1)}</li></ul><pre>Merged symbol pairs in vocabulary: {(&quot;th&quot;, &quot;##i&quot;, &quot;##s&quot;, 1), (&quot;i&quot;, &quot;##s&quot;, 1), (&quot;th&quot;, &quot;##e&quot;, 1), (&quot;w&quot;, &quot;##o&quot;, &quot;##r&quot;, &quot;##d&quot;, 1), (&quot;c&quot;, &quot;##o&quot;, &quot;##r&quot;, &quot;##p&quot;, &quot;##u&quot;, &quot;##s&quot;, 1)}</pre><ul><li>Compute pair score for <em>“this”</em> from <em>“th”</em> &amp; <em>“##is”</em>:<br><strong>“th” “##is” score</strong> = freq_of_<strong>“this”</strong> / ((freq_of_<strong>“th”</strong>) * (freq_of_<strong>“##is”</strong>))</li><li>Compute all pair scores and now identify the merged pair with the highest score and it to the vocabulary. So, vocabulary initially having characters has started getting sub-words and the size of vocabulary is iteratively increasing.</li><li>Apply the same fusion to the remaining split corpus until the desired vocab_size is reached.</li></ul><p><strong><em>Used by models:</em></strong></p><ul><li>BERT, DistilBert, Electra</li></ul><blockquote><strong>Scenariao</strong>: You need to tackle a search query containing Japanese and Korean keywords also apart from English. Traditionally, Japanese and Chinese for example doesn’t include white spaces between characters but Korean has some. Search keywords typed into search engines in Japanes or Koean are usually but not always separated by spaces whereas ASCII keywords are always (English words, abbreviations, numbers)</blockquote><blockquote>To be able to learn where to put white spaces in case of these languages, Google used double underscore “__” as space markers [<a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/37842.pdf">Ref</a>erencce of paper] after decoding via WordPiece on the sentences (which happens by default in BPE, Wordpiece, unigram etc). <br>To train Neural Machine Translation systems for non-segmented languages such as Chinese, Korean and Japanese, we need to run word segmenters independently. The language dependent processing makes it hard to train multilingual NMT models. <br>We will see later how language agnostic SentencePiece solves this.</blockquote><h3>Unigram:</h3><p><strong><em>Idea:</em></strong></p><p>Remove tokens from the initial big vocabulary which impacts the least the loss.</p><p>It assumes that the occurrence of each word is independent of its previous words and doesn’t consider any order. Always generates the most probable token, so not used for a generative model</p><p>It is good for tokenization as it helps in getting the likelihood of different phrases.</p><p><strong><em>Functioning:</em></strong></p><ul><li>Builds initial vocab based on char frequency or byte pair (can use BPE)</li><li>It also keeps the base characters</li><li>How to tokenize a word after building the vocabulary? <br>Find all possible segmented subwords from the vocabulary for the text-&gt; calculate the probability (occurrence of that segment/ occurrence of all segments) and also calculate the loss on the training corpus</li><li>Remove p segments from vocabulary such that loss increases the least</li><li>Again repeat the above steps until the desired vocabulary size is reached</li></ul><p><strong><em>Used by:</em></strong></p><ul><li>Often used along with BPE or Sentencepiece</li></ul><h3>SentencePiece tokenizer:</h3><p><strong><em>Idea:</em></strong></p><p>As discussed in a scenario in WordPiece section above, not all languages uses spaces for text segmentation into words. For eg: Japanese, Chinese. To solve this main problem, sentencePiece takes in raw input (including characters, spaces if any). It then uses the BPE or unigram algorithm to construct the appropriate vocabulary.</p><p><strong><em>Functioning:</em></strong></p><p>It has four components:</p><ul><li>normalizer -&gt; text normalization is done</li><li>trainer -&gt; It uses BPE to train tokenizer</li><li>encoder -&gt; text encoding to pieces</li><li>decoder -&gt; decodes pieces to original</li></ul><p>Hence, decode(encode(normalize(text))) -&gt; normalize(text)</p><blockquote><em>Encoding and decoding manage the vocabulary to id mapping and can directly convert the text into an id sequence and vice versa.</em></blockquote><p>SentencePiece first escapes the whitespace with a meta symbol _ (U+2581), and tokenizes the input into an arbitrary subword sequence, <br>for example:<br> • Raw text: Hello_world. <br>• Tokenized: [Hello] [_wor] [ld] [.]</p><p>As the whitespace is preserved in the tokenized text, we can detokenize the tokens without any ambiguities with the following Python code.</p><pre>detok = &#39;&#39;.join(tokens).replace(&#39;_&#39;, &#39; &#39;)</pre><p><strong><em>Used by models :</em></strong></p><ul><li>XLM, ALBERT, TINYBERT</li></ul><h3>Open-ai tokenization &amp; encoding</h3><p>Under the hood, it is subword tokenization. But a special kind. You’ll see the token_ids for the same sub-word are different for gpt3.5 &amp; gpt-4 (<strong><em>cl100k_base)</em></strong> <br>Different encodings used in openai are: <strong><em>cl100k_base, p50k_base, gpt2</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*06VJhLwkfkfepP4LKjfKjA.png" /></figure><p>The vocab size for gpt-2 = 50,257 whereas for gpt-3.5 &amp; 4 it is 100277</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mk7H4PISQJEiBr3CQ2Dscg.png" /></figure><p>Ref: <a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a> for highlighting tokens and their ids generated through pretrained tokenizer from openai.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9XOu00706KEv2TsYUixrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTtQt642eX9Vj7Ffx-SQrw.png" /><figcaption><a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a></figcaption></figure><p>For programmatically testing token size for open-ai, check out our <a href="https://github.com/openai/tiktoken">tiktoken</a> package for Python. For JavaScript, the community-supported <a href="https://www.npmjs.com/package/tiktoken">@dbdq/tiktoken</a> package works with most GPT models.</p><h3><strong>Summary:</strong></h3><ul><li>Knowing the <strong>fundamentals of subword tokenizers</strong> will help you quickly grasp the most recent advancements in Language processing areas.</li><li>As we saw, the difference between BPE and WordPiece lies in the way the symbol pairs are chosen for adding to the vocabulary.</li><li>Byte-Pair Encoding [BPE], WordPiece, and Unigram do some pre-processing and pre-tokenization on text.</li><li>SentencePiece can train subword models directly from raw sentences, which allows us to make a purely end-to-end and language-independent system.</li><li>Tokenization and word segmentation are becoming increasingly language-independent as neural models are used more frequently.</li></ul><h3>References:</h3><p><a href="https://arxiv.org/pdf/1808.06226.pdf">https://arxiv.org/pdf/1808.06226.pdf</a><br><a href="https://huggingface.co/docs/transformers/tokenizer_summary">https://huggingface.co/docs/transformers/tokenizer_summary</a><br><a href="https://blog.devgenius.io/counting-tokens-for-openai-gpt-3-api-59c8e0812eeb">https://blog.devgenius.io/counting-tokens-for-openai-gpt-3-api-59c8e0812eeb</a><br><a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85323fb64aaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving topic models and understanding evaluation metrics]]></title>
            <link>https://medium.com/@harshitasharma_ai/improving-topic-models-and-understanding-evaluation-metrics-af0509635dc5?source=rss-a97a7ac74ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/af0509635dc5</guid>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Harshita Sharma]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 18:31:13 GMT</pubDate>
            <atom:updated>2023-02-12T18:31:13.662Z</atom:updated>
            <content:encoded><![CDATA[<p><em>About Topics Modelling</em>: Topics are the few keywords that best represent the data cluster and the keywords belonging to one group. So, each topic should talk about a particular topic or a story. The topic models can be used for feature selection also.</p><p>We will first see the idea behind LDA which is widely used for topic modeling, the steps required for LDA, and then focus on only improving and evaluating the model.</p><p>Many times simply using techniques like LDA and generating topics don’t work well, maybe because of the following reasons:</p><ol><li>The number of topics is not proper.</li><li>Topics are not coherent.</li><li>Multiple Topics have the same keywords and there is not much distinction among the different topics.</li><li>How to pre-process data — when to lemmatize and when to stem and when none is good?</li><li>Non-PMI metrics</li></ol><h4>Understanding LDA (Latent Dirichlet Allocation)</h4><blockquote>Authors describe LDA as a <strong>generative probablistic model</strong> for collections of discrete data such as text corpora.</blockquote><p>Examples of other generative models are:</p><ul><li>Gaussian Mixture Model (GMM)</li><li>Hidden Markov Model (HMM)</li><li>Linear Discriminant Analysis (LDA)</li><li>Generative Adversarial Networks (GANs)</li><li>Autoencoders</li><li>Boltzmann Machines</li></ul><p>LDA is a three-level hierarchical Bayesian model:</p><p>Step 1: Each item in corpora is modeled as a finite mixture over an underlying set of topics</p><p>Step2: Each topic is modeled as an infinite mixture over an underlying set of topic probabilities</p><p>Step 3: Topic Probabilities are calculated (Representation of document)</p><p>The LDA model has two parameters that control the distributions:</p><ol><li><strong>Alpha (ɑ)</strong> <strong>a-priori belief on document-topic distribution. </strong>It<strong> </strong>controls per-document topic distribution. So, the <em>alpha </em>parameter controls the mixture of topics for any given document. Turn it down, and the documents will likely have less of a mixture of topics. Turn it up, and the documents will likely have more of a mixture of topics.</li><li><strong>Beta (ꞵ)</strong> <strong>a-priori belief on topic-word distribution. </strong>It controls per topic word distribution: Prob dis over words for the first topic, second topic,… beta dist for each k topic. The <em>beta</em> hyperparameter controls the distribution of words per topic. Turn it down, and the topics will likely have fewer words. Turn it up, and the topics will likely have more words. <br>Referred to as eta in gensimlibrary. Its value is “symmetric”: (default). It uses a fixed symmetric prior of 1.0 / num_topics. Another option is “auto” where it learns an asymmetric prior from the corpus.</li></ol><p>In gensim, both <strong>ɑ </strong>and <strong>ꞵ </strong>default to a symmetric, 1 / <strong>num_topics </strong>prior. Look at tuning here in the <a href="https://github.com/harshita23sharma/MachineLearningAlgos/blob/main/Topic_modeling_on_airbnb_review_data.ipynb">colab_notebook</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QxHSjwQ-UICyW5RskBuKrQ.png" /></figure><p>To summarize:</p><ul><li>M: are the total documents in the corpus</li><li>N: is the number of words in the document</li><li>w: is the Word in a document</li><li>z: is the latent topic assigned to a word</li><li>theta (𝛳): is the topic distribution. Each 𝛳_d is like a random variable that we eventually want to learn, drawn from Dirichlet distribution. Any random variable vector drawn from Dirichlet distribution must have its element sum to one i.e. behaves as a pmf.</li></ul><blockquote>LDA makes assumption that each word in each doc belongs to a particular topic<br>LDA model’s parameters: Alpha (ɑ) and Beta (ꞵ)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*VK5R_2YlRx3NbRIMbUxJ8Q.png" /></figure><p><em>Approach Gibbs sampling</em>: What we want to do in inference is to figure out the latent variables that describe what’s going on in the topic model. Assuming we already have some collection of latent variables that completely describes how we go from topics to allocations to assignments to generate our complete doc collection.</p><p><em>First step</em>: Random initialization of topic for each word initially.</p><p><em>Next step</em>: Change the topic assignment of a single word and pretend we don&#39;t know the topic assignment of the single word but we know all the others. So given everything else we know, what&#39;s the topic assignment of the word? Then we get info from all the other words from all the docs and we do it for all the words...</p><p><em>Mathematically</em>: We are finding conditional probability distribution of a single word topic assignment conditioned on the rest of the model, all the other words’ topic assignments, and all the other latent variables in the model and we want to only care about this latent variable. Another latent var theta: dist over topics in doc, beta: distribution over words in a topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHTXQvlCxmjl9p3Dt4Gc_Q.png" /></figure><p><em>How does Gibbs sampling work?</em></p><p>There are two main parts of conditional probability:<br>Part 1: How much each document like a topic<br>Part2: How much each topic likes a word</p><p>Vector of conditional prob of that word taking on each of the k topics. Each vector will encode how likely the word is to go of the K different topics and then we will choose which topic it gets from that cond prob dist. Each element in the k dimension vector corresponds to how much this topic is likely to be the new topic of this word<br>n_d,k : How many times this doc d already used this topic k.<br>v_w,k: How many times has this topic k already used the word w?<br>Next, we’re going to add in Dirichlet param (prior) for the Dirichlet distribution that generates the multinomial distribution over topics for each document and this acts as a smoothing term (Naive Bayes) Even if the doc has not used a topic before, so n_d,k = 0 so alpha_k is added so that it won’t go zero. The first part n_d,k + alpha, and normalized encode how much this document likes a particular topic. <br>The second part encodes how much a topic likes a particular word</p><p>Go through all of the documents, through every word, decrement the variables associated with that topic assignment, sample a new topic assignment, and then increment the counts again.<br>Ref: <a href="https://www.youtube.com/watch?v=u7l5hhmdc0M">https://www.youtube.com/watch?v=u7l5hhmdc0M</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roxYKUnBrL4CKJ-zOXSXTw.png" /></figure><p><em>Generative Model</em>: Each topic is a multinomial distribution of words, which comes from the Dirichlet distribution. Also, Dirichlet distribution over topics a single document uses.</p><p>For each topic k in {1,…,K}, draw a multinomial distribution (over words for each topic) beta_k from Dirichlet distribution parameterized by lambda.<br>For each document d in {1,…,M}, draw a multinomial distribution (over topics for each document) theta_d from Dirichlet distribution parameterized by alpha.<br>Topic assignment z: Drawn from theta_d distribution over topics<br>Actual word w_n: Drawn from beta_d distribution corresponding to the topic assignment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*GTjrK28TdeBMWtVilFIbPQ.png" /></figure><h3>Understanding Evaluation Techniques</h3><p>We will focus on improving topic quality. Here are the different ways we can try to improve topic quality for example.</p><h4>Topic Coherence</h4><p>First is <strong>optimizing </strong>choice for<strong> a number of topics </strong>through <strong>coherence measure<br></strong>LDA requires specifying the number of topics. We can tune this through the optimization of measures such as predictive likelihood, perplexity, and coherence. Literature has indicated that maximizing a coherence measure, named Cv, leads to better human interpretability. We can test out several topics and asses the Cv measure:</p><pre>dictionary = gensim.corpora.Dictionary(corpus)<br>doc_term_matrix = [dictionary.doc2bow(doc) for doc in corpus]<br><br>coherence = []<br>for k in range(4,25):<br>    print(&#39;Round: &#39;+str(k))<br>    Lda = gensim.models.ldamodel.LdaModel<br>    ldamodel = Lda(doc_term_matrix, num_topics=k, id2word = dictionary, passes=40,\<br>                   iterations=200, chunksize = 10000, eval_every = None)<br>    <br>    cm = gensim.models.coherencemodel.CoherenceModel(model=ldamodel, texts=corpus,\<br>                                                     dictionary=dictionary, coherence=&#39;c_v&#39;)<br>    coherence.append((k,cm.get_coherence()))<br><br>x_val = [x[0] for x in coherence]<br>y_val = [x[1] for x in coherence]<br>plt.plot(x_val,y_val)<br>plt.scatter(x_val,y_val)<br>plt.title(&#39;Number of Topics vs. Coherence&#39;)<br>plt.xlabel(&#39;Number of Topics&#39;)<br>plt.ylabel(&#39;Coherence&#39;)<br>plt.xticks(x_val)<br>plt.show()</pre><p><strong>Plotting this shows:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*YxXpcD41TtO6Kdn8N5eozQ.png" /></figure><p>There is a peak at 13th topics. It is not always best where the highest Cv is, so we can try multiple to find the best result. We tried 13 here, and 11 yielded clearer results. Adding topics can help reveal further sub-topics. Nonetheless, if the same words start to appear across multiple topics, the number of topics is too high.</p><p>To indicate the quality of the topics obtained by the model, topic coherence is mainly used. NPMI topic coherence is the most used one.</p><p>NPMI topic coherence (Normalized PointWise Mutual Information): It is computed on the co-occurrences of the words in the original or an external corpus. The intuition is that if two words co-occur very often, they are more likely related to each other.</p><p>Coherence score ranges between [-1,1] -&gt; higher the better (depends on the dataset)</p><p>Gensim&#39;s computation of coherence is already there for use. <a href="https://radimrehurek.com/gensim/models/ldamodel.html">Ref</a></p><h4>Diversity of the Topics</h4><p>Ideally, we expect topics that represent separate concepts or themes. To achieve this we can use metric IRBO, which is based on the counting of common words</p><p>Inverted Rank Biased Overlap: Topics sharing the exact words at the highest ranks are penalized more than the topics with common words at different rankings. It is the inverse of RBO, where RBO is the proportion of overlapped items among all the items as we progress the ranking depth. It keeps averaging the overlaps as we go down the ranked list. Refer blog on rbo <a href="https://changyaochen.github.io/Comparing-two-ranked-lists/">here</a></p><h4>Relevancy</h4><p><strong>Tune the relevancy score to prioritize terms more exclusive to a topic. </strong>Sometimes, words that are ranked as top words for a given topic may be ranked high because they are globally frequent across text in a corpus. The relevancy score helps to prioritize terms that belong more exclusively to a given topic. This can increase interpretability even more. The relevance of term w to topic k is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*xjg5ZZ9RKzSvaMZO00C9FQ.png" /></figure><p>where ϕkw is the probability of term w in topic k and ϕkw/pkw is lift in term’s probability within a topic to its marginal probability across the corpus (this helps discard globally frequent terms). <strong>A lower lambda value gives more importance to the second term, which gives more importance to topic exclusivity</strong>. We can use Python’s pyLDAvis for this.<br>The paper behind this tool: <a href="https://nlp.stanford.edu/events/illvi2014/papers/sievert-illvi2014.pdf">https://nlp.stanford.edu/events/illvi2014/papers/sievert-illvi2014.pdf</a></p><p>There are other topic modeling techniques out there like contextual models like BERT, ELMo, and GPT, and also a combined combination of both <a href="https://github.com/MilaNLProc/contextualized-topic-models/">CombinedTM</a>.</p><p>While contextualized models can provide high accuracy and are better suited for tasks that require a deeper understanding of the context and meaning of words in a sentence, they can also be computationally expensive and require large amounts of labeled data for pre-training.</p><p>LDA is an unsupervised technique and a good choice when the goal is to understand the general topics present in a text corpus. Some common use cases are EDA, data reduction, clustering, and information retrieval.</p><p>References:</p><ol><li>pyLDAvis :<a href="https://nicharuc.github.io/topic_modeling/#topic=0&amp;lambda=1&amp;term=">https://nicharuc.github.io/topic_modeling/#topic=0&amp;lambda=1&amp;term=</a></li><li>Topic fine-tuning: <a href="https://towardsdatascience.com/6-tips-to-optimize-an-nlp-topic-model-for-interpretability-20742f3047e2">https://towardsdatascience.com/6-tips-to-optimize-an-nlp-topic-model-for-interpretability-20742f3047e2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af0509635dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>