<?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 Iman Sharei on Medium]]></title>
        <description><![CDATA[Stories by Iman Sharei on Medium]]></description>
        <link>https://medium.com/@imansharei24?source=rss-790353a665d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IR3gf5QnbfIuBJOWs8CNJA.jpeg</url>
            <title>Stories by Iman Sharei on Medium</title>
            <link>https://medium.com/@imansharei24?source=rss-790353a665d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:07:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imansharei24/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[The Django Audit Log I Actually Keep Using: One Function, No Magic]]></title>
            <link>https://medium.com/@imansharei24/the-django-audit-log-i-actually-keep-using-one-function-no-magic-315152b65865?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/315152b65865</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 12:50:01 GMT</pubDate>
            <atom:updated>2026-11-15T12:50:01.202Z</atom:updated>
            <content:encoded><![CDATA[<p>django-actlog records only the events you name, shows them in a read-only admin, and stays out of your way. Here is why I recommend it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSrVVo93JmLPwYVfNN_XkA.png" /></figure><p>Every Django project I ship reaches the same moment. Something odd happens in production, someone asks “who did that and when?”, and I realize I have no clean answer. Application logs scroll away. Model history tools record every field change, which is a lot of noise when all I wanted was “this user upgraded their plan” or “this webhook got rejected.”</p><p>For that job I now use django-actlog in my projects. It is an open-source library written by Abtin Dahaei (AbtinDahaei on GitHub), and you can find it here: <a href="https://github.com/AbtinDahaei/django-actlog">https://github.com/AbtinDahaei/django-actlog</a></p><p>I did not build it. I just think it deserves more eyes, so this is my write-up of what it does, how to set it up, and where it falls short.</p><h3>The problem: activity logs that mean something</h3><p>There are two popular audit tools in the Django world. django-auditlog tracks model changes automatically. django-easy-audit hooks into CRUD and auth events automatically. Both are useful, and both follow the same idea: capture everything, filter later.</p><p>django-actlog takes the opposite route. It writes a log row only when your code explicitly calls log_event() with an action string you define. No signals firing behind your back, no middleware, no surprise tables full of rows you will never read.</p><p>That sounds almost too simple. In practice it is exactly what an MVP needs: a short, readable trail of business events like logins, OTP sends, payments, exports and failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2qekWiW2yIxMZbqzP9Qeg.png" /></figure><h3>What is inside</h3><p>The package is small enough to read in ten minutes, and I recommend you do. Here is what I found in version 1.0.0, the current release on PyPI:</p><ul><li><strong>One public function.</strong> log_event(action, user=None, metadata=None, level=None) creates the row synchronously and returns the ActLog instance.</li><li><strong>One model.</strong> ActLog has a nullable user foreign key, an action string, a level, a JSON metadata field and a created_at timestamp.</li><li><strong>Severity levels</strong> that mirror Python logging: DEBUG, INFO, WARNING, ERROR and CRITICAL, exposed as Level. The default is INFO.</li><li><strong>Sensible indexes</strong> on action, level, created_at, plus composite indexes for action by time and user by time.</li><li><strong>A read-only Django admin.</strong> It registers itself, blocks add and delete, shows colored level badges (light and dark themes), filters by level and searches by action and user email.</li><li><strong>A JSON viewer for metadata,</strong> powered by django-json-widget, which is installed and added to INSTALLED_APPS for you.</li><li><strong>User deletion is safe.</strong> The user foreign key uses SET_NULL, so deleting an account keeps its history rows.</li></ul><p>Supported versions per the package metadata: Python 3.10 and up, Django 4.2 through 6.0. It is MIT licensed.</p><h3>Install and setup</h3><p>Installation is one pip command:</p><pre>pip install django-actlog</pre><p>Then add the app to your settings:</p><pre>INSTALLED_APPS = [<br>    # ...<br>    &quot;actlog&quot;,<br>]</pre><p>And run its migrations:</p><pre>python manage.py migrate actlog</pre><p>That is the whole setup. You do not need to add django_json_widget to INSTALLED_APPS yourself; the app config appends it when actlog loads.</p><h3>Using it</h3><p>The README suggests keeping your action names in your own project, not in the library. I like this rule. Your vocabulary of events becomes a small file you can grep:</p><pre># myapp/audit_constants.py<br>LOGIN_SUCCESS = &quot;LOGIN_SUCCESS&quot;<br>LOGIN_FAILED = &quot;LOGIN_FAILED&quot;<br>OTP_SENT = &quot;OTP_SENT&quot;<br>PLAN_UPGRADED = &quot;PLAN_UPGRADED&quot;</pre><p>Then call log_event wherever the event really happens, usually in a service function:</p><pre>from actlog import log_event, Level<br>from myapp.audit_constants import LOGIN_SUCCESS, LOGIN_FAILED<br><br><br>def on_login_success(user, request):<br>    log_event(<br>        LOGIN_SUCCESS,<br>        user=user,<br>        metadata={<br>            &quot;method&quot;: &quot;otp&quot;,<br>            &quot;ip&quot;: request.META.get(&quot;REMOTE_ADDR&quot;),<br>            &quot;user_agent&quot;: request.META.get(&quot;HTTP_USER_AGENT&quot;, &quot;&quot;),<br>        },<br>    )<br><br><br>def on_login_failed(request, username):<br>    log_event(<br>        LOGIN_FAILED,<br>        level=Level.WARNING,<br>        metadata={&quot;username&quot;: username, &quot;ip&quot;: request.META.get(&quot;REMOTE_ADDR&quot;)},<br>    )</pre><p>Notice that IP and user agent go into metadata. Early versions captured request context automatically, but the changelog shows those fields were removed in 0.3.0. Anything contextual now lives in metadata, which keeps the model tiny and puts you in charge of what gets stored. That matters if you care about privacy rules, because nothing personal lands in the table unless you put it there.</p><p>Since the function returns the created row, you can also use it in tests or chain it with other logic:</p><pre>event = log_event(&quot;DATA_EXPORT_FAILED&quot;, user=user, level=Level.CRITICAL,<br>                  metadata={&quot;job_id&quot;: &quot;exp_2291&quot;, &quot;error&quot;: &quot;disk full&quot;})<br>print(event)<br># level=CRITICAL action=DATA_EXPORT_FAILED user=1 at=2026-11-01T14:54:14.277069+00:00</pre><p>That output is real. I set up a fresh Django 6.0 project, installed the library, logged a handful of events and opened the admin. Here is the changelist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agD6KtVrcGoNDYCNo7frYA.png" /></figure><p>And the detail page, where metadata opens in a collapsible JSON viewer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro3gN5zDM5eTkmCRWlcWUQ.png" /></figure><p>Because ActLog is a normal Django model, querying it is just the ORM. The related name on the user defaults to act_logs:</p><pre>from actlog import ActLog, Level<br><br>recent_problems = ActLog.objects.filter(<br>    level__in=[Level.ERROR, Level.CRITICAL]<br>).order_by(&quot;-created_at&quot;)[:20]<br><br>user_history = request.user.act_logs.all()[:50]</pre><h3>Configuration options</h3><p>There are four settings, all optional:</p><ul><li><strong>ACTLOG_MODEL</strong> (default “actlog.ActLog”): dotted path to the log model. The README marks it as advanced.</li><li><strong>ACTLOG_USER_RELATED_NAME</strong> (default “act_logs”): the related name on the user foreign key.</li><li><strong>ACTLOG_ACTION_MAX_LENGTH</strong> (default 64): max length of action strings.</li><li><strong>ACTLOG_USER_SEARCH_FIELDS</strong> (default (“user__email”,)): admin search lookups for the user.</li></ul><p>If your custom user model has no email field, override the last one, for example:</p><pre>ACTLOG_USER_SEARCH_FIELDS = (&quot;user__username&quot;, &quot;user__phone_number&quot;)</pre><h3>Where it fits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djcm_eVEvFpOYNhbo6iUZQ.png" /></figure><p>Here are the places I find it most useful:</p><ul><li><strong>Auth trails.</strong> Logins, failed attempts, OTP sends and password resets, each with whatever context you choose.</li><li><strong>Money events.</strong> Plan upgrades, refunds, rejected webhooks. A support person can open the admin and see the story without touching the database.</li><li><strong>Background job failures.</strong> Log an ERROR or CRITICAL row from a task, with the job id in metadata, and you get a quick dashboard for free.</li><li><strong>Admin actions.</strong> Call it from a custom admin action to record who ran a bulk operation.</li></ul><p>The best part is that your log becomes a list of decisions you made on purpose, not a dump of everything the framework could see.</p><h3>Honest limitations</h3><p>I like this library, but it is deliberately minimal, and you should know what it does not do:</p><ul><li><strong>Writes are synchronous.</strong> Each call is one INSERT in the request path. Async and Celery support existed in 0.1.0 and was removed in 0.2.0. For very hot paths, think about where you call it.</li><li><strong>It is not a model history tool.</strong> No diffs, no before and after values. If you need that, use django-auditlog next to it.</li><li><strong>No retention or cleanup.</strong> There is no management command to prune old rows, so on a busy app you will want your own scheduled delete.</li><li><strong>No request auto-capture.</strong> You pass IP, user agent and the rest yourself.</li><li><strong>Changing the model settings needs care.</strong> ACTLOG_ACTION_MAX_LENGTH and ACTLOG_USER_RELATED_NAME feed the model definition, while the shipped migrations use the defaults. Changing them after install may show up as pending migrations for the actlog app, so I would pick values early and leave them.</li><li><strong>The detail page still shows a Save button</strong> in my test, even though every field is read-only or disabled. Nothing editable goes through, but it can confuse non-technical staff.</li><li><strong>It is young.</strong> Version 1.0.0 landed in July 2026 after a quick series of 0.x releases, so the API has already changed a few times.</li></ul><h3>Tests and code quality</h3><p>I ran the test suite locally with Django 6.0 and Python 3.12. All 15 tests passed and ruff reported no issues, which matches the CI matrix the author set up across Django 4.2, 5.0 and 6.0. The tests cover the logging service and the admin, including the read-only behavior and the level badges.</p><h3>Give it a star</h3><p>Small, focused libraries like this live or die by visibility. If you work with Django and have ever wanted a clean answer to “what happened here?”, try it in a side project this week. If it helps you the way it helps me, go star the repo and say thanks to the author:</p><p><a href="https://github.com/AbtinDahaei/django-actlog">https://github.com/AbtinDahaei/django-actlog</a></p><p>Issues and pull requests are the best way to push it forward. A retention command and an optional async path would be my first wishes.</p><p><em>Iman Sharei is an AI Engineer who builds products with Python and Django. He is not affiliated with django-actlog and uses it in his own projects.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=315152b65865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Guessing What Changed in Your Django API: I Built a Swagger UI That Shows the Diff]]></title>
            <link>https://medium.com/@imansharei24/stop-guessing-what-changed-in-your-django-api-i-built-a-swagger-ui-that-shows-the-diff-274f660642e4?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/274f660642e4</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 12:48:18 GMT</pubDate>
            <atom:updated>2026-11-15T12:48:18.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>swagger-diff-ui compares your live OpenAPI schema with any git branch or commit and marks every endpoint as NEW, UPDATE, or DELETE, inside the same /api/docs/ page you already use</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFK0eKChY4GE31D54jz7XQ.png" /></figure><p>If you work on a Django REST Framework project with drf-spectacular, you probably open Swagger UI many times a day. It tells you what your API looks like right now. It does not tell you what changed.</p><p>That second question comes up all the time. A reviewer wants to know which endpoints a pull request touches. A frontend developer asks whether a field became required. Someone removed an endpoint, and nobody noticed until a client broke. Reading a raw JSON schema diff to answer these questions is painful, and reading serializer code is worse.</p><p>So I built <strong>swagger-diff-ui</strong>, a small open-source Django app that answers it visually. You pick a git branch or commit as the baseline, click Compare, and Swagger UI shows you exactly what is different.</p><h3>What it does</h3><p>swagger-diff-ui is a drop-in replacement for the Swagger UI page you get from drf-spectacular. It adds a dark drawer at the top of /api/docs/ with three things: a baseline branch selector, a commit selector, and a Compare button.</p><p>When you hit Compare, it builds the OpenAPI schema of your project as it was at that commit, generates the current schema, and diffs the two. Then it paints the result straight onto the Swagger UI you already know.</p><p>Here is a real screenshot. I made a tiny petstore API with two commits. In the second commit I added a required status field to Pet, made the tag field required, added a PATCH endpoint and an orders endpoint, and dropped DELETE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCqy_4ECYUS1plHA-_VWeQ.png" /></figure><p>Every changed operation gets a badge on the left. The drawer shows a summary (NEW +2, UPDATE ~3, DELETE -1). Removed operations cannot be shown as normal Swagger rows, because they no longer exist in the current schema, so they appear in a separate red box at the bottom.</p><p>No Node. No separate single-page app. It is the same page with a small layer on top.</p><h3>Key features</h3><p>These are the features I actually shipped, as listed in the README and implemented in the code:</p><ul><li><strong>Branch and commit selectors.</strong> The baseline comes from your real git history. The drawer lists local and remote branches and the recent commits of the selected branch.</li><li><strong>NEW, UPDATE and DELETE tags</strong> on every changed operation.</li><li><strong>Changed only filter.</strong> Hide every unchanged API with one toggle, and bring them back with Show all APIs.</li><li><strong>Field-level UPDATE details.</strong> Open an UPDATE row and you get a “What changed vs baseline” list covering parameters, request body, responses, and schema properties. Type changes, optional to required changes, added and removed properties are all called out.</li><li><strong>Colored Example Value dots.</strong> Changed lines in the Example Value are highlighted, so you can spot the new field without reading the list.</li><li><strong>Nested $ref awareness.</strong> If a component schema changes, every operation that references it, even through other components, is marked as UPDATE.</li><li><strong>Caching.</strong> Each baseline schema is cached by commit SHA under .schema-cache/, so the second compare against the same commit is fast.</li><li><strong>Copy buttons</strong> next to each endpoint path.</li><li><strong>A JSON API</strong> for the diff itself, so the data is not locked inside the UI.</li><li><strong>A CI command.</strong> manage.py swagger_diff prints a summary or a full JSON report, flags likely breaking changes, and can exit with a non-zero code so a pipeline fails.</li><li><strong>Flexible baselines.</strong> Branch names, SHAs, and relative refs like HEAD~1, main~3 or HEAD^ all work.</li></ul><p>Here is what an expanded UPDATE row looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHGMmPyUR7Bq5ko8Rj9RCw.png" /></figure><h3>How it works under the hood</h3><p>The interesting part is how the baseline schema gets built. You cannot just import old code into a running process, so swagger-diff-ui does something simpler and more honest. It creates a temporary git worktree at the selected commit, runs manage.py spectacular there to export that version’s OpenAPI JSON, and removes the worktree afterwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDwa4KIxZPsHIbPLvlQ4SQ.png" /></figure><p>The current schema comes from drf-spectacular’s SchemaGenerator in the running process. A pure Python function then compares the two documents: operations keyed by method and path, parameters, request bodies, responses, operation metadata, and component schemas. The result is a report with paths, components, and a summary of added, removed, updated, and unchanged operations.</p><p>One detail I care about a lot is nested references. Most real APIs share components. If you change a field inside a nested serializer, the endpoint itself looks identical at the top level. swagger-diff-ui resolves $ref chains transitively through both the old and new schemas, so the change bubbles up to every parent operation. There is a test for this, and another one that makes sure cyclic references do not hang the diff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJGyBfBp0epOwGR0TA-nXQ.png" /></figure><h3>Installation</h3><p>You need Python 3.10 or newer, Django 4.2 or newer, Django REST Framework, drf-spectacular, and a git checkout of your project (the baseline comes from git history).</p><p>Install it from PyPI:</p><pre>pip install swagger-diff-ui</pre><p>Or straight from GitHub:</p><pre>pip install &quot;git+https://github.com/Iman-Sharei/swagger-diff-ui.git&quot;</pre><h3>Wiring it into Django</h3><p>If you have set up drf-spectacular before, this will feel familiar. It is one app and one include.</p><p>First, add the app. I recommend doing this only in your local or debug settings:</p><pre># settings (typically local / debug only)<br>INSTALLED_APPS = [<br>    # ...<br>    &quot;drf_spectacular&quot;,<br>    &quot;swagger_diff_ui&quot;,<br>]</pre><p>Then keep spectacular’s schema view and include the swagger-diff-ui routes. The docs page finds the current schema by the URL name api-schema, so keep that name. If your project uses a different one, set SWAGGER_DIFF_SCHEMA_URL_NAME in your settings instead:</p><pre># urls.py<br>from django.urls import include, path<br>from drf_spectacular.views import SpectacularAPIView<br>urlpatterns = [<br>    # Real OpenAPI document (unchanged)<br>    path(&quot;api/schema/&quot;, SpectacularAPIView.as_view(), name=&quot;api-schema&quot;),<br>    # Diff UI + helpers<br>    path(&quot;api/&quot;, include(&quot;swagger_diff_ui.urls&quot;)),<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNfFit1633-TpGTBnPDCsg.png" /></figure><p>Now run your dev server and open the docs:</p><pre>http://127.0.0.1:8000/api/docs/</pre><h3>Using it</h3><p>The flow is short:</p><ol><li>Open /api/docs/.</li><li>In the drawer, pick a baseline branch or a commit.</li><li>Click Compare.</li><li>Changed endpoints get NEW, UPDATE or DELETE badges.</li><li>Open an UPDATE row to see field-level changes and the colored Example Value.</li><li>Use Changed only or Show all APIs to filter, and Hide or Show to collapse the drawer.</li></ol><p>The first compare against a given commit takes a little time, because it has to create the worktree and export the schema. After that it comes from .schema-cache/. Add that folder to your .gitignore.</p><h3>The diff as JSON</h3><p>The UI is backed by plain DRF endpoints, mounted under the same prefix you include the app with. With the api/ prefix you get:</p><pre>/api/docs/                          Swagger UI + schema-diff drawer<br>/api/schema/                        Your real OpenAPI schema (spectacular)<br>/api/swagger-diff/git-refs/         Branches + recent commits<br>/api/swagger-diff/diff/?ref=...     Diff report vs baseline<br>/api/swagger-diff/baseline/?ref=... Raw baseline OpenAPI (optional)</pre><p>The diff endpoint returns a summary block along with per-path details. On my petstore demo, comparing against the first commit returned this summary:</p><pre>{&quot;added&quot;: 2, &quot;removed&quot;: 1, &quot;updated&quot;: 3, &quot;unchanged&quot;: 2}</pre><p>The ref parameter accepts branch names, SHAs, and relative refs, so ?ref=HEAD~1 compares against the previous commit.</p><h3>Where I find it useful</h3><ul><li><strong>Pull request reviews.</strong> Check out the feature branch, run the server, compare against main, and you see exactly which endpoints the PR changes. No more scrolling through serializer diffs to guess.</li><li><strong>API versioning conversations.</strong> Before a release, compare against the last release commit and walk through the badges with the frontend or mobile team.</li><li><strong>Spotting breaking changes.</strong> In the UI, the signals that usually matter are right there: removed operations in the red box, fields that went from optional to required, type changes, and removed properties. The CLI goes one step further and labels them as breaking.</li><li><strong>Onboarding.</strong> A new teammate can compare against an older commit and see how the API evolved, in a UI they already understand.</li><li><strong>CI gates.</strong> Run the management command on every pull request and let it fail the build when a change would break existing clients.</li></ul><h3>Breaking-change checks in CI</h3><p>The UI is for humans. For pipelines, the package ships a Django management command called swagger_diff. It runs the same diff, then applies a set of rules to flag likely breaking changes: removed operations, parameters, fields or responses, request fields that became required, type and $ref changes, and removed enum values.</p><pre># Diff current schema vs previous commit; fail CI if breaking<br><br>python manage.py swagger_diff --ref HEAD~1 --ci<br># Machine-readable report<br>python manage.py swagger_diff --ref origin/main --format json<br># Fail only when you ask<br>python manage.py swagger_diff --ref HEAD~1 --fail-on-breaking</pre><p>The default ref is HEAD~1. The — ci flag is shorthand for a text summary plus a failing exit code when anything breaking shows up, and — no-cache forces a fresh baseline export. Unlike the web endpoints, the command does not require DEBUG, so it can run in a CI job.</p><p>I ran it on my petstore demo. It found 9 breaking findings (the removed DELETE plus status and tag becoming required, counted per affected endpoint and on the schema itself) and exited with code 1. Without — ci or — fail-on-breaking, the same run exits with 0.</p><pre>Baseline: HEAD~1<br>Summary: added=2 removed=1 updated=3 unchanged=2 breaking=9<br>Breaking changes:<br>  • [DELETE /api/pets/{id}/] Operation DELETE /api/pets/{id}/ removed<br>  • [GET /api/pets/] [schema Pet] Property &quot;status&quot; is now required<br>  • [GET /api/pets/] [schema Pet] Property &quot;tag&quot; updated: optional → required<br>  ...</pre><p>The README includes a GitHub Actions step for pull requests:</p><pre>- name: OpenAPI breaking change check<br>  run: python manage.py swagger_diff --ref origin/${{ github.base_ref }} --ci</pre><p>To be honest about its limits, the detection is a heuristic. Treat it as a useful gate, not a formal compatibility proof. In CI, check out enough git history for the baseline ref to exist.</p><h3>Settings worth knowing</h3><p>Baseline schemas are exported in a separate process inside the worktree, so that process needs to know your settings module. It uses SWAGGER_DIFF_SETTINGS_MODULE if you set it, then DJANGO_SETTINGS_MODULE, and falls back to config.settings.local, the cookiecutter style default. If your settings live somewhere else, make sure one of the first two is set.</p><h3>Safety</h3><p>Running git commands from a web request is not something you want in production, so the git baseline endpoints only work when DJANGO_ENV is “local” or DEBUG is True. Git refs are validated before they reach any git command, and since version 0.1.3 anything that starts with a dash is rejected, so a ref can never be read by git as an option. The HTTP helpers also refuse calls that the browser marks as cross-site or that carry an Origin or Referer from another host, which stops a random web page from poking your local server. The CLI is the exception to the DEBUG gate, by design, so it works in CI. Still, please do not expose this on a production server with DEBUG turned on. Wire it only into local or staging settings.</p><h3>Try the sample project</h3><p>The repo now ships a minimal Django and DRF project that already has swagger-diff-ui wired in. It is the quickest way to see the drawer without touching your own code. From the repository root:</p><pre>pip install -e &quot;.[dev]&quot;<br>cd examples/sample_project<br>python manage.py runserver</pre><p>Then open <a href="http://127.0.0.1:8000/api/docs/">http://127.0.0.1:8000/api/docs/</a> in your browser.</p><p>The CLI works from the same folder, as long as you are inside the git checkout of the repo:</p><pre>python manage.py swagger_diff --ref HEAD~1 --format text</pre><p>One thing to keep in mind: the baseline is exported from a worktree of the whole repo, so the ref you pick must already contain the sample project. Older commits fail with a clear error message instead of a confusing traceback.</p><h3>Running the tests</h3><p>If you want to hack on it:</p><pre>pip install -e &quot;.[dev]&quot;<br>pytest -q</pre><p>The test suite covers added, removed and updated operations, parameter requiredness, nested schema changes bubbling up to parent operations, cyclic $ref handling, property add and remove classification, git ref validation including relative refs, breaking-change classification, and the same-origin guard on the HTTP helpers. All 25 tests passed when I ran them for this article, and a GitHub Actions workflow runs the same suite on Python 3.10, 3.11 and 3.12 for every push and pull request, and also runs the swagger_diff command against the sample project.</p><h3>Try it and tell me what breaks</h3><p>swagger-diff-ui is MIT licensed and still marked as alpha (version 0.1.3 at the time of writing), which means this is a good moment to shape it. If you run Django with DRF and drf-spectacular, it takes a couple of minutes to try.</p><p>If it saves you a review or catches a removed endpoint before a client does, a star on GitHub helps a lot. Issues and pull requests are very welcome.</p><p><strong>GitHub:</strong> <a href="https://github.com/Iman-Sharei/swagger-diff-ui">https://github.com/Iman-Sharei/swagger-diff-ui</a></p><p><strong>PyPI:</strong> <a href="https://pypi.org/project/swagger-diff-ui/">https://pypi.org/project/swagger-diff-ui/</a></p><p><em>Iman Sharei, AI Engineer</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274f660642e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ring Topologies and the Road Ahead for QFL]]></title>
            <link>https://medium.com/@imansharei24/ring-topologies-and-the-road-ahead-for-qfl-f91a98fd5cd2?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91a98fd5cd2</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[quantum-internet]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 12:45:23 GMT</pubDate>
            <atom:updated>2026-11-15T12:45:23.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>A decentralized, teleportation-based QFL design, and what eight papers taught me about where this field stands</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsm1eTCnwB_wlfQJkeMeaw.png" /></figure><p>Part 8, the final part of the series Private by Design: Quantum Federated Learning.</p><p>Every QFL system in this series so far has had a center. A server sends out a model, clients send back updates, the server averages. Even the blind computing protocol in Part 5 had a central quantum server.</p><p>The last paper I want to cover removes the center. Tyler Wang, Huan-Hsin Tseng and Shinjae Yoo arrange clients in a ring and pass the model around it, with the weights themselves carried as quantum states. It’s a short workshop-style paper, and I’ll be candid about how much it does and doesn’t show. Then I’ll step back and take stock of the whole series.</p><h3>Why a ring?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRhMc9cjh0CO7KZsXptOSQ.png" /></figure><p>In standard federated learning, everything flows through a hub. That’s simple, but the hub sees every update, and as Part 2 showed, updates can leak data.</p><p>In a ring, each client trains on its own data, then hands the model to the next client. There’s no central node to compromise. The authors’ argument is that a breach of one client only exposes that client’s slice of the data.</p><p>There’s also a quantum-specific reason. Quantum states can’t be copied (the no-cloning theorem), and today’s devices can’t store them for long. A hub that has to collect states from many clients, hold them, and combine them needs quantum memory nobody has yet. A ring only ever sends one state to one neighbor at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*RrNJXlhRU7hDcpOXdFCFSg.png" /></figure><p>Figure from Wang et al., 2023. Each client trains on its share of the data and passes the weights to the next; the last client’s model is evaluated on the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*RrNJXlhRU7hDcpOXdFCFSg.png" /></figure><p>Figure from Wang et al., 2023. Ring and hub-and-spoke topologies with five clients each.</p><h3>The model and its gradients</h3><p>The VQC is small. Inputs are encoded as Rx rotation angles. The variational layer applies CNOTs between neighboring qubits, then a general single-qubit rotation with three parameters on each qubit, and finally reads Pauli Z expectation values.</p><p>Gradients come from the parameter-shift rule, which I demonstrated in code in Part 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JN7VMgu-psAIl3_DUa92EQ.png" /></figure><p>The function is the expectation value of an observable B after encoding x and applying the parameterized gates. Its gradient equals a difference of the same function evaluated at shifted parameters. That’s what makes training possible on hardware: you never need anything but more circuit runs.</p><h3>Quantum weights</h3><p>This is the paper’s headline contribution. Instead of sending weights as ordinary numbers, the authors encode them into quantum states, using the same Rx encoding as the data. The expectation values of those qubits then act as the weights in the circuit. After training, the weight states are “teleported” to the next client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*yILKG3SWVnK5ml_WC8E5YQ.png" /></figure><p>Figure from Wang et al., 2023. Weights are encoded with Rx gates, used in the VQC, and updated with the parameter-shift rule.</p><p>Here’s the protocol as I understand it, in pseudocode:</p><pre>input: clients c_1..c_K in a ring, rounds R, local epochs E<br>w = initial weights<br>for r in 1..R:<br>    for k in 1..K:<br>        state = encode_weights_rx(w)                 # weights as qubit rotations<br>        for e in 1..E:<br>            w = parameter_shift_update(w, data_k, state)<br>        send w to c_(k mod K)+1 via (simulated) teleportation<br>evaluate the model held by the last client on the test set</pre><p>Two caveats the authors are upfront about. The teleportation is mimicked, not simulated at the level of real quantum channels. And the paper doesn’t say whether shot noise or channel noise was included.</p><p>I’d add a third. If the weights are recovered as expectation values before use, they’re effectively classical numbers at the moment of computation. That’s a reasonable first step, but “training entirely in quantum,” as the abstract puts it, is a stronger claim than the method supports.</p><h3>Walking through one hop</h3><p>It helps to trace a single hop in detail. The VQC measures 2 qubits, and each variational layer applies a three-parameter rotation to each of them, so a layer has 6 weights. In the quantum-weights version, each of those 6 numbers is first loaded into a qubit with an Rx rotation, and the qubit’s Z expectation value is what the circuit uses as the weight.</p><p>The client trains for 5 local epochs, updating with parameter shift. Then the weights go to the next client. In the paper’s future-work section, the authors point to an earlier protocol that sends six-qubit states using two Bell states as the channel, and suggest teleporting the 6 weights of each layer that way.</p><p>Teleportation always pairs a quantum resource with classical bits. The sender measures and must send classical results, and the receiver applies corrections based on them. So even a fully quantum ring still needs a classical channel, and the weights only arrive after those classical bits do.</p><p>Over the whole experiment, that’s 5 hops per round for 100 rounds, or 500 hand-offs of every layer’s weights. If each hand-off loses a little fidelity, the errors stack up. That’s the main reason I’d want to see this on a real network simulator before believing the quantum-weights result transfers.</p><h3>Results</h3><p>The task is binary classification on scikit-learn’s make_circles: 1,200 points, 960 for training and 240 for testing. Five clients, 100 rounds, 5 local epochs each. Three configurations: classical FL, QFL with classical weights, and QFL with quantum weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*qI1fjnvzwI1JLzP4HsKP6Q.png" /></figure><p>Figure from Wang et al., 2023. Test accuracy and losses for (a) classical FL, (b) QFL with classical weights, and © QFL with quantum weights.</p><p>The authors report that classical FL and QFL with classical weights converge around rounds 25 and 20. No numbers are given for the final accuracies, so I read them off the plots. In panel ©, the quantum-weights version only reaches roughly 0.9. Treat those readings as approximate.</p><p>The conclusion claims a quantum advantage over classical FL. The discussion section of the same paper says the dataset is too simple to show a significant one. I agree with the discussion section.</p><h3>Try it: does the order of the ring matter?</h3><p>One limitation bothered me enough that I wanted to see it. In a ring, the model you evaluate is whatever the last client left behind. If clients have very different data, the model may lean toward the last one.</p><p>I wrote a small classical simulation to check. It’s not a quantum circuit: it’s logistic regression with a squared-radius feature, which is enough to separate make_circles-style data. I matched the paper’s sizes: 1,200 points, 960 for training and 240 for testing, 5 clients, 100 rounds. I compared a ring against FedAvg on the same partitions, once with random (IID) splits and once with clients sorted by label.</p><pre>import numpy as np<br>rng = np.random.default_rng(0)<br>def circles(n):<br>    r = np.where(rng.random(n) &lt; 0.5, 0.5, 1.0) + rng.normal(0, 0.15, n)<br>    t = rng.uniform(0, 2*np.pi, n); X = np.c_[r*np.cos(t), r*np.sin(t)]<br>    return X, (r &gt; 0.75).astype(float)<br>def feats(X): return np.c_[X, (X**2).sum(1), np.ones(len(X))]<br>X, y = circles(1200); Xtr, ytr, Xte, yte = X[:960], y[:960], X[960:], y[960:]<br>def sgd(w, X, y, epochs=20, lr=2.0):<br>    F = feats(X)<br>    for _ in range(epochs):<br>        p = 1/(1+np.exp(-F@w)); w = w - lr*F.T@(p-y)/len(y)<br>    return w<br>def acc(w): return np.mean(((feats(Xte)@w) &gt; 0) == yte)<br>def split(noniid):<br>    idx = np.argsort(ytr + rng.random(960)*0.0) if noniid else rng.permutation(960)<br>    return np.array_split(idx, 5)<br>for name, noniid in [(&quot;IID&quot;, False), (&quot;label-sorted&quot;, True)]:<br>    parts = split(noniid)<br>    w_ring = np.zeros(4); w_avg = np.zeros(4)<br>    for r in range(1, 101):<br>        hops = []<br>        for p in parts:<br>            w_ring = sgd(w_ring, Xtr[p], ytr[p]); hops.append(acc(w_ring))<br>        w_avg = np.mean([sgd(w_avg.copy(), Xtr[p], ytr[p]) for p in parts], axis=0)<br>        if r in (1, 100):<br>            print(f&quot;{name:12s} round {r:3d}: ring after each hop &quot; + &quot; &quot;.join(f&quot;{h:.3f}&quot; for h in hops) + f&quot; | fedavg {acc(w_avg):.3f}&quot;)</pre><p>Here’s the real output:</p><pre>IID          round   1: ring after each hop 0.983 0.992 0.996 0.983 1.000 | fedavg 0.992<br>IID          round 100: ring after each hop 1.000 1.000 1.000 1.000 1.000 | fedavg 0.996<br>label-sorted round   1: ring after each hop 0.467 0.467 0.946 0.583 0.533 | fedavg 0.946<br>label-sorted round 100: ring after each hop 1.000 0.983 1.000 0.988 0.988 | fedavg 0.992</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4zpp0tTJSTZHQt06e5PfA.png" /></figure><p>With IID data, the ring is fine from the very first round. With label-sorted data, round 1 is a mess. After the first two clients, which hold only one class, the model scores 0.467. The third client, which holds a mix, lifts it to 0.946. Then the last two, holding the other class, drag it back down to 0.533. FedAvg, averaging all five, reaches 0.946 in one round.</p><p>By round 100, both approaches end up at 0.983 to 1.000, so the ring does recover on this easy problem. But the per-hop swing is the point. On a harder dataset, or with fewer rounds, the final client’s data could decide the result.</p><p>The paper uses make_circles with what looks like a random split, so its results don’t test this. I’d want any future ring QFL to report accuracy after every hop, not just at the end of the ring.</p><h3>What the ring does and doesn’t protect</h3><p>A ring removes the central aggregator, and that’s a real gain. But the next client in the ring receives your entire updated model. That’s the same information a server would get from you in FedAvg, and arguably more, because it isn’t averaged with anyone else’s update first.</p><p>So the gradient inversion attacks from Part 2 apply between neighbors. The authors suggest adding differential privacy as future work. I think it’s not optional. Any ring QFL deployment should add the DP machinery from Part 6 at every hop.</p><p>The no-cloning argument also needs care. It prevents an eavesdropper from copying a quantum state in transit. It doesn’t stop the intended recipient from measuring it many times over many rounds, and it doesn’t help once the weights are turned back into numbers.</p><h3>A worked example: two neighbors comparing notes</h3><p>The risk gets sharper if two clients collude. Say clients 2 and 4 sit on either side of client 3. Client 2 knows exactly which model it handed to client 3. Client 4 knows exactly which model it received back.</p><p>Subtract one from the other and they have client 3’s update, alone and unaveraged, for every round. That’s the ideal input for a gradient inversion attack from Part 2. In FedAvg, the server only ever sees client 3’s update mixed into an average, unless it’s malicious too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syVUrJJkbl3pVHoS_yhqbQ.png" /></figure><p>Nothing in the ring design prevents this. Defenses exist: per-hop DP noise, randomly reshuffling the ring each round so neighbors change, or secure aggregation run over small groups of clients. None of them is in the paper, and I’d consider the first two the minimum for any real deployment.</p><h3>How the ring compares with the rest of the series</h3><p>Every other system in this series uses a hub. Here’s what each design exposes, and to whom.</p><p>The ring is the only design without a server, but it’s also the only one where a peer sees a full, unaveraged model. The blind protocol in Part 5 is the opposite trade: a powerful central server that learns almost nothing. If I had to choose, I’d take the blind hub for privacy and the ring for resilience, and I’d want DP noise in both.</p><p>The paper also argues that the ring reduces quantum error by spreading qubits across devices. I don’t think that follows. Each client still runs the whole circuit on its own device. A ring spreads the data and the training time, not the qubits per circuit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTH8wGlVxv3TUzQJnX7Bjg.png" /></figure><h3>Practical takeaways</h3><ul><li>Use a ring when you can’t trust any single party to aggregate, but plan for the cost: training is sequential, so time grows with the number of clients.</li><li>Shuffle the ring order each round. My demo shows how much the order matters under non-IID data in early rounds.</li><li>Add DP noise at every hop. In a ring, your neighbor sees exactly what a FedAvg server would see from you.</li><li>Budget for the classical channel. Teleportation still needs classical bits for every transfer.</li><li>Until teleportation is simulated with a realistic noise model, treat “quantum weights” results as proof of concept.</li></ul><h3>Limitations &amp; open questions</h3><ul><li>Tiny benchmark. A 2D toy dataset can’t distinguish between models, and the paper says so itself.</li><li>Sequential training. A ring processes clients one at a time, so wall-clock time grows with the number of clients. With hundreds of clients, as in Part 7, that’s impractical without parallel rings or gossip protocols.</li><li>Simulated teleportation. Real teleportation needs shared entanglement and classical communication, and it’s noisy. How do fidelity losses accumulate over 100 rounds and 5 hops each?</li><li>Final-client bias. The evaluated model is whatever the last client holds. Under non-IID data, it may be biased toward that client’s distribution. Part 3 showed how much non-IID data can slow FedAvg; rings may be worse.</li><li>Privacy is unmeasured. No attack is run and no epsilon is reported.</li></ul><h3>The road ahead: what eight papers taught me</h3><p>I started this series wanting to know whether quantum computing makes federated learning more private. After reading these papers end to end, here’s where I’ve landed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCAtIFnKZ1SzfuzK-KZnew.png" /></figure><p>First, keeping data local is not privacy. That’s true for classical FL and it’s true for QFL. Gradients leak (Part 2), and none of the hybrid models in Part 3 changed that.</p><p>Second, the strongest privacy results here are cryptographic, not statistical. Blind quantum computing (Part 5) gives an unconditional guarantee against the server. That’s the clearest case I found of quantum mechanics doing something classical systems can’t.</p><p>Third, differential privacy transfers to quantum models without changes (Part 6), and NISQ noise might pay for some of it (Part 7). But the numbers reported so far are thin, and several papers contradict themselves.</p><p>Fourth, almost nothing has been run on real hardware, and none of the QFL papers in this series runs a data reconstruction attack against its own defense.</p><p>Larasati, Firdaus and Kim’s 2022 overview of the field lists many of the same challenges: limited hardware, the different nature of quantum computation, and open questions about deployment. Qiao and colleagues’ 2024 survey frames QFL around efficiency plus privacy and security tools like quantum key distribution. I’ve read both only at the abstract level, so I’m citing them for orientation rather than detail.</p><p>If I had to pick the three experiments I’d most like to see next:</p><ol><li>A DP-QFL run on a real quantum device, with measured noise feeding a published privacy accountant.</li><li>Gradient inversion attacks, like those in Part 2, run against every QFL defense in this series.</li><li>A ring or gossip QFL with per-hop DP, on a dataset harder than make_circles.</li></ol><h3>My take</h3><p>QFL isn’t ready to protect anyone’s data in production. But it has produced one genuinely new tool, blind computation, and one genuinely interesting idea, noise as a privacy resource. Those two are worth following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MONctZWRI1wpDVDNyKV1cA.png" /></figure><p>Thanks for reading the series. If you’ve only read this part, I’d start at Part 1 and skim forward; each part builds on the last.</p><p>Previous: Part 7, Turning Quantum Noise Into Privacy (link to be added on publishing).</p><p>Start of the series: Part 1, Quantum Federated Learning, Explained Simply (link to be added on publishing).</p><h3>Sources</h3><ul><li>Tyler Wang, Huan-Hsin Tseng and Shinjae Yoo, Quantum Federated Learning with Quantum Networks, 2023. <a href="https://arxiv.org/abs/2310.15084">arXiv:2310.15084</a></li><li>Harashta Tatimma Larasati, Muhammad Firdaus and Howon Kim, Quantum Federated Learning: Remarks and Challenges, IEEE CSCloud/EdgeCom 2022. <a href="https://doi.org/10.1109/cscloud-edgecom54986.2022.00010">doi:10.1109/CSCloud-EdgeCom54986.2022.00010</a> (abstract only)</li><li>Cheng Qiao, Mianjie Li, Yuan Liu and Zhihong Tian, Transitioning From Federated Learning to Quantum Federated Learning in Internet of Things: A Comprehensive Survey, IEEE Communications Surveys &amp; Tutorials, 2024. <a href="https://doi.org/10.1109/comst.2024.3399612">doi:10.1109/COMST.2024.3399612</a> (abstract only)</li><li>Weikang Li, Sirui Lu and Dong-Ling Deng, Quantum federated learning through blind quantum computing, 2021. <a href="https://arxiv.org/abs/2103.08403">arXiv:2103.08403</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91a98fd5cd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning Quantum Noise Into Privacy]]></title>
            <link>https://medium.com/@imansharei24/turning-quantum-noise-into-privacy-c45095ab99c1?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c45095ab99c1</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[differential-privacy]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[federated-learning]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 12:42:12 GMT</pubDate>
            <atom:updated>2026-11-15T12:42:12.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two 2025 papers argue that the noise NISQ devices can’t avoid could pay for differential privacy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjwBcWtnp-jNF_FuPo5TyQ.png" /></figure><p>Part 7 of the series Private by Design: Quantum Federated Learning.</p><p>Part 6 ended with a nagging question. Every quantum gradient on real hardware is already noisy, because it’s estimated from a finite number of measurements and because gates are imperfect. DP-SGD then adds more noise on top. Isn’t that wasteful?</p><p>Two 2025 papers take that question seriously from opposite directions. Pokharel, Rahman, Shaon, Morris and Nguyen try to count the hardware noise toward the privacy budget, so that you add little or no artificial noise. Phan, Nguyen, Pham and Pi do the reverse: they add noise on purpose and argue it helps quantum training, not just privacy.</p><p>Both ideas are clever. Both papers also have reporting problems that make me trust the headline numbers less than I’d like, and I’ll be specific about them.</p><h3>Where the noise comes from</h3><p>A quantum model’s output is an expectation value. On hardware, you estimate it by running the circuit M times (shots) and averaging. The estimate’s variance shrinks like one over M. That’s shot noise, and it’s unavoidable.</p><p>Gates also fail. A common model is the depolarizing channel: with some probability, a qubit’s state is replaced by pure randomness. Stack L layers, each with error rate lambda, and the chance that something went wrong grows quickly.</p><p>The key observation in Pokharel et al. is that both effects are random, independent of the data, and can be approximated as Gaussian over many shots. That’s exactly what the Gaussian mechanism in DP needs.</p><h3>Paper one: DP-QFL, noise you already paid for</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*Sa18NwJmACvRHfJUds0rpg.png" /></figure><p>Figure from Pokharel et al., 2025. NISQ clients train with a DP mechanism driven by device noise; the server aggregates; an adversary queries the global model.</p><h3>The accounting</h3><p>Here’s the chain of reasoning, simplified from their equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOXjQOtHZ6OrQQn-os9O-A.png" /></figure><p>Depolarizing errors across L layers give an effective error probability. Combined with shot noise, that sets a noise standard deviation sigma for each gradient. Clip gradients to norm C and you know the sensitivity. The Gaussian mechanism gives a per-round epsilon, and advanced composition adds it up over N clients and T rounds.</p><p>The interesting knobs here aren’t a noise multiplier anymore. They’re the number of shots and the hardware error rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*cok97Ns2J1wNS-Aco7SFdQ.png" /></figure><p>Figure from Pokharel et al., 2025. Algorithm 1: local training with noisy circuits, gradient clipping, and a final privacy cost from Eq. 14.</p><p>In pseudocode, the client side looks like this:</p><pre>input: global model w, shots M, depolarizing rate lambda, layers L, clip C<br>for each local epoch:<br>    for each batch:<br>        g = parameter_shift_gradient(circuit(w), shots = M)   # noisy by construction<br>        g = g * min(1, C / norm(g))                           # bound sensitivity<br>        w = adam_step(w, g)                                   # no extra noise added<br>sigma = noise_std_from(M, lambda, L)                          # shot + depolarizing<br>epsilon_round = gaussian_mechanism(sensitivity(C), sigma, delta)<br>return w, epsilon_round</pre><h3>A worked example: how noisy is a depolarized circuit?</h3><p>The depolarizing formula is easier to read with numbers. Pokharel et al. use a per-gate error rate lambda of 0.05 in their ablations. With 3 layers, the chance that something went wrong is 1 minus 0.95 cubed, about 0.14. With 5 layers, it’s about 0.23.</p><p>What does that do to the output? The paper splits the effect in two. The ideal expectation value gets multiplied by 1 minus p, so it shrinks toward zero. That shrinkage is the same for every input, and the paper argues, citing earlier work, that a data-independent change like this is post-processing and doesn’t affect the DP guarantee.</p><p>The part that helps privacy is the variance, which the paper says grows with 1 minus (1 minus p) squared. At 3 layers that factor is about 0.26, and at 5 layers about 0.40. Deeper circuits are noisier, and noisier means more private. That matches the direction of their Table III, where epsilon drops from 12.001 to 9.022 as depth goes from 3 to 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxSCTUhQ4ysbaNcW7Qhu7Q.png" /></figure><h3>Try it: how much privacy do shots buy?</h3><p>Shot noise is the easier half to simulate, so I did. The script below estimates a single qubit’s Z expectation value (true value 0.3) from a finite number of shots, repeats that 5,000 times, and measures the spread. Then it plugs that spread into the standard Gaussian mechanism formula.</p><p>To get an epsilon, I had to assume a sensitivity: how much one training record can shift the expectation value. I picked 0.1. That’s a made-up number for illustration, not something from either paper, and the formula I use is only valid for epsilon below 1. So read the last column as a trend, not a guarantee.</p><pre>import numpy as np<br>rng = np.random.default_rng(0)<br>p_true = 0.3                     # true &lt;Z&gt; of a qubit<br>delta = 1e-5<br>print(&quot;shots  empirical_std  theory_std  toy_epsilon&quot;)<br>for shots in [100, 1000, 10000]:<br>    ests = []<br>    for _ in range(5000):<br>        ones = rng.binomial(shots, (1 - p_true) / 2)   # count of |1&gt; outcomes<br>        ests.append(1 - 2 * ones / shots)<br>    s_emp = np.std(ests); s_th = np.sqrt((1 - p_true**2) / shots)<br>    sens = 0.1                   # assumed change in &lt;Z&gt; from swapping one record<br>    eps = np.sqrt(2 * np.log(1.25 / delta)) * sens / s_th<br>    print(f&quot;{shots:5d}  {s_emp:12.4f}  {s_th:10.4f}  {eps:10.2f}&quot;)</pre><p>Here’s the real output:</p><pre>shots  empirical_std  theory_std  toy_epsilon<br>  100        0.0966      0.0954        5.08<br> 1000        0.0296      0.0302       16.06<br>10000        0.0095      0.0095       50.79</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAaIvDS3OPoblKxlyy56ig.png" /></figure><p>The measured spread matches the theory, the square root of (1 minus 0.09) over the number of shots, to within a few percent. And it shows the uncomfortable trade-off in one table: going from 100 to 10,000 shots makes the estimate 10 times more accurate and the toy epsilon 10 times worse.</p><p>That’s the same direction as Pokharel’s budget curve: more shots, weaker privacy. It’s also why I said a cleaner device is a less private one. Any engineering win on precision is a privacy loss, unless you add noise back on purpose.</p><h3>The setup</h3><p>Everything is simulated with TorchQuantum on a GPU. Images are downscaled to 16 by 16 and amplitude-encoded. Each circuit layer has Rx, Ry and Rz on every qubit followed by CNOTs between neighbors.</p><p>There are 10 clients, each running 5 local epochs with batch size 64, for 50 rounds. Adam with learning rate 0.01, a clipping threshold of 0.8, and delta fixed at 10 to the minus 5.</p><h3>Results: the knobs and the budget</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZEON2eZdkI7P_P7VF8ZSQ.png" /></figure><p>This is the most useful table in the paper. With 30 shots and lambda of 0.1, the total epsilon is about 5.2. With 1,000 shots and lambda of 0.01, it’s above 100, which is essentially no privacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*H2bbT_v5UajTQeOnsZc91g.png" /></figure><p>Figure from Pokharel et al., 2025. Total privacy budget against number of shots, for three depolarizing factors.</p><p>The direction makes sense. More shots average out shot noise, and cleaner gates add less depolarizing noise. Either way, less randomness means less privacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cfzpv4O1JzTbee8wKz1how.png" /></figure><p>Figure from Pokharel et al., 2025. Training curves on MNIST and CIFAR-10 for the four noise settings.</p><p>On MNIST, the least private setting reached over 94% and the most private about 79%. On CIFAR-10, accuracy went from 86% down through 81%, 76% and 71% as epsilon dropped from over 100 to 25.01, 10.7 and 5.2.</p><p>They also compared against two baselines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNBPQPrF-0wncKjjaYXU9g.png" /></figure><p>DP-QFL wins on both datasets. But the paper doesn’t state which epsilon this table uses, only “the same level of security,” so I can’t place it against the curves above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MZ4D-bGWgF9NOnsccGEIg.png" /></figure><p>Two more findings from their Tables II and III. Going from 8 to 10 to 12 qubits lowered epsilon from 10.762 to 4.700 to 2.290, but MNIST accuracy fell from 86.18% to 80.47% at 12 qubits. Deeper circuits also lowered epsilon, from 12.001 at 3 layers to 9.022 at 5, without improving accuracy.</p><p>I like this ablation because it’s honest about the cost. The 12-qubit model has the best privacy number in the table, and the worst accuracy on both datasets, 80.47% and 72.19%. The authors read it as overfitting plus excess noise. Either way, more qubits isn’t a free privacy dial. The 10-qubit row, at an epsilon of 4.700 with accuracy close to the 8-qubit model, is the setting I’d pick from this table.</p><h3>The attack they tested isn’t a privacy attack</h3><p>The paper evaluates robustness against a black-box FGSM attack: the adversary queries the model, trains a substitute, and crafts perturbed inputs to cause misclassification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*QM_lZRqe2SW7VCG1IhvOqA.png" /></figure><p>Figure from Pokharel et al., 2025. Under FGSM, the DP model keeps higher accuracy and a lower attack success rate than the non-private baseline.</p><p>The DP model did better under attack, about 7% higher accuracy on average. That’s a real result, but it’s about adversarial robustness, not privacy. Nobody tried to reconstruct a client’s data from its updates, which is the threat DP is meant to stop.</p><h3>Where the paper contradicts itself</h3><ul><li>The text says “the privacy budget decreases with a higher number of shots.” The figure and the table say the opposite, and so does the math. I’m going with the figure.</li><li>The text says the strongest privacy (about 5) came from 30 shots and a depolarizing factor of 0.01. The figure legend says 0.1. Again, the legend fits the logic.</li><li>The budget analysis says it uses 8 qubits and 3 layers, giving 10.7 at 60 shots and lambda 0.05. But Table III reports 12.001 for 3 layers and 10.762 for 4 layers at those same settings.</li></ul><p>None of these change the main idea. They do mean I wouldn’t quote a specific epsilon from this paper without checking it myself.</p><h3>Paper two: ADP-QFL, noise as a feature</h3><p>Phan et al. start from a different problem. Quantum neural networks suffer from vanishing gradient variance as qubits and layers grow, the barren plateau problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*lRXf9V4JoAuq4IpjMb5LVw.png" /></figure><p>Figure from Phan et al., 2025. Gradient variance decays quickly with more qubits and more layers.</p><p>Their argument is that low gradient variance causes two problems. Training gets stuck in sharp minima, and the transmitted updates become too predictable, which they argue makes them easier to attack. Adding calibrated noise addresses both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*ZjfLSAWV1Iw4L-8fq7MYXg.png" /></figure><p>Figure from Phan et al., 2025. Clients train locally, add noise, and pass a threshold check before the server averages their models.</p><h3>The mechanism</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lFiptXIo4fFXKZ0gmaruQ.png" /></figure><p>Three pieces matter. First, the noise variance decays over rounds, so early training gets a lot of noise and later fine-tuning gets little. Second, a lemma sets the starting variance from the target epsilon, the number of rounds, and the number of participating clients. Third, a filter: the server only accepts a client’s noisy model if it’s within b over lambda of the client’s own noise-free estimate.</p><p>They also bound the QNN’s gradient variance by 3 sigma squared over 2 to the 2n minus 1, for n qubits. That’s the formal version of the barren plateau worry.</p><pre>input: N clients, K per round, rounds T, target epsilon, delta, decay alpha<br>sigma0^2 = noise_from_lemma(T, K, epsilon, delta)<br>for t in 1..T:<br>    sigma_t^2 = sigma0^2 / (1 + alpha * t)          # adaptive decay<br>    S = select K clients<br>    for each client u in S (in parallel):<br>        phi_u = local_train(global_model, data_u)<br>        phi_hat_u = phi_u + Normal(0, sigma_t^2)     # client-level noise<br>        if norm(phi_hat_u - phi_u) &lt;= b / lambda:    # model estimation filter<br>            send phi_hat_u to server<br>    global_model = average(received models)<br>return global_model</pre><p>One thing in that loop bothers me. The filter compares the noisy model with the clean one and drops clients whose noise was large. Rejecting large noise draws changes the noise distribution, and I didn’t see the privacy proof account for that. I may be missing it, but it’s the first thing I’d ask the authors.</p><h3>The setup</h3><p>100 clients, 800 rounds, one local epoch with batch size 10, Adam at 0.005, MSE loss. The model is an 8-qubit QCNN with three conv and pool pairs and 64 parameters. All data is non-IID, with label skew. The simulation ran on a laptop-class CPU.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpxwXoGLd9IIxv1tmxw5Ng.png" /></figure><p>On MNIST, ADP-QFL leads at 98.47%, narrowly ahead of FedRep and pFedMe. On CIFAR-10, it’s at 83.85%, behind FedBN and FedRep, though well ahead of plain FedAvg and the quantum FedQNN baseline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*00R6S3lJJGLiUTxQKH9EwA.png" /></figure><p>Figure from Phan et al., 2025. Test accuracy at epsilon 1.0: ADP-QFL against QFL without the estimation filter and classical FL with DP.</p><p>At epsilon 1.0, ADP-QFL reached 0.83, 0.91, 0.94 and 0.98 at rounds 100, 300, 600 and 800. QFL without the filter ended near 0.90, and classical FL with DP near 0.85.</p><p>They also report MNIST accuracy above 97.57% across privacy budgets from 0.000423 to 0.9.</p><h3>What else the experiments show</h3><p>Phan et al. back up the headline table with a few extra checks that are worth knowing about.</p><p>Statistical tests. They report paired t-tests against every baseline. On MNIST, ADP-QFL’s lead is significant against all five (p below 0.01). On CIFAR-10, there’s no significant difference from FedRep, FedBN or FedQNN (p above 0.05). That’s a fair way to say “competitive, not better” on the harder dataset, and I appreciate that they include it.</p><p>Time. ADP-QFL converged in 1,356 seconds on MNIST, close to FedAvg’s 1,270, and faster than FedBN, pFedMe and FedRep. On CIFAR-10 it took 9,322 seconds, slower than FedAvg, FedBN and FedRep, but faster than pFedMe and FedQNN.</p><p>Participation. With 10%, 20% and 50% of clients per round, CIFAR-10 accuracy went from 82.78% to 82.98% to 83.85%. MNIST barely changed. More clients per round help on harder data, though each extra client also spends privacy budget.</p><p>The filter’s effect. The comparison with “QFL without estimation” is effectively an ablation of the filter. At epsilon 1.0, removing it drops final accuracy from about 0.98 to about 0.90. That’s a big effect, which is exactly why I want to know whether the filter’s rejection step is covered by the privacy proof.</p><h3>A worked example of the noise schedule</h3><p>The decay rule divides the starting variance by 1 plus alpha times the round number. The paper’s text doesn’t give the value of alpha it used, so here’s an illustration with a value I chose, 0.01. At round 100 the variance is half its starting value. At round 800, the last round, it’s one ninth.</p><p>In standard deviation terms, that’s a factor of 3 between the first and last round. Early rounds, when the model is far from any minimum, take most of the noise. That is a sensible schedule for training. For privacy, though, what matters is the total across all rounds, and the paper’s lemma sets the starting variance so that the total matches the target epsilon.</p><h3>Why I’m cautious</h3><ul><li>Inconsistent setup. The text says 20 clients per round (a ratio of 0.2), Table IV says 10%, and 83.85% on CIFAR-10 is reported both for 10% participation (Table IV) and for 50% (the participation study, where 10% gives 82.78%).</li><li>Labels. The privacy figure’s legend calls the values “noise,” while the text calls them privacy budgets.</li><li>Too good to be true. An epsilon of 0.000423 with almost no accuracy loss would be remarkable. Classical DP research would struggle to get anywhere near that. I’d need to see the accountant to believe it.</li><li>The task framing. The algorithm is titled “Task-level Differential Privacy” while the text claims client-level DP. Those aren’t the same guarantee.</li><li>A small model doing a lot. 64 parameters and 8 qubits reaching 98.47% on 10-class MNIST is surprising. The paper doesn’t describe how 784 pixels reach 8 qubits.</li></ul><h3>Putting the two side by side</h3><p>Pokharel et al. ask: how much privacy does the hardware give me for free? Phan et al. ask: how should I add noise so that it helps training too?</p><p>The first idea is more novel and, I think, more important long term. It changes what “better hardware” means: a cleaner device is a less private one, unless you add noise back. The second is closer to well-known classical tricks (decaying noise schedules and robust aggregation) applied to QNNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22HFaJvi5r97xA47Ircuzg.png" /></figure><h3>How this fits with the rest of the series</h3><p>The table in Part 6 showed where each paper puts its noise. These two papers stretch the idea in opposite directions. Pokharel et al. move the noise source into the hardware. Phan et al. move the noise target from single records up to whole client models.</p><p>Compared with Part 6, both give up some rigor. Watkins and Rofougaran used a standard accountant on exact simulations. Here, Pokharel relies on a Gaussian approximation of device noise and loose advanced composition, and Phan’s filter raises an unanswered question. Compared with Part 5, neither hides anything from the server: privacy here is statistical, not cryptographic.</p><h3>Practical takeaways</h3><ul><li>If you run QFL on real hardware, record the shot count and calibration data for every job. Without them, you can’t claim the hardware noise as privacy.</li><li>Treat hardware noise as a floor, not the whole budget. Add calibrated classical noise on top, so the guarantee doesn’t depend on a provider’s error rates.</li><li>When you sweep qubits or depth, report accuracy and epsilon together, as Pokharel et al. do. The best privacy row is rarely the best model.</li><li>If you add a filter or any step that depends on the noise draw, include it in the privacy proof or test it empirically.</li><li>Decide early whether you need record-level or client-level privacy. Phan’s approach targets the second, Pokharel’s the first.</li></ul><h3>Limitations &amp; open questions</h3><ul><li>Is hardware noise trustworthy noise? DP requires that the noise distribution is known and can’t be influenced by an attacker. Real device noise drifts with calibration and temperature. If the provider lowers it, your epsilon silently gets worse.</li><li>Who controls the shots? In a cloud setting, the shot count may be set by the user, but the noise model is the provider’s. That’s a strange trust split.</li><li>No reconstruction attacks. Neither paper runs gradient inversion against its private models. Until someone does, the epsilons are the only evidence, and I’ve shown why I’d double-check them.</li><li>Simulated noise. Pokharel et al. model depolarizing noise in simulation. Real devices have correlated, non-depolarizing errors.</li><li>Composition. Advanced composition over N clients and T rounds is loose. A modern accountant (like Renyi DP) might give much tighter numbers, and might change which settings look viable.</li><li>The filter question in ADP-QFL, described above.</li></ul><h3>My take</h3><p>The best idea in this part of the literature is simple: on NISQ hardware, noise is not just a cost, it’s a resource you can account for. I’d like to see it tested on real hardware with a measured noise model and an actual inversion attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhF5TBzupvEH9S5cetKj-A.png" /></figure><p>Until then, I’d treat both papers as promising directions with numbers that need independent checking.</p><p>Previous: Part 6, Differential Privacy for Quantum Classifiers (link to be added on publishing).</p><p>Next: Part 8, Ring Topologies and the Road Ahead for QFL (link to be added on publishing).</p><h3>Sources</h3><ul><li>Atit Pokharel, Ratun Rahman, Shaba Shaon, Thomas Morris and Dinh C. Nguyen, Differentially Private Federated Quantum Learning via Quantum Noise, 2025. <a href="https://arxiv.org/abs/2508.20310">arXiv:2508.20310</a></li><li>Duc-Thien Phan, Minh-Duong Nguyen, Quoc-Viet Pham and Huilong Pi, Enhancing Gradient Variance and Differential Privacy in Quantum Federated Learning, 2025. <a href="https://arxiv.org/abs/2509.05377">arXiv:2509.05377</a></li><li>John Preskill, Quantum Computing in the NISQ era and beyond, 2018. <a href="https://arxiv.org/abs/1801.00862">arXiv:1801.00862</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c45095ab99c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Differential Privacy for Quantum Classifiers]]></title>
            <link>https://medium.com/@imansharei24/differential-privacy-for-quantum-classifiers-67c633e02f40?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/67c633e02f40</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[differential-privacy]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[federated-learning]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 19:22:35 GMT</pubDate>
            <atom:updated>2026-11-12T19:22:35.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>What DP-SGD costs a variational circuit, from a single model to a hundred federated clients</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PI5lc0OpFytkOXtW4r9JLw.png" /></figure><p>Part 6 of the series Private by Design: Quantum Federated Learning. This is the first of three advanced pieces.</p><p>Up to now, the series has treated differential privacy as a box you tick. Part 5 added noise to gradients but never said how private the result was. In this piece I want to fix that, using two papers from the same Brookhaven group that put real numbers on it.</p><p>The first, by William Watkins, Samuel Yen-Chi Chen and Shinjae Yoo, was the first demonstration of a differentially private variational quantum classifier. The second, by Rod Rofougaran, Shinjae Yoo, Huan-Hsin Tseng and Samuel Yen-Chi Chen, takes the same machinery into federated learning.</p><p>My short version: both papers show DP-SGD works on quantum circuits with surprisingly little accuracy loss. Neither shows that the quantum part is doing anything a classical model couldn’t, and the federated paper’s privacy number deserves a careful read.</p><h3>A precise definition of private</h3><p>Differential privacy says something specific. Take any two datasets that differ by one record. A training algorithm is private if the probability of producing any given model barely changes between the two.</p><p>“Barely” is controlled by two numbers. Epsilon bounds the multiplicative change in probability, and smaller is stronger. Delta is a small probability that the guarantee fails outright, usually set below one over the dataset size.</p><p>Both papers use delta of 10 to the minus 5. Watkins et al. justify it explicitly: if delta were bigger than one over n, an algorithm could “satisfy” DP by publishing a few complete records.</p><h3>DP-SGD in three moves</h3><p>The standard recipe, from Abadi et al., changes ordinary stochastic gradient descent in three ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWo2L6vyG17Id1ysUu2Qaw.png" /></figure><p>First, clip each example’s gradient so its length is at most S. This caps how much any one record can pull the model. Second, add Gaussian noise with standard deviation equal to the noise multiplier sigma times S. Third, track the cumulative privacy loss over every step with an accountant, which turns sigma, the sampling rate and the number of steps into an epsilon.</p><p>Here’s the loop as pseudocode:</p><pre>input: data D of size N, batch size B, clip norm S, noise multiplier sigma,<br>       steps T, learning rate eta<br>initialize circuit parameters theta<br>for t in 1..T:<br>    sample batch b from D with probability q = B / N per example<br>    for each example x in b:<br>        g_x = gradient of loss(x, theta)          # parameter shift on hardware<br>        g_x = g_x * min(1, S / norm(g_x))         # clip<br>    g = (sum of g_x + Normal(0, sigma^2 S^2 I)) / B   # noise<br>    theta = optimizer_step(theta, g)<br>epsilon = accountant(q, sigma, T, delta)<br>return theta, epsilon</pre><p>Nothing in that loop cares whether the model is a neural network or a quantum circuit. That’s the key observation behind both papers. The quantum circuit produces a gradient (through the parameter-shift rule, or analytically in simulation), and from there on it’s classical post-processing.</p><h3>A worked example: what one noisy step looks like</h3><p>Numbers make this easier to feel. Take the Watkins settings: batch size 32 and a clip norm of 1.0. After clipping, no single example can move the summed gradient by more than 1.0 in length.</p><p>Now add noise with multiplier 1. Each coordinate of the summed gradient gets Gaussian noise with standard deviation 1.0, the same size as the largest possible pull from one example. Divide by the batch of 32 and both shrink together, to about 0.031.</p><p>That’s the whole trick in one sentence. The noise is calibrated so that any one record’s influence is buried in randomness of the same size, while the 31 other examples, pulling in roughly the same direction, still add up to a usable signal.</p><p>It also explains why batch size matters so much. Bigger batches mean more honest signal per step for the same noise, which is why DP training usually prefers larger batches than ordinary training.</p><h3>Why quantum gradients are easy to clip</h3><p>Here’s a property of VQCs that I think both papers undersell. With the parameter-shift rule, each partial derivative is half the difference of two expectation values. If the measured observable is a Pauli operator, each expectation value lies between minus 1 and 1, so each partial derivative is at most 1 in size.</p><p>That means a VQC’s gradient is bounded by construction, before you clip anything. For a squared loss on labels of plus or minus 1, the loss multiplies that by at most 4. A classical network has no such ceiling. Its gradients can be huge on outliers, which is exactly what clipping has to tame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uE5EjGZGGNSmCW12gcwi7w.png" /></figure><p>In practice this means you can pick the clip norm from the circuit’s structure instead of tuning it. I haven’t seen either paper exploit that, and it’s one of the few places where the quantum model has a clean, structural edge under DP.</p><h3>Try it: DP-SGD on a one-qubit classifier</h3><p>To make the loop concrete, I wrote a tiny version in PennyLane. One qubit, one input encoded as an RY angle, two trainable rotations, 64 training points with a threshold label. Each step samples 16 examples, computes per-example gradients, clips them to norm 1, adds Gaussian noise, and updates. I ran 40 steps for each noise multiplier, with 5 random seeds each.</p><pre>import pennylane as qml<br>from pennylane import numpy as np<br>np.random.seed(0)<br>dev = qml.device(&quot;default.qubit&quot;, wires=1)<br>@qml.qnode(dev)<br>def f(x, w):<br>    qml.RY(x, wires=0); qml.RY(w[0], wires=0); qml.RZ(w[1], wires=0)<br>    return qml.expval(qml.PauliZ(0))<br># toy data: label +1 if x &lt; pi/2 else -1<br>X = np.random.uniform(0, np.pi, 64, requires_grad=False)<br>Y = np.where(X &lt; np.pi/2, 1.0, -1.0)<br>grad = qml.grad(lambda w, x, y: (f(x, w) - y) ** 2, argnums=0)<br>def acc(w): return np.mean(np.sign([f(x, w) for x in X]) == Y)<br>C, lr, B = 1.0, 0.3, 16<br>for sigma in [0.0, 1.0, 4.0, 8.0]:<br>    accs, clipped = [], 0<br>    for seed in range(5):<br>        np.random.seed(seed); w = np.array([0.8, 0.1], requires_grad=True)<br>        for step in range(40):<br>            idx = np.random.choice(64, B, replace=False)<br>            gs = []<br>            for i in idx:<br>                g = grad(w, X[i], Y[i]); n = np.linalg.norm(g)<br>                if n &gt; C: clipped += 1<br>                gs.append(g / max(1.0, n / C))<br>            noisy = (np.sum(gs, axis=0) + np.random.normal(0, sigma * C, 2)) / B<br>            w = w - lr * noisy<br>        accs.append(acc(w))<br>    print(f&quot;noise multiplier {sigma:3.1f}: mean accuracy {np.mean(accs):.3f}, worst {np.min(accs):.3f}, clipped {clipped}/{5*40*B}&quot;)</pre><p>Here’s the real output from my run:</p><pre>noise multiplier 0.0: mean accuracy 0.981, worst 0.922, clipped 1119/3200<br>noise multiplier 1.0: mean accuracy 0.972, worst 0.922, clipped 1132/3200<br>noise multiplier 4.0: mean accuracy 0.950, worst 0.891, clipped 1110/3200<br>noise multiplier 8.0: mean accuracy 0.887, worst 0.719, clipped 1127/3200</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq-_lHRnK2Uy7eaa6jE1nQ.png" /></figure><p>Three things stand out. First, the clipping rate barely moves with noise, at about 35% of per-example gradients, because clipping happens before noise is added. Second, accuracy falls smoothly as the noise multiplier rises, from 0.981 with no noise to 0.887 at multiplier 8.</p><p>Third, and to me most useful, the worst seed falls much faster than the mean: 0.719 at multiplier 8. That’s the same pattern as the Watkins circles result. Under DP, single runs get unreliable, so a table with one number per cell can hide a lot of spread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8aA1pXpHFQZbQ9ic_SAUQ.png" /></figure><p>This demo doesn’t compute an epsilon. That needs a privacy accountant (Watkins et al. used PyVacy, and Opacus is the common choice today), and with only 64 points, any honest epsilon would be large. The point is the mechanics, not the guarantee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEHlvzk8HtHQD4C3EBwrvQ.png" /></figure><p>Figure from Watkins et al., 2021. The quantum computer evaluates the circuit and gradients; the noise is added classically before the update.</p><h3>Paper one: a private VQC</h3><p>Watkins et al. built small hybrid classifiers in PennyLane with a PyTorch interface, the Qulacs simulator, and the PyVacy library for DP. They used RMSprop with learning rate 0.05, momentum 0.5, batch size 32, a clip norm of 1.0, and delta of 10 to the minus 5.</p><p>They compared each VQC against a classical neural network with a similar parameter budget. That’s the right control, and I wish more QML papers did it.</p><h3>The 2D benchmarks</h3><p>Three scikit-learn toy sets: blobs, moons and circles, with 200 samples each. The VQC uses two chained two-qubit subcircuits with 24 parameters. The classical network has 36.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmhRPunoHV5CESO0GP0vzg.png" /></figure><p>On blobs and moons, the two models are close at every privacy level. Circles is where it gets interesting: under DP, the network collapses to 0.47 and 0.43, worse than a coin flip, while the VQC holds at 0.60.</p><p>The authors read that as a possible quantum advantage. I’d be more careful. A 0.60 on a balanced two-class problem isn’t a usable classifier either, and with no error bars or repeat counts reported, the gap could easily come from how each model happened to initialize.</p><p>One odd detail: the VQC on moons scores 0.88 with privacy and 0.87 without. The paper notes it as the single exception. I’d guess it’s noise between runs rather than DP helping.</p><h3>MNIST 0 vs 1</h3><p>This is the stronger experiment. The 784 pixels are zero-padded to 1,024 and amplitude-encoded into 10 qubits. The VQC has two subcircuits, 240 plus 48 parameters, for 288 total. The classical baseline is a 1,024 to 1 to 2 network with 1,029 parameters.</p><p>They swept the noise multiplier from 1.0 to 5.0, which gave epsilon values from about 1.73 down to about 0.07.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJ4GnYfTASUejZ6V_eBtYQ.png" /></figure><p>At moderate privacy, both models stay above 0.92. The VQC is actually ahead for epsilon between about 0.41 and 1.34, for example 0.98 versus 0.97 at epsilon 1.07, and the table caption says so. But from epsilon 0.26 downward, the VQC drops steadily, ending at 0.74 against the network’s 0.83.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8s7k1avwymSdxXX9Q46Ayw.png" /></figure><p>Figure from Watkins et al., 2021. Accuracy after 30 epochs against epsilon for MNIST 0 vs 1.</p><p>Here’s a problem. The caption of that figure says the quantum classifier “is at least as accurate as the classical classifier for all investigated DP levels.” Their own Table III says otherwise for the four strongest privacy settings. I trust the table. The fair summary is that a VQC with 28% of the parameters matches the network under mild privacy and falls behind under strong privacy.</p><h3>Paper two: DP inside quantum federated learning</h3><p>Rofougaran et al. take the same idea into the federated setting. Their model is the hybrid from Part 3: a pretrained VGG16 feature extractor feeding a 4-qubit VQC, trained on Cats vs Dogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*BPIBJC4BBrjyVJrIzhDN6Q.png" /></figure><p>Figure from Rofougaran et al., 2023. The QFL setup: a global quantum model is shared, selected clients train locally and send updates back.</p><p>The data, 23,000 images, is split evenly across 100 clients. Each round, 5 clients are chosen at random and run local DP-SGD for 1, 2 or 4 epochs, then the server averages their parameters. Each configuration was repeated three times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*k1OVbtFaI5khgmwJCh4ajQ.png" /></figure><p>Figure from Rofougaran et al., 2023. Algorithm 1, QFL-DP: DP-SGD runs inside each selected client, and the privacy cost is computed at the end with an accountant.</p><h3>How much noise is enough?</h3><p>The paper quotes a theorem from Abadi et al. that ties the noise level to the target privacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaFUPNQoClEO3GjE8_zPCw.png" /></figure><p>Read it from left to right. More steps T and a larger sampling ratio q need more noise. A smaller target epsilon needs more noise. The constant c2 hides the details, so in practice people use a numerical accountant instead.</p><h3>Results</h3><p>All runs, private or not, converged to roughly 0.98 test accuracy, with epsilon around 1.24 and delta of 10 to the minus 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*e3j9z7MohcplxrrFymiGVw.png" /></figure><p>Figure from Rofougaran et al., 2023. Training with 1, 2 and 4 local epochs under DP, against a non-private baseline.</p><p>More local epochs meant fewer rounds to converge and lower variance. Private training was slower and noisier, as you’d expect.</p><p>Then they varied the noise multiplier: 0.15, 1 and 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*jroF3eon4cNgcv5rL-715A.png" /></figure><p>Figure from Rofougaran et al., 2023. Three noise levels; all converge to about 0.98.</p><p>The final accuracy didn’t change across the three. The authors say so honestly and suggest the task is too easy. I agree, and I’d go further.</p><h3>What I think the 0.98 really means</h3><p>Remember from Part 3 that this model is mostly VGG16. The pretrained convolutional layers already turn a cat photo into features that separate cats from dogs very well. The VQC is a tiny head on top of a huge classical network.</p><p>So “DP doesn’t hurt accuracy” here mostly tells us that a well-pretrained feature extractor makes the remaining learning easy. It’s a real and useful result for practitioners. It just isn’t evidence about quantum models under DP.</p><p>There’s also a wording issue. The paper says “higher epsilon results in a slower, higher-variance training process.” Every other sentence around it, and DP theory, say the opposite: more noise means lower epsilon and slower training. I’m fairly sure that’s a typo for “lower epsilon.”</p><p>And the epsilon of 1.24 is the global one, computed over all rounds. It’s a record-level guarantee for each client’s data. It is not a client-level guarantee: it doesn’t promise that an observer can’t tell whether a given client participated at all. Part 7 covers a paper that goes after the client-level version.</p><h3>Comparing the two papers side by side</h3><p>Both papers clip and noise per example, both use delta of 10 to the minus 5, and both simulate noise-free circuits with exact expectation values.</p><p>The differences matter more. Watkins et al. use small fully quantum classifiers and a parameter-matched classical baseline, so their results say something about the quantum model itself. Rofougaran et al. use a large classical backbone and no classical baseline, so their results say something about the pipeline.</p><p>If I were designing the next experiment, I’d take the Rofougaran federated setup and swap in the Watkins controls: a matched classical head, multiple seeds, and a sweep that pushes epsilon below 0.3, where the Watkins VQC started to struggle.</p><h3>How this compares with the rest of the series</h3><p>It helps to line up where each paper in this series puts its noise, because the guarantees differ more than the word “differential privacy” suggests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmWizXQRiDvOKCqV3CsYuQ.png" /></figure><p>Part 5’s blind protocol adds Gaussian noise to gradients, but its main protection is cryptographic: the server never learns the circuit. The two papers here add noise per example, which protects individual records. Part 7 will show two departures: letting the hardware supply the noise, and adding noise to whole client models for a client-level guarantee.</p><p>My reading is that record-level DP is the most mature of these. Its accounting is standard, the libraries exist, and the Watkins MNIST sweep is the cleanest experiment in the series. The other approaches promise more but, as Part 7 shows, come with weaker evidence.</p><h3>Practical takeaways</h3><ul><li>If you’re building a private VQC today, start with plain DP-SGD from an existing library. Nothing quantum-specific is needed.</li><li>Use the bounded parameter-shift gradient to set the clip norm, and log how often clipping actually triggers.</li><li>Run several seeds per privacy level. My toy run shows the worst seed can drift far below the mean.</li><li>Report the accountant, the sampling rate and the number of steps alongside epsilon, as Watkins et al. do. Without them, an epsilon can’t be checked.</li><li>Be clear about whether your epsilon covers records or whole clients. In federated settings, they answer different questions.</li></ul><h3>Limitations &amp; open questions</h3><ul><li>No hardware. Both papers compute exact expectation values. On a real device, every gradient is estimated from a finite number of shots, which is itself noisy. Should that noise count toward the privacy budget? Part 7 says yes.</li><li>Thin statistics. Watkins et al. report a single number per configuration, with no spread. The circles result, the most quantum-favorable, is the one I’d most like to see with error bars.</li><li>The advantage question is open. Under strong privacy, the MNIST VQC lost to a network with about 3.6 times as many parameters. Is that a property of VQCs, of amplitude encoding, or of this particular architecture? Nobody knows yet.</li><li>Record-level versus client-level. Rofougaran’s epsilon protects individual images, not whole clients. For federated learning, the client-level question is often the one regulators and users care about.</li><li>No attack evaluation. Neither paper runs a gradient inversion attack against its private model. None of the papers in this series has done that yet, and it’s the kind of evidence I’d want alongside every epsilon.</li><li>Barren plateaus. Clipping and noise both shrink the useful signal in each gradient. For deeper circuits, where gradients can already vanish, how does DP interact with that? I haven’t seen it studied.</li></ul><h3>My take</h3><p>These two papers did the unglamorous but necessary work: they showed that the standard DP toolkit transfers to quantum models without modification. That’s worth more than it sounds, because it means quantum FL can borrow a decade of classical privacy engineering.</p><p>What they haven’t shown is that quantum models are better at being private. On the cleanest comparison available, MNIST with matched baselines, the answer was “about the same, then worse.” I’d love to be proven wrong, but that’s what the data says today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZxkHuL5WgbBSrdXIch0TQ.png" /></figure><p>Previous: Part 5, Blind Quantum Computing Meets Federated Learning (link to be added on publishing).</p><p>Next: Part 7, Turning Quantum Noise Into Privacy (link to be added on publishing).</p><h3>Sources</h3><ul><li>William M. Watkins, Samuel Yen-Chi Chen and Shinjae Yoo, Quantum machine learning with differential privacy, 2021. <a href="https://arxiv.org/abs/2103.06232">arXiv:2103.06232</a></li><li>Rod Rofougaran, Shinjae Yoo, Huan-Hsin Tseng and Samuel Yen-Chi Chen, Federated quantum machine learning with differential privacy, 2023. <a href="https://arxiv.org/abs/2310.06973">arXiv:2310.06973</a></li><li>Martin Abadi et al., Deep Learning with Differential Privacy, 2016. <a href="https://arxiv.org/abs/1607.00133">arXiv:1607.00133</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67c633e02f40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blind Quantum Computing Meets Federated Learning]]></title>
            <link>https://medium.com/@imansharei24/blind-quantum-computing-meets-federated-learning-cf411af90b8f?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf411af90b8f</guid>
            <category><![CDATA[quantum-machine-learning]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 19:16:48 GMT</pubDate>
            <atom:updated>2026-11-12T19:16:48.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Li, Lu and Deng let clients train on a quantum server that can’t see their data or their model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFv8HCVebvxakBtBAcQTWg.png" /></figure><p>Part 5 of the series Private by Design: Quantum Federated Learning.</p><p>TL;DR</p><ul><li>Li, Lu and Deng combine two protections: universal blind quantum computing (UBQC), which hides the computation from the quantum server, and differential privacy, which hides each client’s data from everyone else.</li><li>Clients only need to prepare single qubits. The server does the heavy quantum work and, by the protocol’s design, learns nothing about inputs, outputs or the circuit.</li><li>In simulation, classifiers reached about 98% on MNIST (1 vs 9) and about 94% on breast cancer data (WDBC). Adding differential privacy slowed training, and their gradient attack recovered digits with high fidelity without it.</li><li>I include a small script showing why a disguised angle tells the server nothing, and the parameter-shift rule they use for gradients.</li></ul><h3>A different threat model</h3><p>Parts 3 and 4 assumed every client owns a quantum computer, or at least a simulator. That’s not realistic for a while. Most people who want quantum compute will rent it.</p><p>So here’s the question this paper asks. If I send my training job to someone else’s quantum computer, how do I stop the owner from reading my data and my model?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7ZQ7wl9EYj8UnuDdzm9SQ.png" /></figure><p>Weikang Li, Sirui Lu and Dong-Ling Deng answer with a protocol from quantum cryptography called universal blind quantum computing, introduced by Broadbent, Fitzsimons and Kashefi. Then they bolt differential privacy on top for the multi-client case.</p><h3>Blind quantum computing in plain terms</h3><p>There are two parties. Alice, the client, has data but only a tiny quantum capability: she can prepare single qubits in a few chosen states. Bob, the server, has a full quantum computer but isn’t trusted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7HG8evHwt3nCI-hh3vqkw.png" /></figure><p>Alice sends Bob a stream of single qubits, each rotated by a secret random angle. Bob entangles them into a fixed, generic pattern called a brickwork state. Then Alice tells Bob, one qubit at a time, which angle to measure at. Bob measures and reports back a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCk1cNgvXDOLcQTvilx3FA.png" /></figure><p>The trick is that the brickwork pattern is the same for every computation. What makes it compute something specific is the sequence of measurement angles. And Alice never sends the real angles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qg9ZHQrg6INKpWBQV9k-Fg.png" /></figure><h3>The disguise</h3><p>Each real measurement angle is hidden by two secrets: the random angle Alice baked into the qubit, and a random bit that adds an extra half turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNTMOfK9O8V6SZPsBpzdZQ.png" /></figure><p>Bob sees only the disguised angle. Because the secret angle is uniformly random, every disguised angle is equally likely no matter what the real one was. Alice can undo the effect of her secrets on the results; Bob can’t. The paper stresses that this security is unconditional: it doesn’t depend on any assumption about Bob’s computing power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVpe4x1aar-D01hrqlpPBA.png" /></figure><h3>Try it: the disguise and the gradient</h3><p>Here’s a short script that checks both formulas above. The first half samples disguised angles for three different “true” angles and counts how often the server sees each possible value. The second half checks the parameter-shift rule on a one-qubit circuit.</p><pre># Two ideas from Li, Lu &amp; Deng: hidden measurement angles and the parameter-shift rule<br>import numpy as np<br>import pennylane as qml<br>from pennylane import numpy as pnp<br><br>rng = np.random.default_rng(0)<br>angles = np.arange(8) * np.pi / 4           # UBQC angles live on multiples of pi/4<br><br>def disguise(phi, n=100_000):<br>    theta = rng.choice(angles, n)           # client&#39;s secret random angle<br>    r = rng.integers(0, 2, n)               # client&#39;s secret random bit<br>    return np.mod(phi + theta + r * np.pi, 2 * np.pi)<br><br>for phi in [0.0, np.pi / 4, 3 * np.pi / 2]:<br>    d = disguise(phi)<br>    counts = np.bincount(np.round(d / (np.pi / 4)).astype(int) % 8, minlength=8) / len(d)<br>    print(f&quot;true angle {phi:4.2f}: server sees each of 8 angles with freq&quot;, np.round(counts, 3))<br><br>dev = qml.device(&quot;default.qubit&quot;, wires=1)<br>@qml.qnode(dev)<br>def f(t):<br>    qml.RX(t, wires=0)<br>    return qml.expval(qml.PauliZ(0))<br><br>t = pnp.array(0.7, requires_grad=True)<br>shift = (f(t + np.pi / 2) - f(t - np.pi / 2)) / 2<br>print(f&quot;parameter-shift gradient: {float(shift):.6f}&quot;)<br>print(f&quot;autograd gradient:        {float(qml.grad(f)(t)):.6f}&quot;)<br>print(f&quot;exact -sin(0.7):          {-np.sin(0.7):.6f}&quot;)</pre><p>Real output from my run:</p><pre>true angle 0.00: server sees each of 8 angles with freq [0.126 0.124 0.125 0.124 0.124 0.126 0.125 0.125]<br>true angle 0.79: server sees each of 8 angles with freq [0.125 0.126 0.123 0.126 0.126 0.124 0.124 0.127]<br>true angle 4.71: server sees each of 8 angles with freq [0.124 0.126 0.125 0.125 0.125 0.126 0.126 0.124]<br>parameter-shift gradient: -0.644218<br>autograd gradient:        -0.644218<br>exact -sin(0.7):          -0.644218</pre><p>Whatever the true angle, the server sees all eight possible values about 12.5% of the time each. That’s the whole point: the distribution carries no information about the angle.</p><p>The second half shows why the parameter-shift rule matters here. Running the same circuit at two shifted angles gives the exact gradient, matching both automatic differentiation and the textbook answer. A blind protocol can only run circuits, so a gradient you get from circuit runs alone fits it perfectly.</p><h3>The classifier</h3><p>The authors design a variational classifier that fits the brickwork state neatly. Each layer has z and x rotations on every qubit, followed by CNOT gates, and the layer repeats. Every one of those gates can be carried out by measuring the brickwork state along specific directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3qOxMzM7TOpHB6ZfKfMwA.png" /></figure><p>All simulations were done with Yao.jl, a Julia quantum simulator, using Adam and cross-entropy loss. For the single-client case, they used 8 qubits for MNIST and 6 for WDBC, a circuit depth of 30, learning rate 0.001 and 300 iterations. Accuracy saturated around 98% and 94%.</p><p>They also simulated imperfect qubit preparation and measurement. The supplementary results suggest training stays robust up to an input noise level of 0.02.</p><h3>From one client to many</h3><p>Blindness protects Alice from Bob. But in federated learning there’s a second problem: the shared model itself. Every client’s gradient updates the public model, and as Part 2 showed, gradients can leak the data behind them.</p><p>So the multi-client protocol adds differential privacy. In each iteration:</p><ol><li>One client is chosen at random and samples a mini-batch of its data.</li><li>It computes the gradient blindly on Bob’s server.</li><li>It clips each gradient element to a bound R.</li><li>It adds Gaussian noise with standard deviation 2R divided by mu, where a smaller mu means more noise.</li><li>The noisy gradient updates the shared model with Adam.</li></ol><p>Note that this isn’t FedAvg. There’s no averaging round; clients take turns updating one shared model. The paper’s text calls the noise Laplace in a couple of places, but the algorithm and the description both use a normal distribution, so I’d treat it as Gaussian.</p><p>The multi-party experiments used 10 clients with 200 samples each for MNIST and 4 clients with 100 each for WDBC, a gradient bound of 0.01, and batch size 50.</p><h3>Does it actually stop the attack?</h3><p>The authors ran their own gradient attack against the quantum classifier, inspired by the DLG attack from Part 2. Without differential privacy, the recovered “1” and “9” digits had very high fidelity to the originals. With noise added, the recoveries looked random.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMsZZiXH4A3Q1VgBOfuD5w.png" /></figure><p>Two honest caveats from the paper itself. First, more noise (smaller mu) lowers accuracy and slows convergence. Second, with a batch size of 1, the attacker can still guess the label, because the loss curve for the correct label tends to reach the lowest value. Bigger batches with mixed labels help.</p><p>They also tested clients choosing different noise levels, from mu of 1 down to 0.55 across the 10 clients, and training stayed robust.</p><h3>Limitations as I see them</h3><ul><li>Alice still needs quantum hardware: she must prepare and send single qubits. That’s far less than a full quantum computer, but it isn’t nothing.</li><li>The experiments use Gaussian noise but never report a formal privacy budget (an epsilon). Without one, “differential privacy” here is more of a mechanism than a guarantee.</li><li>Everything is simulated, and the blind protocol’s communication overhead (many rounds of classical messages per measurement) isn’t measured.</li><li>One client updates per iteration, which is closer to sequential delegated training than to the federated averaging used elsewhere in this series.</li></ul><h3>My take</h3><p>This is my favorite threat model in the series. It takes seriously the most likely future: quantum computers in a few data centers, rented by people who don’t fully trust the owners.</p><p>Blindness solves the server problem cleanly, with a security proof that doesn’t depend on anyone’s computing power. Differential privacy is needed for the other clients, and here it’s under-specified. Part 6 shows what a fully accounted version looks like.</p><p>Previous: Part 4, When the Data Itself Is Quantum (link to be added on publishing).</p><p>Next: Part 6, Differential Privacy for Quantum Classifiers (link to be added on publishing).</p><h3>Sources</h3><ul><li>Weikang Li, Sirui Lu and Dong-Ling Deng, Quantum federated learning through blind quantum computing, 2021. <a href="https://arxiv.org/abs/2103.08403">arXiv:2103.08403</a></li><li>Anne Broadbent, Joseph Fitzsimons and Elham Kashefi, Universal blind quantum computation, 2009. <a href="https://arxiv.org/abs/0807.4154">arXiv:0807.4154</a></li><li>Ligeng Zhu, Zhijian Liu and Song Han, Deep Leakage from Gradients, 2019. <a href="https://arxiv.org/abs/1906.08935">arXiv:1906.08935</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf411af90b8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When the Data Itself Is Quantum]]></title>
            <link>https://medium.com/@imansharei24/when-the-data-itself-is-quantum-b241cc3acc91?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b241cc3acc91</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[quantum-machine-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 19:09:33 GMT</pubDate>
            <atom:updated>2026-11-12T19:09:33.785Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chehimi and Saad’s federated QCNN, trained on quantum states that never leave their clients</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bst6zxHuNxkdI2m3fEjOyQ.png" /></figure><p>Part 4 of the series Private by Design: Quantum Federated Learning.</p><p>TL;DR</p><ul><li>Chehimi and Saad built what they call the first purely quantum federated learning framework: clients hold quantum data and train a quantum convolutional neural network (QCNN).</li><li>They used 8-qubit cluster states, 30 clients with 160 samples each, a 64-parameter QCNN, and plain federated averaging.</li><li>Federated training beat a single centralized client, and IID vs non-IID data made little difference (99.25% vs 98.625% test accuracy).</li><li>I include a short PennyLane check showing what an excitation does to a cluster state.</li><li>It’s a convincing proof of concept on a toy quantum dataset. It doesn’t address privacy attacks at all, which I’ll come back to.</li></ul><h3>Why quantum data changes the argument</h3><p>In Part 3, the clients held ordinary photos. The quantum circuit was a small add-on at the end of a big classical network. You could reasonably ask why the quantum part was there.</p><p>Mahdi Chehimi and Walid Saad flip the setup. Their clients don’t have photos. They have quantum states, the kind a quantum sensor or a quantum experiment would produce.</p><p>That matters for two reasons. You can’t copy an unknown quantum state (the no-cloning theorem), and sending one over a network is fragile. So “send everything to a central server” isn’t just a privacy problem here; it’s a physics problem. Training where the data lives becomes the obvious design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvCYyNurX20IePOnZu6n7Q.png" /></figure><h3>Hybrid QFL vs purely quantum QFL</h3><p>It helps to put the two flavors side by side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGwS7o3Lp-D_ZMXGDV4_kw.png" /></figure><p>In both cases, what travels to the server is classical: a list of circuit parameters. The difference is what each client computes on. Here, the whole model is quantum, and so is the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOIcDh5pFFyyFu0nvODInw.png" /></figure><h3>The data: excited or not?</h3><p>Each sample is an 8-qubit cluster state, a standard entangled state used in quantum computing and sensing. Some samples get an “excitation”, a rotation around the x-axis applied to the qubits. The task is binary: was the excitation large enough to count, or not?</p><p>The rotation angles were drawn uniformly between minus pi and pi. Each of the 30 clients got 160 labeled samples, stored as serialized circuits.</p><p>One small thing I noticed: the paper describes the labels in two places, and the 0 and 1 assignment for “excited” is swapped between them. It doesn’t affect the results, but it’s worth knowing if you try to reproduce it.</p><h3>Try it: what an “excitation” does to a cluster state</h3><p>I wanted to see why this task is learnable at all, so I wrote a tiny PennyLane check. A cluster state has “stabilizers”: measurements that return exactly +1 on the perfect state. Rotating one qubit breaks that.</p><pre># Build an 8-qubit cluster state, add an &quot;excitation&quot;, and watch a stabilizer react<br>import pennylane as qml<br>from pennylane import numpy as np<br><br>n = 8<br>dev = qml.device(&quot;default.qubit&quot;, wires=n)<br><br>@qml.qnode(dev)<br>def cluster(angle):<br>    for i in range(n):<br>        qml.Hadamard(wires=i)<br>    for i in range(n):                      # ring of CZ gates -&gt; cluster state<br>        qml.CZ(wires=[i, (i + 1) % n])<br>    qml.RX(angle, wires=0)                  # excitation on qubit 0<br>    # stabilizer of qubit 1: Z0 X1 Z2 equals +1 on a perfect cluster state<br>    return qml.expval(qml.PauliZ(0) @ qml.PauliX(1) @ qml.PauliZ(2))<br><br>for angle in [0.0, 0.3, np.pi / 2, np.pi]:<br>    print(f&quot;excitation {angle:5.2f} rad -&gt; stabilizer &lt;Z0 X1 Z2&gt; = {float(cluster(angle)):+.3f}&quot;)</pre><p>Real output from my run:</p><pre>excitation  0.00 rad -&gt; stabilizer &lt;Z0 X1 Z2&gt; = +1.000<br>excitation  0.30 rad -&gt; stabilizer &lt;Z0 X1 Z2&gt; = +0.955<br>excitation  1.57 rad -&gt; stabilizer &lt;Z0 X1 Z2&gt; = +0.000<br>excitation  3.14 rad -&gt; stabilizer &lt;Z0 X1 Z2&gt; = -1.000</pre><p>The stabilizer drops from +1 smoothly, following the cosine of the rotation angle (cos 0.3 is 0.955). A small excitation barely moves it, a large one flips it. That’s the signal the QCNN has to learn to pick up, and it’s why a threshold between “excited” and “not excited” is a natural binary task.</p><h3>The model: a quantum CNN</h3><p>A QCNN borrows the structure of a classical convolutional network. Convolution layers apply the same small gate pattern across neighboring qubits. Pooling layers measure some qubits and use the outcomes to rotate their neighbors, which shrinks the active system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dYYZ685MZ9J7Fe82nLtHQ.png" /></figure><p>The authors settled on three convolution and pooling pairs, followed by a quantum fully connected layer and a measurement, with 64 trainable parameters in total. The qubit counts per stage in my diagram are a schematic; the paper fixes the number of stages and parameters, not a drawing.</p><p>Training minimizes mean squared error between the prediction and the 0 or 1 label.</p><h3>The federated setup</h3><p>The implementation uses TensorFlow Quantum for the circuits, TensorFlow Federated for the federated loop, and Cirq underneath. Everything ran on Google Colab CPUs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZfrzxuKrfqRUSL_ZicBQw.png" /></figure><p>All clients participate every round, which is a simplification the authors acknowledge. A few clients are held out for testing. The server just averages (its “optimizer” is SGD with learning rate 1, which is the same as plain averaging), and the clients run their own local optimizer.</p><h3>What they found</h3><p>Here are the main results in one place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42tXL47CodRZcIRA7EwzEg.png" /></figure><p>More clients helped. With 6 clients (4 training, 2 testing), accuracy was noticeably worse. As they scaled toward 30 clients (25 training, 5 testing), test accuracy rose without overfitting.</p><p>At 30 clients, the federated model beat the centralized single-client baseline. Their explanation is that each client benefits from the others’ data. That’s a fair point, but note the centralized baseline is one client with its own 160 samples, not all the data pooled together. I’d call this “collaboration beats isolation” rather than “federated beats centralized” in the usual sense.</p><p>The optimizer story was the most practical part for me:</p><ul><li>SGD at learning rate 0.02 was the only one that started high from the first epoch, and it settled around 96.5%.</li><li>Adam at 0.02 converged higher after a few epochs.</li><li>Adam at 0.2 couldn’t learn at all.</li><li>Adam at 0.002 gave smoother curves but lower accuracy.</li><li>RMSprop at 0.002 was slow and ended lower.</li></ul><h3>IID vs non-IID quantum data</h3><p>To make the data non-IID, the authors generated half the clients’ rotation angles from a truncated normal distribution instead of a uniform one. So half the clients see a different distribution of states.</p><p>The result: 99.25% test accuracy on IID data and 98.625% on non-IID. That’s a small drop. They also report test MSE of 5.66 and 6.57, without stating a scale for those numbers, so I’d only read them relative to each other.</p><p>Repeated runs with different seeds stayed within 5% error, according to their error-bar figure.</p><p>My read is that this kind of non-IID is mild. In my own toy run in Part 3, a label-skewed split hurt much more than an even one. Shifting the distribution of a rotation angle isn’t the same as giving each client only one class.</p><h3>What about privacy?</h3><p>Here’s the gap. The paper’s privacy argument, like Chen and Yoo’s, is that the data stays local. Nothing protects the shared parameters.</p><p>With only 64 parameters, the attacks from Part 2 might struggle to rebuild much. But “might struggle” isn’t a guarantee, and nobody in this paper tests it. The authors themselves suggest quantum cryptography to encrypt the shared parameters as future work.</p><h3>Limitations as I see them</h3><ul><li>The dataset is synthetic and simple. Cluster-state excitation detection is a standard tutorial task, and near-perfect accuracy on it doesn’t tell us much about harder quantum data.</li><li>Everything is simulated. The authors note that today’s NISQ hardware and its noise make real deployment hard.</li><li>Full client participation and fixed client data size remove two of the messiest parts of real federated learning.</li><li>No privacy analysis beyond data locality.</li></ul><h3>My take</h3><p>I think this paper makes the strongest case for QFL in the whole series, and it isn’t because of the accuracy numbers. It’s the argument: if your data is quantum, you can’t just copy it to a server, so federated training isn’t an optional privacy upgrade. It’s the default.</p><p>That’s a much more convincing reason for QFL to exist than “we bolted a 4-qubit circuit onto VGG16”. The open question is whether real quantum sensor networks will produce data that’s this cooperative.</p><p>Previous: Part 3, Federated Quantum ML, Hands On (link to be added on publishing).</p><p>Next: Part 5, Blind Quantum Computing Meets Federated Learning (link to be added on publishing).</p><h3>Sources</h3><ul><li>Mahdi Chehimi and Walid Saad, Quantum Federated Learning with Quantum Data, 2021. <a href="https://arxiv.org/abs/2106.00005">arXiv:2106.00005</a></li><li>Samuel Yen-Chi Chen and Shinjae Yoo, Federated Quantum Machine Learning, 2021. <a href="https://arxiv.org/abs/2103.12010">arXiv:2103.12010</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b241cc3acc91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Federated Quantum ML, Hands On]]></title>
            <link>https://medium.com/@imansharei24/federated-quantum-ml-hands-on-fa41585939df?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa41585939df</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[penny-lane]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quantum-machine-learning]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 12:46:39 GMT</pubDate>
            <atom:updated>2026-11-10T12:46:39.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chen and Yoo’s hybrid quantum classifier, plus a federated VQC you can run in PennyLane</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXaxhKdYviSly6Py5iqDJQ.png" /></figure><p>Part 3 of the series Private by Design: Quantum Federated Learning.</p><p>TL;DR</p><ul><li>Chen and Yoo (2021) trained a hybrid model, a pre-trained VGG16 feeding a 4-qubit variational circuit, with federated averaging across 100 simulated clients.</li><li>Federated accuracy landed within a fraction of a percent of centralized training on two image tasks.</li><li>I wrote a small PennyLane simulation of the same idea. Centralized and IID federated training ended close together, and a label-skewed split lagged behind.</li><li>The paper’s privacy story is “data stays local”. As Part 2 showed, that’s not enough on its own.</li></ul><h3>Why this paper is the right starting point</h3><p>Federated Quantum Machine Learning by Samuel Yen-Chi Chen and Shinjae Yoo is one of the first papers to run the full federated loop with a quantum model inside. Most later QFL papers cite it, and Parts 6 and 8 of this series come from the same group.</p><p>It’s also refreshingly practical. The authors don’t pretend a 4-qubit circuit can process raw photos. They put a pre-trained classical network in front of it and let the quantum part do the final classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsVoLFMS1uQuFpTtZp68gw.png" /></figure><h3>The model</h3><p>The input image goes through VGG16, a well-known classical network pre-trained on ImageNet, which turns it into a feature vector. VGG16’s original classifier is replaced by a trainable head of three linear layers (25,088 to 4,096 to 4,096 to 4) with ReLU and dropout, which compresses everything into 4 numbers, one per qubit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Q1Oe0o23WEjOnKdy9qiQw.png" /></figure><p>Each number is loaded into its qubit with two rotations. The first angle is the arctangent of the value, the second is the arctangent of its square. Squashing through arctangent keeps the angles in a sensible range whatever the scale of the input.</p><p>Then come the trainable parts: a chain of CNOT gates to entangle the qubits, followed by a general single-qubit rotation (three angles) on each qubit. That block repeats twice, which gives 24 trainable circuit parameters. Two qubits are measured to produce the two class scores.</p><h3>The federated setup</h3><p>For the cats versus dogs task, the authors used 23,000 training images and 2,000 test images. They split the training set evenly across 100 clients, 230 images each.</p><p>Each round, 5 clients were picked. Each one trained locally for 1, 2 or 4 epochs with batch size 32, then the server averaged their parameters. They ran 100 rounds. A second task, planes versus cars from CIFAR-10, used 10,000 training and 2,000 test images.</p><p>The simulation stack was PyTorch for the classical side, PennyLane for the circuit, and Qulacs as a fast simulator backend.</p><h3>The results</h3><p>Here are the reported test accuracies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BdKGclGgPZ2jAd2hCv_0w.png" /></figure><p>On cats versus dogs, every federated setting landed between 98.6% and 98.7%, against 98.75% centralized. On planes versus cars, the federated runs ranged from 93.4% to 94.05%, around the centralized 93.65%. One federated setting actually beat centralized, which I’d read as noise rather than a real advantage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Tp9Uk7nLWAqbfRRqsy3MA.png" /></figure><p>More local epochs didn’t buy much. That’s consistent with what I’d expect when the heavy lifting is done by a pre-trained feature extractor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqclOtDekCY6kuVYBUXhng.png" /></figure><h3>The efficiency argument</h3><p>The authors also point out that each round touches far fewer samples than a centralized epoch. With 5 clients of 230 images, one federated round processes 1,150 images. One centralized epoch processes 23,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QVH-XkVFhkuCmqilDWVAA.png" /></figure><p>I’d add a caveat. That’s per round, and federated training needs many rounds, so the total isn’t automatically smaller. Also, when describing the CIFAR setting, the paper gives a figure of 100 x 5 x 1 = 500 that I couldn’t reconcile with its own setup. I’d treat the exact accounting there with care.</p><h3>My PennyLane simulation</h3><p>I wanted to feel the federated loop myself, so I wrote a small version. No VGG16 and no images; just the quantum part on a toy problem, so it runs on a laptop in under three minutes.</p><p>What it does:</p><ul><li>Generates a 4-dimensional dataset with two classes: points near a small shell and points near a larger shell.</li><li>Uses the same encoding style as the paper (arctangent of x and of x squared) and a 2-layer circuit of CNOTs plus general rotations: 24 parameters, two measured qubits.</li><li>Trains three ways for 15 rounds: centralized; FedAvg over 5 clients with an even (IID) split; and FedAvg where the data is sorted by label before splitting, so most clients see only one class.</li></ul><p>Here’s the full script. It runs as is with PennyLane 0.45 (pip install pennylane).</p><pre># Federated VQC on a toy dataset: centralized vs FedAvg (IID) vs FedAvg (non-IID)<br>import json<br>import pennylane as qml<br>from pennylane import numpy as np<br><br>N_QUBITS, N_LAYERS = 4, 2<br>dev = qml.device(&quot;default.qubit&quot;, wires=N_QUBITS)<br><br>@qml.qnode(dev)<br>def circuit(weights, x):<br>    for i in range(N_QUBITS):                  # Chen &amp; Yoo style encoding<br>        qml.RY(np.arctan(x[i]), wires=i)<br>        qml.RZ(np.arctan(x[i] ** 2), wires=i)<br>    for layer in weights:                      # CNOT ring + general rotation<br>        for i in range(N_QUBITS):<br>            qml.CNOT(wires=[i, (i + 1) % N_QUBITS])<br>        for i in range(N_QUBITS):<br>            qml.Rot(*layer[i], wires=i)<br>    return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))]<br><br>def predict_logits(w, X):<br>    return np.stack([np.stack(circuit(w, x)) for x in X])<br><br>def loss(w, X, y):                             # softmax cross-entropy on 2 readouts<br>    z = 3.0 * predict_logits(w, X)<br>    z = z - np.max(z, axis=1, keepdims=True)<br>    logp = z - np.log(np.sum(np.exp(z), axis=1, keepdims=True))<br>    return -np.mean(logp[np.arange(len(y)), y])<br><br>def accuracy(w, X, y):<br>    return float(np.mean(np.argmax(predict_logits(w, X), axis=1) == y))<br><br>def make_data(n, rng):                         # two noisy concentric shells in 4D<br>    y = rng.integers(0, 2, n)<br>    d = rng.normal(size=(n, 4)); d /= np.linalg.norm(d, axis=1, keepdims=True)<br>    r = np.where(y == 0, 0.6, 1.6) + 0.25 * rng.normal(size=n)<br>    return np.array(d * r[:, None], requires_grad=False), y<br><br>def local_train(w, X, y, epochs=1, batch=10, lr=0.1, seed=0):<br>    opt, rng = qml.AdamOptimizer(lr), np.random.default_rng(seed)<br>    w = np.array(w, requires_grad=True)<br>    for _ in range(epochs):<br>        idx = rng.permutation(len(y))<br>        for s in range(0, len(y), batch):<br>            b = idx[s:s + batch]<br>            w = opt.step(lambda v: loss(v, X[b], y[b]), w)<br>    return w<br><br>rng = np.random.default_rng(42)<br>Xtr, ytr = make_data(200, rng); Xte, yte = make_data(100, rng)<br>w0 = 0.1 * np.random.default_rng(7).normal(size=(N_LAYERS, N_QUBITS, 3))<br><br>def split(non_iid, k=5):<br>    order = np.argsort(ytr, kind=&quot;stable&quot;) if non_iid else np.arange(len(ytr))<br>    return [order[i::k] if not non_iid else order[i * 40:(i + 1) * 40] for i in range(k)]<br><br>ROUNDS, results = 15, {}<br>for name in [&quot;centralized&quot;, &quot;fedavg_iid&quot;, &quot;fedavg_noniid&quot;]:<br>    w, curve = w0.copy(), []<br>    for r in range(ROUNDS):<br>        if name == &quot;centralized&quot;:<br>            w = local_train(w, Xtr, ytr, seed=r)<br>        else:<br>            parts = split(non_iid=(name == &quot;fedavg_noniid&quot;))<br>            locals_ = [local_train(w, Xtr[p], ytr[p], seed=100 * r + c) for c, p in enumerate(parts)]<br>            w = sum(locals_) / len(locals_)    # FedAvg: equal-size clients, plain mean<br>        curve.append(accuracy(w, Xte, yte))<br>        print(f&quot;{name:14s} round {r + 1}: test acc = {curve[-1]:.2f}&quot;)<br>    results[name] = curve<br>json.dump(results, open(&quot;results.json&quot;, &quot;w&quot;))</pre><p>And here is the exact output from my run (seeds are fixed, so you should see the same numbers):</p><pre>centralized    round 1: test acc = 0.63<br>centralized    round 2: test acc = 0.74<br>centralized    round 3: test acc = 0.81<br>centralized    round 4: test acc = 0.80<br>centralized    round 5: test acc = 0.71<br>centralized    round 6: test acc = 0.48<br>centralized    round 7: test acc = 0.83<br>centralized    round 8: test acc = 0.84<br>centralized    round 9: test acc = 0.83<br>centralized    round 10: test acc = 0.82<br>centralized    round 11: test acc = 0.79<br>centralized    round 12: test acc = 0.88<br>centralized    round 13: test acc = 0.79<br>centralized    round 14: test acc = 0.85<br>centralized    round 15: test acc = 0.83<br>fedavg_iid     round 1: test acc = 0.61<br>fedavg_iid     round 2: test acc = 0.66<br>fedavg_iid     round 3: test acc = 0.65<br>fedavg_iid     round 4: test acc = 0.64<br>fedavg_iid     round 5: test acc = 0.64<br>fedavg_iid     round 6: test acc = 0.67<br>fedavg_iid     round 7: test acc = 0.66<br>fedavg_iid     round 8: test acc = 0.71<br>fedavg_iid     round 9: test acc = 0.69<br>fedavg_iid     round 10: test acc = 0.61<br>fedavg_iid     round 11: test acc = 0.79<br>fedavg_iid     round 12: test acc = 0.68<br>fedavg_iid     round 13: test acc = 0.82<br>fedavg_iid     round 14: test acc = 0.80<br>fedavg_iid     round 15: test acc = 0.81<br>fedavg_noniid  round 1: test acc = 0.61<br>fedavg_noniid  round 2: test acc = 0.62<br>fedavg_noniid  round 3: test acc = 0.63<br>fedavg_noniid  round 4: test acc = 0.63<br>fedavg_noniid  round 5: test acc = 0.63<br>fedavg_noniid  round 6: test acc = 0.66<br>fedavg_noniid  round 7: test acc = 0.68<br>fedavg_noniid  round 8: test acc = 0.68<br>fedavg_noniid  round 9: test acc = 0.66<br>fedavg_noniid  round 10: test acc = 0.68<br>fedavg_noniid  round 11: test acc = 0.68<br>fedavg_noniid  round 12: test acc = 0.68<br>fedavg_noniid  round 13: test acc = 0.69<br>fedavg_noniid  round 14: test acc = 0.70<br>fedavg_noniid  round 15: test acc = 0.71</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5BOMyH90tMmgeE1dgGZ-Q.png" /></figure><h3>What I take from my run</h3><p>Centralized training climbed fastest but bounced around a lot, including one dip to 0.48 in round 6. That’s what Adam with a fairly high learning rate does on a tiny dataset.</p><p>IID FedAvg started slower, then caught up: 0.81 in round 15 against 0.83 centralized. Averaging five clients’ updates smoothed out some of the noise, at the cost of speed.</p><p>The label-skewed split was the clear loser at 0.71. When each client mostly sees one class, their local updates pull in different directions and the average makes slow progress. Chen and Yoo split their data evenly, so their paper doesn’t test this case.</p><p>A fairness note on my comparison. “Round” means something different for each mode. Centralized does one pass over all 200 points; each federated client does one pass over its 40 points and then they’re averaged. I kept it simple on purpose. It’s a toy to build intuition, not a benchmark.</p><h3>Where the privacy story stands</h3><p>The paper’s privacy argument is that raw images never leave the clients. That’s true, and it’s useful. But Part 2 showed that shared gradients and weights can leak training data, and the classical VGG16 front end here is exactly the kind of model those attacks were built for.</p><p>Note that the trainable classical head is large: its first layer alone maps 25,088 inputs to 4,096 outputs. Geiping and colleagues showed that the input to a fully connected layer like that can be recovered with simple algebra. Nobody I’ve read has measured this attack on this exact architecture, but I wouldn’t bet on it being safe.</p><h3>My take</h3><p>I like this paper because it’s honest about scale. Four qubits, a classical network doing most of the work, and a clear demonstration that federated averaging doesn’t break a hybrid model.</p><p>What it doesn’t show is a quantum advantage, and it doesn’t claim one. Its real contribution is proof that the plumbing works. Everything after it in this series is about making that plumbing private.</p><p>Previous: Part 2, How Gradients Leak Your Private Data (link to be added on publishing).</p><p>Next: Part 4, When the Data Itself Is Quantum (link to be added on publishing).</p><h3>Sources</h3><ul><li>Samuel Yen-Chi Chen and Shinjae Yoo, Federated Quantum Machine Learning, Entropy, 2021. <a href="https://arxiv.org/abs/2103.12010">arXiv:2103.12010</a></li><li>PennyLane documentation: <a href="https://pennylane.ai/">pennylane.ai</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa41585939df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Gradients Leak Your Private Data]]></title>
            <link>https://medium.com/@imansharei24/how-gradients-leak-your-private-data-b39e2060fc76?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b39e2060fc76</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 12:38:39 GMT</pubDate>
            <atom:updated>2026-11-10T12:38:39.181Z</atom:updated>
            <content:encoded><![CDATA[<h3>Federated learning keeps your data at home, but the updates it sends can still give it away</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPiNPu0MAdoxCmm-WcPyyg.png" /></figure><p>Part 2 of the series Private by Design: Quantum Federated Learning.</p><p>In Part 1, I described federated learning as a recipe club. Everyone cooks at home and mails in only their tweaks to the recipe. It sounds private.</p><p>Then, in 2019, a paper called Deep Leakage from Gradients showed that, for some models, those “tweaks” can be turned back into the original ingredients. Almost pixel for pixel.</p><p>This article explains how that works, without math. It’s the single most important idea for understanding why the rest of this series exists.</p><h3>What a gradient actually is</h3><p>When a model trains on an example, it asks one question: which way should I nudge each of my weights to make fewer mistakes on this? The answer is a long list of numbers called a gradient.</p><p>In federated learning, devices share gradients (or the weights they produce) instead of raw data. The assumption is that a list of nudges says little about the example that caused them.</p><p>The trouble is that the nudges are very specific. A photo of your face produces a different set of nudges than a photo of mine. If someone knows the model and sees the nudges, they can work backwards.</p><h3>The attack in four steps</h3><p>Ligeng Zhu, Zhijian Liu and Song Han called their method Deep Leakage from Gradients, or DLG. The idea is surprisingly simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upkUSir_8nEr35uUIOjmJg.png" /></figure><ol><li>A client computes a gradient on a private image and shares it.</li><li>The attacker, who has the same model, starts from a random noise image and a random guess for the label.</li><li>The attacker computes the gradient that this fake image would produce.</li><li>The attacker keeps adjusting the fake image and label until its gradient matches the real one.</li></ol><p>When the gradients match, the fake image usually looks like the real one. It’s like reverse-engineering a recipe by cooking until your tweaks match someone else’s tweaks exactly.</p><p>Zhu and colleagues describe two settings where this matters. One is a malicious server collecting updates. The other is decentralized training, where a curious neighbor sees your updates directly.</p><h3>How well does it work?</h3><p>Disturbingly well, at least under the paper’s conditions. The authors tested on four image datasets: handwritten digits, small color images, street-view house numbers and faces.</p><p>They measured how different the rebuilt image was from the original (lower is better for the attacker). DLG’s error stayed below 0.03 on every dataset. An earlier attack they compared against stayed above 0.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9DwbYnTzmbLNpGPPBT9Dg.png" /></figure><p>They also showed the same trick works on text. With a language model, most of the original sentence came back within about 30 steps of the attack.</p><h3>There are limits, and they matter</h3><p>I don’t want to oversell this. The original DLG worked under friendly conditions for the attacker.</p><p>It needed a model with smooth activation functions and freshly initialized weights. It worked on batches of up to 8 images and resolutions up to 64 by 64 pixels. Bigger batches made it slower, as the next chart shows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odBDFTkLdJBSSl23whhDGA.png" /></figure><p>Going from one image to eight multiplied the work by about ten. So, for a while, “use big batches” sounded like a defense.</p><h3>The follow-up that made it worse</h3><p>A year later, Jonas Geiping and colleagues asked a sharper question: how easy is it, really, to break privacy in federated learning?</p><p>They changed what the attacker tries to match. Instead of matching the exact size of the gradient, they matched its direction, and they nudged the</p><p>image to look natural (smooth, without random speckles).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5s8FMBnuGEN_0LKpnysogg.png" /></figure><p>PSNR is a score for image similarity; higher means a closer copy. On trained networks, which is the realistic case, the new attack did clearly better. It also worked on full-size ImageNet photos through a very deep network, which the original attack couldn’t handle.</p><p>Two findings stood out to me. Even with a batch of 100 images, several were still recognizable. And doing many local training steps before sharing, which people hoped would blur things, didn’t really help.</p><p>They also proved something simple and slightly alarming. For a common type of layer (a fully connected one), the input can be recovered with basic algebra, no optimization needed.</p><h3>What actually stops it?</h3><p>Zhu and colleagues tried several cheap defenses. Some worked, but they all came with a price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XMjnGu97CvtZ-M2zjjJLQ.png" /></figure><p>Small amounts of random noise did nothing. Enough noise to stop the attack dropped accuracy from 76.3% to about 45%. Pruning away more than about 20% of the smallest gradient values also defended against it.</p><p>Geiping and colleagues end with the line I think everyone should remember: provable differential privacy is the only real guarantee. Everything else is a hope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0YVIJ3xmM7-hoMRJb9SaQ.png" /></figure><h3>Why this matters for quantum models</h3><p>You might wonder why a quantum series needs a whole article on classical attacks. Here’s my reasoning.</p><p>Quantum federated learning still shares gradients or circuit angles. Nothing in the quantum part automatically hides them. If anything, the hybrid models in Part 3 have a big classical network in front of the quantum circuit, and that classical part is exactly where these attacks are well understood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKcHK_u7r6V9Tg5yvpahiQ.png" /></figure><p>So the question for QFL isn’t “is it private because it’s federated?” It’s “which extra protection does it add, and what does that cost?” That question drives Parts 5 to 8.</p><h3>My take</h3><p>I find DLG one of the most useful papers to read early, because it kills a comfortable myth fast. “We never share raw data” is a statement about plumbing, not about privacy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuJGtcWcrB2KWti-XgiNqA.png" /></figure><p>The good news is that the same researchers point to the fix. Add carefully measured noise, account for it properly, and accept a small accuracy hit. Quantum hardware, as we’ll see, already comes with noise built in.</p><p>Previous: Part 1, Quantum Federated Learning, Explained Simply (link to be added on publishing).</p><p>Next: Part 3, Federated Quantum ML, Hands On (link to be added on publishing).</p><h3>Sources</h3><ul><li>Ligeng Zhu, Zhijian Liu and Song Han, Deep Leakage from Gradients, NeurIPS 2019. <a href="https://arxiv.org/abs/1906.08935">arXiv:1906.08935</a></li><li>Jonas Geiping, Hartmut Bauermeister, Hannah Dröge and Michael Moeller, Inverting Gradients: How easy is it to break privacy in federated learning?, NeurIPS 2020. <a href="https://arxiv.org/abs/2003.14053">arXiv:2003.14053</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b39e2060fc76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Federated Learning, Explained Simply]]></title>
            <link>https://medium.com/@imansharei24/quantum-federated-learning-explained-simply-5fbae073f6a7?source=rss-790353a665d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fbae073f6a7</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Iman Sharei]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 17:18:26 GMT</pubDate>
            <atom:updated>2026-11-06T17:18:26.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>What happens when quantum models learn together without ever sharing their data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMCbKJCH_xWRC4Ex0DzydQ.png" /></figure><p>Part 1 of the series Private by Design: Quantum Federated Learning.</p><p>Two ideas keep showing up in my reading lists. One is federated learning, where devices train a shared model without handing over their data. The other is quantum machine learning, where parts of a model run on a quantum computer.</p><p>Quantum federated learning, or QFL, is what you get when you put them together. This article is the gentle version: no formulas, just the moving parts and why anyone would bother.</p><h3>First, a one-minute refresher on federated learning</h3><p>Normally, if you want to train a model on lots of people’s data, you collect all of it in one place. That’s convenient, and it’s also a privacy liability.</p><p>Federated learning flips the flow. The model travels to the data instead of the data traveling to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJzJGHN6qtRl1XIDHA0q4g.png" /></figure><p>Each device trains a copy of the model on what it has locally. It then sends back only the changes it made. A central server averages those changes into a better shared model and sends it out again. That averaging step has a name, FedAvg, and it shows up in nearly every paper in this series.</p><p>I like to think of it as a recipe club. Everyone cooks the same recipe in their own kitchen, writes down small tweaks, and mails only the tweaks to the club organizer. Nobody ever sees anyone else’s pantry.</p><h3>So what is a quantum model?</h3><p>A regular computer stores bits. A bit is a light switch: on or off, 1 or 0.</p><p>A quantum computer stores qubits. A qubit is closer to a dimmer you can rotate in more than one direction. While nobody is looking, it can sit in a blend of 0 and 1. When you measure it, you get a plain 0 or 1, with odds set by how the dimmer was turned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4206RULYri-aVJJqRw7FQ.png" /></figure><p>A quantum machine learning model is usually a short circuit of these rotations. The angles of the rotations are the model’s “weights”. Training means adjusting those angles until the measurements give useful answers, like “cat” or “dog”.</p><p>Researchers often call these circuits variational quantum circuits, or VQCs. You’ll see that acronym a lot in later parts.</p><h3>The hybrid loop most quantum models use today</h3><p>Here’s something that surprised me when I started reading. Today’s quantum models are almost never purely quantum.</p><p>They run in a loop. A classical computer prepares the data, the quantum chip runs the circuit, someone measures the result, and the classical computer decides how to nudge the angles. Then it repeats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJIHV6WTW1M99EY70ZYdOg.png" /></figure><p>John Preskill, the physicist who coined the term NISQ (Noisy Intermediate-Scale Quantum), describes exactly this kind of hybrid loop as a natural fit for current machines. The quantum chip does one specialized job, and the classical computer does the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pikFwT8Xf8dBLgojSX0WPg.png" /></figure><h3>Why today’s machines are “noisy”</h3><p>Preskill’s 2018 paper is still the best plain-language picture of where we are. Machines with 50 to a few hundred qubits are big enough that ordinary computers can’t simulate them by brute force. That’s exciting.</p><p>The catch is noise. Every operation has a small chance of going wrong, and the errors pile up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2LYLtLGziELRgjgbp-7Pw.png" /></figure><p>Preskill put two-qubit gate errors above 0.1%. With errors like that, circuits of roughly a thousand gates are about the practical limit. Fully error-corrected machines would need millions of physical qubits.</p><p>His summary line has stuck with me: NISQ “will not change the world by itself”. I think that’s a healthy attitude to bring to QFL papers too.</p><h3>Putting the two together</h3><p>Now combine the pieces. In QFL, each client trains a quantum (or hybrid) model locally. The clients send their updated circuit angles to a server. The server averages them and sends the new angles back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlQ6kSg1lgkb08LyS2Jz4w.png" /></figure><p>In 2021, Samuel Yen-Chi Chen and Shinjae Yoo published one of the first concrete demonstrations of this. Their clients combined a pre-trained classical image network with a small 4-qubit circuit and trained it with federated averaging.</p><p>The result was encouraging. On a cats versus dogs task, the federated version reached test accuracy of about 98.6 to 98.7%, against 98.75% for normal centralized training. In other words, splitting training across 100 simulated clients barely cost anything.</p><p>I’ll unpack that paper properly, with runnable code, in Part 3.</p><h3>Why would anyone want this?</h3><p>Here’s my honest take on the motivations, from strongest to weakest.</p><ol><li>The data might itself be quantum. If labs or sensors produce quantum states, you can’t just copy them to a central server, and sending them is hard. Learning where the data lives makes a lot of sense. Preskill also suggests quantum machine learning may shine most on quantum data, because loading classical data into qubits is expensive.</li><li>Quantum hardware is scarce and spread out. A federated setup lets several groups pool learning without pooling their raw data or their machines.</li><li>Privacy regulations still apply. Hospitals and banks face the same rules whether their model is classical or quantum.</li><li>Possible quantum advantages in model size. Some papers report quantum models matching classical ones with fewer parameters. I treat this as interesting but unproven at scale.</li></ol><p>A large 2024 survey by Qiao and colleagues in IEEE Communications Surveys and Tutorials maps out this whole research area, from architectures to security. I’ve only read its abstract, so I’m not going to quote its details. It’s a good sign, though, that the field is big enough to need a survey of that size.</p><h3>The part people skip: federated is not automatically private</h3><p>This is the bit I want you to remember. Keeping data on the device is a good start, but the updates that leave the device can still leak information.</p><p>Researchers have shown that, in the classical world, you can sometimes rebuild training images almost pixel for pixel from shared gradients. Nothing about swapping in a quantum circuit magically fixes that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZBGEUBasNaWKp0N8xnKeA.png" /></figure><p>That’s why the rest of this series spends so much time on privacy tools: differential privacy, blind quantum computing, and even using the hardware’s own noise as protection.</p><h3>What’s coming in this series</h3><p>Here’s the plan, from beginner to advanced.</p><ul><li>Part 2: how gradients leak private data, in plain language.</li><li>Part 3: Chen and Yoo’s hybrid QFL model, with a PennyLane simulation you can run.</li><li>Part 4: federated learning when the data itself is quantum.</li><li>Part 5: blind quantum computing, where the server can’t see what it’s computing.</li><li>Part 6: differential privacy for quantum classifiers, math included.</li><li>Part 7: turning quantum noise into a privacy feature.</li><li>Part 8: ring topologies, simulated quantum communication, and a wrap-up.</li></ul><h3>My take</h3><p>QFL today is mostly simulation. The clients are usually quantum simulators on a laptop, not real chips. That doesn’t make the work pointless; it means we’re designing the plumbing before the house is built.</p><p>What I find genuinely exciting is the privacy angle. Quantum hardware is noisy, distributed, and scarce, and those exact properties keep turning out to be useful for privacy-preserving learning. We’ll see that in detail by Part 7.</p><p>Next up, Part 2: How Gradients Leak Your Private Data (link to be added on publishing).</p><h3>Sources</h3><ul><li>Samuel Yen-Chi Chen and Shinjae Yoo, Federated Quantum Machine Learning, Entropy, 2021. <a href="https://arxiv.org/abs/2103.12010">arXiv:2103.12010</a></li><li>John Preskill, Quantum Computing in the NISQ era and beyond, Quantum, 2018. <a href="https://arxiv.org/abs/1801.00862">arXiv:1801.00862</a></li><li>Qiao et al., survey of quantum federated learning, IEEE Communications Surveys and Tutorials, vol. 27, no. 1, pp. 509 to 545. <a href="https://doi.org/10.1109/comst.2024.3399612">doi:10.1109/COMST.2024.3399612</a> (abstract only).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fbae073f6a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>