Update logbook: Reproduction: Adaptive Personalized Federated Learning via Multi-task Averaging of Kernel Mean Embeddings
Browse filesFiles changed (19)
- README.md+14-5
- bucket-icon.svgAdded
- index.html+82-17
- logbook.cssAdded+2142
- logbook.jsAdded
- logbook.jsonAdded+87
- pages/claim-1-theorem-4-4-finite-sample-kme-guarantee/page.mdAdded+22
- pages/claim-2-corollary-4-6-downstream-excess-risk-transfer/page.mdAdded+22
- pages/claim-3-example-4-5-automatic-adaptive-collaboration/page.mdAdded+22
- pages/claim-4-theorem-5-2-random-fourier-feature-tradeoff/page.mdAdded+302
- pages/claim-5-section-6-1-100-agent-synthetic-concept-shift/page.mdAdded+1310
- pages/claim-6-section-6-3-femnist-192-agent-benchmark/page.mdAdded+298
- pages/conclusion/page.mdAdded+19
- pages/executive-summary/page.mdAdded
- pages/index.mdAdded+16
- trackio-logo-light.pngAdded
- trackio-logo.pngAdded
- trackio-wordmark-dark.pngAdded
- workspace.jsonAdded+29
12345678910---title: Repro Adaptive Personalized Fl Multi Task Averaging Kernel Mean Embeddingemoji: ⚡colorFrom: greencolorTo: greensdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819---title: "Reproduction: Adaptive Personalized Federated Learning via Multi-task Averaging of Kernel Mean Embeddings"emoji: 🎯colorFrom: yellowcolorTo: redsdk: staticpinned: falsetags:- trackio- trackio-logbook- open-experiment- icml2026-repro- paper-ADHGbxsREr- arxiv:2603.02233---# Reproduction: Adaptive Personalized Federated Learning via Multi-task Averaging of Kernel Mean EmbeddingsAn open experiment logbook, published with [Trackio](https://github.com/gradio-app/trackio).
12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Reproduction: Adaptive Personalized Federated Learning via Multi-task Averaging of Kernel Mean Embeddings</title><link rel="stylesheet" href="./logbook.css" /></head><body><div id="app"><aside id="sidebar"><div id="book-head"><img id="book-wordmark" src="./trackio-wordmark-dark.png" alt="" /><div id="book-title" class="sr-only">Logbook</div></div><nav id="tree"></nav><div id="sidebar-foot" hidden><button id="connect-btn" type="button"><span class="ico">ⓘ</span> Collaborate with your agent</button></div></aside><main id="content"><nav id="view-tabs" aria-label="Logbook views"><a data-view="code" href="#/view/code/index"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m18 16 4-4-4-4" /><path d="m6 8-4 4 4 4" /><path d="m14.5 4-5 16" /></svg><span>Logbook</span></a><a data-view="trace" href="#/view/trace"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M8 5h13" /><path d="M13 12h8" /><path d="M13 19h8" /><path d="M3 10a2 2 0 0 0 2 2h3" /><path d="M3 5v12a2 2 0 0 0 2 2h3" /></svg><span>Traces</span></a><a data-view="workspace" href="#/view/workspace"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" /></svg><span>Workspace</span></a></nav><header id="logbook-header"><h1 id="logbook-title"></h1><div id="logbook-cli"></div></header><div id="page"></div></main></div><div id="modal" hidden><div class="modal-backdrop"></div><div class="modal-card" role="dialog" aria-modal="true"><div class="modal-head"><div class="modal-title"><img class="modal-logo" src="./trackio-logo.png" alt="" />Collaborate with your agent</div><div class="modal-actions"><button id="copy-agent" class="btn">Copy for agent</button><button id="modal-close" class="btn icon" aria-label="Close">×</button></div></div><div class="modal-body"><p class="modal-intro">Point your coding agent at this logbook. It reads a compact,token-efficient version — and if you've given it write access to thisSpace, it can add findings that sync back automatically.</p><ol id="connect-steps"></ol></div></div></div><script src="./logbook.js"></script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142:root { --bg: #ffffff; --paper: #ffffff; --panel: #ffffff; --ink: #1f2937; --muted: #6b7280; --line: #e5e7eb; --accent: #f97316; --accent-strong: #ea580c; --accent-soft: #fff7ed; --accent-line: rgba(249, 115, 22, 0.16); --grid-line: rgba(31, 41, 55, 0.02); --code-bg: #f3f4f6; --radius: 12px; --sidebar-width: 280px; --content-gutter: 40px; --serif: ui-serif, "Iowan Old Style", "Palatino Linotype", Georgia, serif; --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; --mono: "SFMono-Regular", "Cascadia Mono", "JetBrains Mono", Menlo, Consolas, ui-monospace, monospace;}
* { box-sizing: border-box;}
html,body { margin: 0; padding: 0;}
html { scroll-behavior: smooth; scrollbar-gutter: stable;}
body { background: var(--bg); color: var(--ink); font-family: var(--sans); font-size: 13px; line-height: 1.65; -webkit-font-smoothing: antialiased;}
#app { display: flex; min-height: 100vh;}
body[data-view="trace"] #sidebar-foot,body[data-view="workspace"] #sidebar-foot { display: none;}
/* ---- sidebar (composition-book cover) ---- */#sidebar { width: var(--sidebar-width); flex: 0 0 var(--sidebar-width); background: #17181c; color: #e7e7ea; position: sticky; top: 0; height: 100vh; overflow-y: auto; padding: 22px 16px; display: flex; flex-direction: column;}
#book-head { display: flex; align-items: center; gap: 10px; padding: 8px; margin-bottom: 12px; border-radius: 10px; cursor: pointer; transition: background 0.12s;}#book-head:hover { background: rgba(255, 255, 255, 0.05);}#book-wordmark { width: 154px; height: auto; object-fit: contain;}.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;}
#tree { flex: 1; padding-top: 8px;}
#tree .tree-label { padding: 6px 10px 8px; color: #777a83; font-size: 10px; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase;}
#tree a { display: block; padding: 6px 10px; border-radius: 8px; color: #c3c4cb; text-decoration: none; font-size: 14px; transition: background 0.12s, color 0.12s; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
#tree a:hover { background: rgba(255, 255, 255, 0.06); color: #ffffff;}
#tree a.active { background: rgba(249, 115, 22, 0.16); color: #fdba74; font-weight: 600;}
#tree a .tree-mark { color: #6b6d76;}
#tree a:hover .tree-mark,#tree a.active .tree-mark { color: inherit; opacity: 0.6;}
#tree .depth-1 { padding-left: 22px;}#tree .depth-2 { padding-left: 34px;}#tree .depth-3 { padding-left: 46px;}
/* ---- content ---- */#content { flex: 1; min-width: 0; padding: 24px clamp( var(--content-gutter), calc(100vw - 960px), calc(var(--sidebar-width) + var(--content-gutter)) ) 120px var(--content-gutter); background-color: var(--paper); background-image: linear-gradient(var(--grid-line) 1px, transparent 1px), linear-gradient(90deg, var(--grid-line) 1px, transparent 1px); background-size: 26px 26px; background-position: center top;}
#logbook-header { width: 100%; max-width: 1080px; margin: 0 auto 20px;}#logbook-title { font-family: var(--serif); font-size: 34px; line-height: 1.15; letter-spacing: -0.02em; margin: 0 0 10px; overflow-wrap: anywhere;}#logbook-cli { display: grid; gap: 7px;}
#page { width: 100%; min-width: 0; max-width: 1080px; margin: 0 auto;}
.page-section { scroll-margin-top: 40px; padding: 0 0 35px; margin: 0 0 32px;}
.page-section:last-child { margin-bottom: 0;}
.page-layout { display: block;}
.page-body { min-width: 0;}
.resource-anchor { display: block; height: 0; overflow: hidden;}
/* ---- pinned notes ---- */.pinned-notes { margin: 30px 0 32px;}.pinned-notes-list .cell { margin: 0;}.pinned-notes-list .cell-title { display: flex; align-items: center; gap: 7px;}.pin-ico { flex: 0 0 auto; width: 14px; height: 14px; fill: var(--accent); stroke: none;}.pinned-notes-list .cell + .cell { margin-top: 12px;}.book-intro.has-pinned-notes { border-bottom: none; padding-bottom: 22px; margin-bottom: 30px;}.book-intro.book-intro-tight { border-bottom: none; padding-bottom: 4px; margin-bottom: 20px;}
#page h1 { font-family: var(--serif); font-size: 34px; line-height: 1.15; letter-spacing: -0.02em; margin: 0 0 8px; overflow-wrap: anywhere;}
#page .page-section:not(.book-intro) h1 { font-size: 26px;}
#page h2 { font-family: var(--serif); font-size: 24px; margin: 36px 0 10px;}
#page h3 { font-size: 17px; font-weight: 700; margin: 26px 0 2px; letter-spacing: -0.01em;}
#page h3::before { content: ""; display: inline-block; width: 7px; height: 7px; border-radius: 2px; background: var(--accent); margin-right: 10px; vertical-align: middle; transform: translateY(-1px);}
#page p { margin: 10px 0;}
#page blockquote { margin: 14px 0; padding: 2px 16px; border-left: 3px solid #fdba74; color: var(--muted);}
#page hr { display: none;}
#page code { font-family: var(--mono); font-size: 0.86em; background: var(--code-bg); padding: 2px 6px; border-radius: 6px;}
#page pre { max-width: 100%; background: var(--code-bg); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px; overflow-x: auto;}#page pre code { background: none; padding: 0; font-size: 11.5px;}
/* ---- code blocks + collapsible accordion ---- */#page pre.hl { background: #17181c; border: none; color: #e7e7ea; font-size: 13px; line-height: 1.58;}#page pre.hl code { color: inherit; font-family: var(--mono);}.code-accordion { border: 1px solid rgba(249, 115, 22, 0.2); border-radius: 8px; overflow: hidden; margin: 12px 0; background: #17181c;}.code-accordion summary { list-style: none; cursor: pointer; display: flex; align-items: center; gap: 9px; padding: 9px 12px; font-family: var(--mono); font-size: 11.5px; font-weight: 700; color: #e7e7ea; background: #1e2027; user-select: none; overflow-wrap: anywhere;}.code-accordion summary::-webkit-details-marker { display: none;}.code-accordion summary::after { content: "▸"; margin-left: auto; color: var(--accent); transition: transform 0.12s; transform: rotate(180deg);}.code-accordion[open] summary::after { transform: rotate(90deg);}.code-accordion .code-ico { color: var(--accent); font-weight: 700;}.code-accordion pre.hl { margin: 0; border-radius: 0; border: none; border-top: 1px solid rgba(249, 115, 22, 0.16);}.tok-comment { color: #7a7d87; font-style: italic;}.tok-string { color: #a5d6a7;}.tok-keyword { color: #fdba74;}.tok-number { color: #7fd0e0;}
#page a { color: var(--accent);}
#page ul { padding-left: 20px;}
.ts { font-family: var(--mono); font-size: 12px; color: var(--muted); background: none; padding: 0;}
/* ---- notebook-style cells ---- */.cell { max-width: 100%; margin: 0 0 32px; background: none; border: none; border-radius: 0; box-shadow: none; overflow: visible;}.cell-head { display: flex; justify-content: space-between; gap: 16px; align-items: baseline; padding: 0 0 5px; background: none; border-bottom: none;}.cell-head.no-title { justify-content: flex-end; padding: 0 0 3px;}.cell-title { flex: 1; min-width: 0; font-size: 13px; font-weight: 650; color: var(--ink); line-height: 1.35; overflow-wrap: anywhere;}.cell-meta { flex: 0 0 auto; display: flex; align-items: center; gap: 10px; font-family: var(--sans); font-size: 13px; color: var(--muted);}.cell-open { flex: 0 0 auto; font-family: var(--mono); font-size: 12px; color: var(--accent); text-decoration: none;}.cell-open:hover { color: var(--accent-strong);}.cell-body { min-width: 0; padding: 0;}.cell.dashboard .cell-body { padding: 0;}#page .cell-body h1,#page .cell-body h2 { font-family: var(--sans); font-size: 17px; font-weight: 700; letter-spacing: -0.01em; line-height: 1.35; margin: 22px 0 6px;}#page .cell-body > :first-child { margin-top: 0;}#page .cell-body > :last-child { margin-bottom: 0;}.figure-fit { position: relative; overflow: hidden; min-height: 160px; border: 1px solid var(--line); border-radius: 8px; background: #fff;}.figure-fit[hidden] { display: none;}.figure-fit:fullscreen,.figure-fit:-webkit-full-screen { width: 100%; height: 100%; border: none; border-radius: 0;}.figure-frame { display: block; width: 100%; min-height: 160px; border: none; background: #fff;}.figure-frame[hidden],.figure-raw[hidden] { display: none;}.fig-switch { position: relative; display: inline-flex; flex: 0 0 auto; border: 1px solid var(--line); border-radius: 999px; background: var(--code-bg); padding: 2px;}.fig-switch button { position: relative; z-index: 1; flex: 1; min-width: 62px; border: none; background: none; font-family: var(--sans); font-size: 12px; font-weight: 600; color: var(--muted); padding: 3px 12px; border-radius: 999px; cursor: pointer; transition: color 0.15s;}.fig-switch button.active { color: var(--accent-strong);}.fig-switch-thumb { position: absolute; top: 2px; bottom: 2px; left: 2px; width: calc(50% - 2px); border-radius: 999px; background: var(--panel); border: 1px solid rgba(249, 115, 22, 0.35); box-shadow: 0 1px 4px rgba(31, 41, 55, 0.08); transition: transform 0.18s ease;}.fig-switch.raw .fig-switch-thumb { transform: translateX(100%);}#page .figure-raw pre { margin: 0; max-height: 420px; overflow: auto; font-family: var(--mono); font-size: 13px; line-height: 1.55; background: var(--code-bg); border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px;}/* ---- figure fullscreen ---- */.cell-fullscreen { position: relative; display: inline-flex; flex: 0 0 auto;}.cell-fullscreen-btn { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; padding: 0; border: 1px solid var(--line); border-radius: 999px; background: var(--code-bg); color: var(--muted); cursor: pointer; transition: color 0.15s, border-color 0.15s, background 0.15s;}.cell-fullscreen-btn:hover { color: var(--accent-strong); border-color: rgba(249, 115, 22, 0.35); background: var(--accent-soft);}.cell-fullscreen-btn svg { width: 14px; height: 14px;}/* ---- copyable snippets ---- */.snippet { position: relative;}.copy-snippet { position: absolute; top: 7px; right: 8px; width: 24px; height: 24px; border: none; border-radius: 6px; background: rgba(255, 255, 255, 0.08); color: #9a9da8; font-size: 12px; line-height: 1; cursor: pointer; opacity: 0; transition: opacity 0.12s, color 0.12s, background 0.12s;}.snippet:hover .copy-snippet,.jp-out:hover .copy-snippet,.figure-raw:hover .copy-snippet,.code-accordion summary:hover .copy-snippet { opacity: 1;}.copy-snippet:hover { color: #ffffff; background: rgba(255, 255, 255, 0.16);}.copy-snippet.copied { color: #52d08a; opacity: 1;}.code-accordion .code-name { user-select: text; cursor: text;}.jp-out,.figure-raw { position: relative;}.jp-out .copy-snippet,.figure-raw .copy-snippet { background: var(--code-bg); color: var(--muted); border: 1px solid var(--line);}.jp-out .copy-snippet:hover,.figure-raw .copy-snippet:hover { color: var(--accent-strong); background: var(--panel);}
/* ---- jupyter-style code cells ---- */.jp { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; margin: 0; background: var(--panel);}.jp-cmd { display: flex; align-items: baseline; gap: 9px; position: relative; padding: 10px 16px 10px 0; font-family: var(--mono); font-size: 12px; color: #8b8e98;}.jp-cmd-prompt { color: var(--accent); font-weight: 700;}#page .jp-cmd code { min-width: 0; color: #b6b9c2; font-family: var(--mono); font-size: 12px; background: none; padding: 0; border-radius: 0; overflow-wrap: anywhere;}.jp-cmd:hover .copy-snippet { opacity: 1;}.jp-in-body .jp-cmd + .code-accordion,.jp-in-body .jp-cmd + .snippet { border-top: 1px solid rgba(255, 255, 255, 0.09);}.jp-gutter { flex: 0 0 46px; padding: 13px 0 0 13px; font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.07em; text-transform: uppercase; font-weight: 600; user-select: none;}.jp-in { display: flex; background: #17181c;}.jp-in .jp-gutter { color: #6f727d;}.jp-in-body { flex: 1; min-width: 0;}#page .jp-in-body pre.hl { margin: 0; border: none; border-radius: 0; background: none; padding: 12px 16px 12px 0; overflow-y: auto; max-height: 26em;}.jp-in-body .code-accordion { margin: 0; border: none; border-top: 1px solid rgba(255, 255, 255, 0.09); border-radius: 0; background: none;}.jp-in-body .code-accordion summary { background: none; padding: 9px 16px 9px 0;}.jp-in-body .code-accordion pre.hl { border-top: 1px solid rgba(255, 255, 255, 0.09);}.jp-meta { padding: 5px 14px; font-family: var(--mono); font-size: 11.5px; color: var(--muted); background: #fbfbfc; border-top: 1px solid var(--line);}.jp-out { display: flex; border-top: 1px solid var(--line); background: var(--panel);}.jp-out .jp-gutter { color: var(--accent-strong);}.jp-out-body { flex: 1; min-width: 0;}#page .jp-out-pre { min-width: 0; margin: 0; border: none; border-radius: 0; background: none; color: var(--ink); font-family: var(--mono); font-size: 13px; line-height: 1.55; padding: 12px 16px 12px 0; white-space: pre; overflow-x: auto; overflow-y: auto; max-height: 26em;}.jp-artifacts { display: flex; flex-direction: column;}.jp-out-body .jp-out-pre + .jp-artifacts { border-top: 1px solid var(--line);}.out-artifact { display: flex; align-items: baseline; gap: 8px; padding: 9px 16px 9px 0; text-decoration: none; color: inherit;}.out-artifact + .out-artifact { border-top: 1px solid var(--line);}a.out-artifact:hover .out-artifact-name { color: var(--accent-strong);}.out-artifact-ico { flex: 0 0 auto; font-size: 13px;}.out-artifact-name { font-family: var(--mono); font-size: 12.5px; font-weight: 600; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}.out-artifact-meta { flex: 0 0 auto; margin-left: auto; padding-left: 12px; font-size: 12px; color: var(--muted); white-space: nowrap;}.out-artifact-state.open { color: var(--accent); font-weight: 600;}.trackio-embed { border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; background: var(--panel);}.trackio-cell-meta { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end;}
/* ---- unfurl cards ---- */.unfurl { display: block; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); margin: 12px 0; overflow: hidden; text-decoration: none; color: inherit; transition: border-color 0.14s, box-shadow 0.14s;}.unfurl:hover { border-color: #cfcbe6; box-shadow: 0 4px 18px rgba(30, 20, 80, 0.06);}
.unfurl-body { padding: 13px 16px; display: flex; gap: 12px; align-items: flex-start;}
.unfurl-ico { font-size: 20px; line-height: 1.3; flex: 0 0 auto;}
.unfurl-main { min-width: 0; flex: 1;}
.unfurl-kind { font-family: var(--mono); font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--accent); font-weight: 600;}
.unfurl-title { font-weight: 650; font-size: 15px; margin: 1px 0 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}
.unfurl-desc { color: var(--muted); font-size: 13.5px; line-height: 1.45;}
.unfurl-meta { margin-top: 6px; display: flex; flex-wrap: wrap; gap: 6px;}
.chip { font-size: 11.5px; background: var(--code-bg); border-radius: 999px; padding: 2px 9px; color: var(--muted); font-family: var(--mono);}
.unfurl-raw { font-family: var(--mono); font-size: 11px; color: var(--muted); border-top: 1px solid var(--line); padding: 7px 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}
.unfurl.embed { padding: 0; overflow: hidden;}.embed-head { display: flex; align-items: center; gap: 10px; padding: 10px 14px; border-bottom: 1px solid var(--line);}.embed-head .unfurl-kind { flex: 0 0 auto;}.embed-title { flex: 1; min-width: 0; font-weight: 650; font-size: 14px; color: var(--ink); text-decoration: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}.embed-title:hover { color: var(--accent);}.embed-open { flex: 0 0 auto; font-family: var(--mono); font-size: 12px; color: var(--accent); text-decoration: none;}.embed-frame { display: block; width: 100%; height: 560px; border: 0; background: var(--code-bg);}
.dashboard-shell { display: block;}.dashboard-shell .dashboard-frame { display: block; width: 100%; height: 900px; border: 0; background: var(--code-bg);}
.unfurl.image { padding: 0;}.unfurl.image img { display: block; width: 100%; height: auto; max-height: 460px; object-fit: contain; background: var(--code-bg);}
.artifact-chip { border: 1px solid var(--line); background: var(--panel); border-radius: var(--radius); padding: 10px 14px; margin: 8px 0; font-size: 14px;}.cell.dashboard .artifact-chip { margin: 14px 18px 18px;}.artifact-chip code { color: var(--accent);}
/* ---- task board ---- */.board-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); margin: 12px 0 20px; background: var(--panel);}table.board { border-collapse: collapse; width: 100%; font-size: 14px;}table.board th,table.board td { text-align: left; padding: 9px 14px; border-bottom: 1px solid var(--line); vertical-align: top;}table.board thead th { background: var(--accent-soft); font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; color: #9a4a12; font-weight: 600; border-bottom: 1px solid var(--line);}table.board tbody tr:last-child td { border-bottom: none;}table.board .col-check { text-align: center; width: 92px; white-space: nowrap;}table.board tr.section-row td { background: var(--accent-soft); text-align: center; font-weight: 700; font-size: 13px; color: var(--accent-strong); padding: 7px 14px; letter-spacing: 0.02em;}.box { display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; border: 1.5px solid #cfcbe0; border-radius: 5px; font-size: 12px; color: #fff; line-height: 1;}.box.on { background: var(--accent); border-color: var(--accent);}.who-chip { display: inline-block; padding: 3px 12px; border-radius: 999px; font-size: 12.5px; font-weight: 600; white-space: nowrap;}.who-chip.muted { background: var(--code-bg); color: var(--muted); font-weight: 500;}
/* ---- status badges + clickable rows ---- */table.board .col-status { width: 130px; white-space: nowrap;}.badge { display: inline-block; padding: 3px 11px; border-radius: 999px; font-size: 12px; font-weight: 600; letter-spacing: 0.01em;}.badge.gray { background: var(--code-bg); color: var(--muted);}.badge.amber { background: var(--accent-soft); color: #b45309;}.badge.green { background: #e6f7ee; color: #1a8a55;}.badge.red { background: #fde8ec; color: #c62a4b;}table.board tr.linked-row { cursor: pointer;}table.board tr.linked-row:hover td { background: var(--accent-soft);}table.board tr.linked-row a { color: var(--ink); font-weight: 600; text-decoration: none;}table.board tr.linked-row:hover a { color: var(--accent-strong);}
/* ---- agent read hint ---- */.agent-hint { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 0; font-size: 12.5px; color: var(--muted);}.agent-hint code { flex: 1 1 18rem; min-width: 0; background: var(--code-bg); padding: 2px 9px; border-radius: 6px; font-family: var(--mono); font-size: 12px; font-weight: 500; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}.agent-hint .copy { flex: 0 0 auto; background: none; color: var(--muted); border: 1px solid var(--line); border-radius: 6px; width: 22px; height: 22px; font-size: 11px; line-height: 1; cursor: pointer; transition: color 0.12s, border-color 0.12s;}.agent-hint .copy:hover { color: var(--accent-strong); border-color: var(--accent);}.agent-hint .copy.copied { color: #1a8a55; border-color: #1a8a55;}.agent-hint-note { margin-left: auto; font-size: 12px; color: var(--muted);}.hub-destination { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; color: var(--muted); font-size: 12.5px;}.hub-destination a { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; padding: 3px 9px; border: 1px solid var(--accent-line); border-radius: 999px; background: var(--accent-soft); color: var(--accent-strong); font-family: var(--mono); font-size: 12px; font-weight: 650; line-height: 1.5; text-decoration: none; overflow-wrap: anywhere; transition: border-color 0.12s, background 0.12s, color 0.12s;}.hub-destination a:hover { border-color: var(--accent); background: #ffedd5; color: #c2410c;}.hub-destination svg { width: 13px; height: 13px; flex: 0 0 auto; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round;}
.index-paper-link { margin: 14px 0 30px; font-size: 19px; line-height: 1.35; font-weight: 700;}.index-paper-link a { text-underline-offset: 4px; text-decoration-thickness: 2px;}.art-ico { width: 1em; height: 1em; object-fit: contain; vertical-align: -0.15em;}.art-file-ico { width: 15px; height: 15px; flex: 0 0 auto; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; vertical-align: -0.2em;}.out-artifact-ico .art-file-ico { color: var(--muted);}
/* ---- scroll-to-resource highlight ---- */.res-flash { animation: res-flash 1.5s ease; border-radius: 8px;}@keyframes res-flash { 0%, 25% { box-shadow: 0 0 0 3px var(--accent); } 100% { box-shadow: 0 0 0 3px rgba(249, 115, 22, 0); }}
/* ---- inline resource chips ---- */#page .res-chip { display: inline-flex; align-items: center; gap: 5px; max-width: 100%; padding: 0 9px 0 6px; margin: 0 1px; border: 1px solid var(--line); border-radius: 999px; background: var(--panel); font-family: var(--mono); font-size: 0.78em; font-weight: 600; color: var(--ink); text-decoration: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; line-height: 1.65; transform: translateY(-0.08em); transition: border-color 0.12s, background 0.12s, color 0.12s;}.res-chip-ico { font-size: 1.05em; line-height: 1;}#page .res-chip:hover { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-strong);}
/* ---- connect footer + modal ---- */#sidebar-foot { margin-top: auto; padding-top: 14px; border-top: 1px solid rgba(255, 255, 255, 0.1);}
#connect-btn { width: 100%; display: flex; align-items: center; gap: 8px; background: rgba(255, 255, 255, 0.05); color: #c3c4cb; border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 9px; padding: 9px 12px; font-size: 13.5px; font-family: var(--sans); cursor: pointer; transition: background 0.12s, color 0.12s, border-color 0.12s;}#connect-btn:hover { background: rgba(249, 115, 22, 0.14); border-color: rgba(249, 115, 22, 0.4); color: #fdba74;}#connect-btn .ico { font-size: 15px;}
#modal[hidden] { display: none;}#modal { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; padding: 24px;}.modal-backdrop { position: absolute; inset: 0; background: rgba(20, 18, 30, 0.5); backdrop-filter: blur(2px);}.modal-card { position: relative; background: var(--panel); border-radius: 16px; width: 100%; max-width: 620px; max-height: 85vh; overflow-y: auto; box-shadow: 0 24px 70px rgba(20, 15, 50, 0.28);}.modal-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 18px 22px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel);}.modal-title { display: flex; align-items: center; gap: 10px; font-family: var(--serif); font-size: 21px; letter-spacing: -0.01em;}.modal-logo { width: 26px; height: 26px; object-fit: contain;}.modal-actions { display: flex; align-items: center; gap: 8px;}.btn { font-family: var(--sans); font-size: 13.5px; font-weight: 600; border: 1px solid var(--line); background: var(--panel); color: var(--ink); border-radius: 9px; padding: 8px 13px; cursor: pointer; transition: background 0.12s, border-color 0.12s, color 0.12s;}.btn:hover { border-color: var(--accent); color: var(--accent-strong);}.btn.copied { border-color: #1a8a55; color: #1a8a55;}.btn.icon { font-size: 18px; line-height: 1; padding: 6px 11px; font-weight: 400;}.modal-body { padding: 20px 22px 26px;}.modal-intro { margin: 0 0 20px; color: var(--muted); line-height: 1.55;}#connect-steps { list-style: none; margin: 0; padding: 0;}#connect-steps li { margin-bottom: 18px;}.step-title { font-weight: 600; font-size: 14.5px; margin-bottom: 8px;}.codeblock { display: flex; align-items: center; gap: 8px; background: #17181c; border-radius: 10px; padding: 11px 12px 11px 15px;}.codeblock code { flex: 1; min-width: 0; overflow-x: auto; white-space: nowrap; font-family: var(--mono); font-size: 13px; color: #f0efff; background: none; padding: 0;}.codeblock .copy { flex: 0 0 auto; background: rgba(255, 255, 255, 0.08); color: #c3c4cb; border: 1px solid rgba(255, 255, 255, 0.14); border-radius: 7px; width: 30px; height: 30px; font-size: 14px; cursor: pointer; transition: background 0.12s, color 0.12s;}.codeblock .copy:hover { background: rgba(249, 115, 22, 0.2); color: #fdba74;}.codeblock .copy.copied { color: #52d08a;}
/* ---- top-level logbook views ---- */#view-tabs { position: sticky; top: 0; z-index: 30; width: 100%; max-width: 1080px; margin: 0 auto 24px; padding-top: 10px; display: flex; align-items: center; justify-content: flex-start; gap: 26px; border-bottom: 1px solid var(--line); background: var(--paper);}#view-tabs a { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; margin-bottom: -1px; color: var(--muted); border-bottom: 2px solid transparent; text-decoration: none; font-size: 13.5px; font-weight: 600; transition: color 0.12s, border-color 0.12s;}#view-tabs a:hover { color: var(--ink);}#view-tabs a.active { color: var(--accent-strong); border-bottom-color: var(--accent);}#view-tabs svg { width: 18px; height: 18px; flex: 0 0 auto; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;}.workspace-file svg,.workspace-folder summary svg,.workspace-download svg { width: 17px; height: 17px; flex: 0 0 auto; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round;}
#page.trace-page,#page.workspace-page { max-width: 1080px;}.view-loading { padding: 72px 0; color: var(--muted); text-align: center;}.view-empty { margin: 48px 0; padding: 44px 28px; border: 1px dashed #d8dbe1; border-radius: var(--radius); background: rgba(255, 255, 255, 0.72); text-align: center;}.view-empty h2 { margin: 0 0 7px; font-size: 18px;}.view-empty p { max-width: 560px; margin: 0 auto; color: var(--muted);}.view-empty code { display: inline-block; margin-top: 18px; padding: 7px 10px; border-radius: 7px; background: var(--code-bg); font-family: var(--mono); font-size: 12px;}#page .repo-ref-link { display: inline-block; margin-top: 18px; padding: 8px 14px; border-radius: 8px; background: var(--accent-strong, #2158d0); color: #fff; font-weight: 600; text-decoration: none;}#page .repo-ref-link:hover,#page .repo-ref-link:focus-visible { color: #fff; filter: brightness(0.95);}.view-eyebrow { margin-bottom: 4px; color: var(--accent-strong); font-family: var(--mono); font-size: 11px; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase;}
/* ---- trace ---- */.trace-session { scroll-margin-top: 24px;}.trace-session + .trace-session { margin-top: 44px; padding-top: 40px; border-top: 1px solid var(--line);}.trace-session-title { margin: 0 0 14px; color: var(--ink); font-family: var(--serif); font-size: 22px; line-height: 1.2; letter-spacing: -0.02em; overflow-wrap: anywhere;}.workspace-header h1 { margin: 0; color: var(--ink); font-size: 30px; line-height: 1.2; letter-spacing: -0.025em;}.trace-meta { display: flex; flex-wrap: wrap; gap: 9px 20px; margin-bottom: 34px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 10px; background: rgba(255, 255, 255, 0.78); color: var(--muted); font-family: var(--mono); font-size: 11px;}.trace-meta strong { color: var(--ink); font-weight: 650;}.trace-source-missing { color: #b45309;}.trace-timeline { position: relative;}.trace-timeline::before { content: ""; position: absolute; top: 0; bottom: 0; left: 82px; width: 1px; background: #dedfe3;}.trace-load-controls { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin: 22px 0 0 100px; padding-top: 16px; border-top: 1px solid var(--line);}.trace-load-progress { color: var(--muted); font-family: var(--mono); font-size: 11px;}.trace-load-more { padding: 7px 12px; border: 1px solid var(--line-strong); border-radius: 7px; background: var(--paper); color: var(--ink); cursor: pointer; font: 650 12px/1.2 var(--sans);}.trace-load-more:hover:not(:disabled) { border-color: var(--accent); color: var(--accent-strong);}.trace-load-more:disabled { cursor: default; opacity: 0.65;}.trace-entry { --trace-depth: 0; position: relative; display: grid; grid-template-columns: 100px minmax(0, 1fr); margin: 0 0 18px calc(var(--trace-depth) * 24px);}.trace-rail { position: relative; min-height: 36px; padding: 4px 28px 0 0; color: #8a8d95; text-align: right; font-family: var(--mono);}.trace-number,.trace-elapsed { display: block; white-space: nowrap;}.trace-number { font-size: 12px; font-weight: 650;}.trace-elapsed { margin-top: 3px; font-size: 10px;}.trace-dot { position: absolute; top: 10px; right: 11px; width: 11px; height: 11px; border: 2px solid var(--paper); border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 1px #d7d9de;}.trace-card { min-width: 0; overflow: hidden; border: 1px solid #dddfe4; border-radius: 11px; background: rgba(255, 255, 255, 0.92);}.trace-card > header { display: flex; align-items: center; gap: 10px; min-height: 37px; padding: 8px 13px; border-bottom: 1px solid #eceef1;}.trace-status .trace-card > header { border-bottom: 0; padding-bottom: 5px;}.trace-kind { font-family: var(--mono); font-size: 10.5px; font-weight: 750; letter-spacing: 0.08em; text-transform: uppercase;}.trace-turn { color: var(--muted); font: 10px var(--mono);}.trace-status-badge { margin-left: auto; padding: 1px 6px; border-radius: 999px; background: #eef0f3; color: var(--muted); font: 9.5px var(--mono); text-transform: uppercase;}.trace-status-badge-error,.trace-status-badge-failed { background: #fef2f2; color: #b91c1c;}.trace-body { margin: 0; padding: 15px 17px 17px; overflow-wrap: anywhere; white-space: pre-wrap; font-family: var(--sans); font-size: 13px; line-height: 1.65;}.trace-reasoning .trace-card { border-style: dashed; border-color: #d7b98a; background: #fffdf8;}.trace-reasoning .trace-kind { color: #9a6b22;}.trace-reasoning .trace-body { font-style: italic;}.trace-user .trace-card { border-left: 3px solid #f3a66d;}.trace-tool_call .trace-card,.trace-tool_result .trace-card { border-color: #2d3036; background: #191a1e; color: #ececf0;}.trace-tool_call .trace-card > header,.trace-tool_result .trace-card > header { border-bottom-color: rgba(255, 255, 255, 0.1);}.trace-tool_call .trace-kind,.trace-tool_result .trace-kind { color: #f5a66d;}.trace-tool_call .trace-turn,.trace-tool_result .trace-turn { color: #979aa3;}.trace-tool_call .trace-body,.trace-tool_result .trace-body,.trace-output pre { font-family: var(--mono); font-size: 11.5px; line-height: 1.6;}#page .trace-tool_call pre.trace-body,#page .trace-tool_result pre.trace-body { margin: 0; padding: 15px 17px 17px; border: 0; border-radius: 0; background: transparent; color: #ececf0;}.trace-output { border-top: 1px dashed rgba(255, 255, 255, 0.14);}.trace-output summary { padding: 9px 14px; color: #aaaeb7; cursor: pointer; font: 700 10px var(--mono); letter-spacing: 0.06em; text-transform: uppercase;}#page .trace-output pre { max-height: 480px; margin: 0; padding: 0 16px 16px; border: 0; border-radius: 0; background: transparent; overflow: auto; color: #d7d8dd; white-space: pre-wrap;}
/* ---- workspace ---- */.workspace-header { padding-bottom: 24px;}.workspace-header p { margin: 0; color: var(--muted); font-family: var(--mono); font-size: 11px;}.workspace-inventory { overflow: hidden; border: 1px solid var(--line); border-radius: 11px; background: rgba(255, 255, 255, 0.92);}.workspace-folder > summary { display: flex; align-items: center; gap: 8px; min-height: 39px; padding: 8px 13px; background: #fafafa; cursor: pointer; font-weight: 650; list-style: none;}.workspace-folder > summary::-webkit-details-marker { display: none;}.workspace-folder > summary::after { content: "›"; margin-left: auto; color: #989ba2; transform: rotate(90deg);}.workspace-folder:not([open]) > summary::after { transform: rotate(0);}.workspace-folder-children { padding-left: 20px;}.workspace-file { display: grid; grid-template-columns: minmax(180px, 1fr) 72px 78px 180px 36px; align-items: center; min-height: 44px; padding: 7px 10px 7px 13px; color: var(--muted); font-family: var(--mono); font-size: 10.5px;}.workspace-file-name { display: flex; align-items: center; min-width: 0; gap: 8px; color: var(--ink); font-family: var(--sans); font-size: 12.5px; font-weight: 550;}.workspace-file-name span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}.workspace-file-type { width: fit-content; padding: 1px 6px; border-radius: 999px; background: var(--accent-soft); color: var(--accent-strong); text-transform: uppercase;}.workspace-download { display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; border-radius: 7px; color: var(--muted);}.workspace-download:hover { background: var(--accent-soft); color: var(--accent-strong);}.workspace-unpublished { color: #9ca3af; text-align: center;}
.workspace-header { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap;}.workspace-toggle { display: inline-flex; align-items: center; padding: 2px; border: 1px solid var(--line); border-radius: 999px; background: #fafafa;}.workspace-toggle-btn { padding: 4px 13px; border: 0; border-radius: 999px; background: transparent; color: var(--muted); font-family: var(--sans); font-size: 12px; font-weight: 600; cursor: pointer;}.workspace-toggle-btn:hover { color: var(--accent-strong);}.workspace-toggle-btn.is-active { background: var(--accent); color: #ffffff;}.workspace-group + .workspace-group { margin-top: 18px;}.workspace-group-head,.workspace-hub-group-head { display: flex; align-items: center; gap: 8px; margin: 0; padding: 8px 13px; background: #fafafa; border-bottom: 1px solid var(--line); color: var(--ink); font-family: var(--sans); font-size: 12px; font-weight: 650; text-transform: capitalize;}.workspace-group-count,.workspace-hub-count { padding: 0 7px; border-radius: 999px; background: var(--accent-soft); color: var(--accent-strong); font-family: var(--mono); font-size: 10.5px;}.workspace-group { overflow: hidden; border: 1px solid var(--line); border-radius: 11px; background: rgba(255, 255, 255, 0.92);}
.workspace-hub { margin-top: 28px;}.workspace-hub-title { margin: 0 0 14px; font-family: var(--sans); font-size: 16px; font-weight: 700; color: var(--ink);}.workspace-hub-group { overflow: hidden; border: 1px solid var(--line); border-radius: 11px; background: rgba(255, 255, 255, 0.92);}.workspace-hub-group + .workspace-hub-group { margin-top: 14px;}.workspace-hub-list { display: flex; flex-direction: column;}.workspace-hub-link { padding: 9px 13px; color: var(--accent-strong); font-family: var(--mono); font-size: 12px; text-decoration: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}.workspace-hub-link + .workspace-hub-link { border-top: 1px solid var(--line);}.workspace-hub-link:hover { background: var(--accent-soft); text-decoration: underline;}
/* --- UI nits --- *//* Flush group headers: #page h3/h2 (ID selectors) otherwise inject a top margin that, with overflow:hidden on the card, shows as whitespace above "Jobs" etc. */#page .workspace-hub-title { margin: 0 0 14px;}#page .workspace-hub-group-head,#page .workspace-group-head { margin: 0;}/* HF brand logo before the "Hugging Face artifacts" heading */.workspace-hub-title { display: flex; align-items: center; gap: 9px;}.workspace-hub-logo { width: 22px; height: 22px; flex: none;}/* Center empty-state placeholders (heading, body, command) */.view-empty { display: flex; flex-direction: column; align-items: center;}#page .view-empty h2,#page .view-empty p { text-align: center;}
@media (max-width: 720px) { #app { flex-direction: column; } #sidebar { width: 100%; flex: none; height: auto; position: static; } #content { display: block; width: 100%; padding: 28px 20px 80px; overflow-x: hidden; } #view-tabs { margin: 0 0 20px; gap: 18px; justify-content: flex-start; overflow-x: auto; } #view-tabs a { flex: 0 0 auto; } .trace-timeline::before { left: 16px; } .trace-entry { grid-template-columns: 32px minmax(0, 1fr); margin-left: calc(var(--trace-depth) * 10px); } .trace-rail { padding: 0; } .trace-number, .trace-elapsed { display: none; } .trace-dot { top: 10px; right: 10px; } .workspace-file { grid-template-columns: minmax(150px, 1fr) 66px 34px; } .workspace-file-size, .workspace-file-time { display: none; } #page { width: 100%; max-width: 100%; } #page h1, #logbook-title { font-size: 30px; } .cell-head { align-items: flex-start; flex-direction: column; gap: 4px; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687{ "schema_version": 2, "title": "Reproduction: Adaptive Personalized Federated Learning via Multi-task Averaging of Kernel Mean Embeddings", "emoji": "🎯", "space_id": "vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding", "paper": { "arxiv_id": "2603.02233" }, "tags": [ "icml2026-repro", "paper-ADHGbxsREr" ], "updated_at": "2026-07-28T06:21:29+00:00", "root": { "slug": "index", "title": "Reproduction: Adaptive Personalized Federated Learning via Multi-task Averaging of Kernel Mean Embeddings", "file": "pages/index.md", "children": [ { "slug": "executive-summary", "title": "Executive summary", "file": "pages/executive-summary/page.md", "children": [] }, { "slug": "claim-1-theorem-4-4-finite-sample-kme-guarantee", "title": "Claim 1: Theorem 4.4 finite-sample KME guarantee", "file": "pages/claim-1-theorem-4-4-finite-sample-kme-guarantee/page.md", "children": [] }, { "slug": "claim-2-corollary-4-6-downstream-excess-risk-transfer", "title": "Claim 2: Corollary 4.6 downstream excess-risk transfer", "file": "pages/claim-2-corollary-4-6-downstream-excess-risk-transfer/page.md", "children": [] }, { "slug": "claim-3-example-4-5-automatic-adaptive-collaboration", "title": "Claim 3: Example 4.5 automatic adaptive collaboration", "file": "pages/claim-3-example-4-5-automatic-adaptive-collaboration/page.md", "children": [] }, { "slug": "claim-4-theorem-5-2-random-fourier-feature-tradeoff", "title": "Claim 4: Theorem 5.2 random Fourier-feature tradeoff", "file": "pages/claim-4-theorem-5-2-random-fourier-feature-tradeoff/page.md", "children": [] }, { "slug": "claim-5-section-6-1-100-agent-synthetic-concept-shift", "title": "Claim 5: Section 6.1 100-agent synthetic concept shift", "file": "pages/claim-5-section-6-1-100-agent-synthetic-concept-shift/page.md", "children": [] }, { "slug": "claim-6-section-6-3-femnist-192-agent-benchmark", "title": "Claim 6: Section 6.3 FEMNIST 192-agent benchmark", "file": "pages/claim-6-section-6-3-femnist-192-agent-benchmark/page.md", "children": [] }, { "slug": "conclusion", "title": "Conclusion", "file": "pages/conclusion/page.md", "children": [] } ] }, "traces": [], "workspace": { "file": "workspace.json", "file_count": 0, "total_size": 0, "bucket_id": null }, "agent_view_tokens": 4609, "trace_view_tokens": 10, "workspace_view_tokens": 48, "revision": "da220efeb6d76cd226b2", "workspace_ref": { "repo_id": "vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts", "repo_type": "bucket", "repo_url": "https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts", "private": true }, "workspace_bucket": "https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts"}12345678910111213141516171819202122# Claim 1: Theorem 4.4 finite-sample KME guarantee
---<!-- trackio-cell{"type": "markdown", "id": "cell_069091946489", "created_at": "2026-07-19T09:32:03+00:00", "title": "Claim 1: Theorem 4.4 finite-sample KME guarantee"}-->Document setup, runs, and results for **Claim 1: Theorem 4.4 finite-sample KME guarantee**.
---<!-- trackio-cell{"type": "markdown", "id": "cell_40b9d46f1306", "created_at": "2026-07-19T09:54:23+00:00", "title": "Evidence and status"}-->The source theorem was checked against the [arXiv PDF](https://arxiv.org/pdf/2603.02233), Theorem 4.4 (Eq. 14–15). For every subset containing target agent 1, it bounds expected squared MMD by a bias term , variance , and lower-order terms involving , , and effective dimension. This directly establishes the stated bias–variance tradeoff. **Status: source-verified theorem statement; not independently re-proven.**
---<!-- trackio-cell{"type": "markdown", "id": "cell_7efaad82fdef", "created_at": "2026-07-19T09:56:03+00:00", "title": "Clarified evidence"}-->Clarification: in Eq. 14, for every V containing agent 1, the leading terms are Delta_V squared plus (Tr Sigma_1 + 2 Delta_V)/n_V. Delta_V is the largest distributional MMD within V and n_V is the combined client sample size. The remaining terms depend on log(B n_1), |V|/n_V, and effective dimension. This is a direct source audit of https://arxiv.org/pdf/2603.02233, not an independent proof.12345678910111213141516171819202122# Claim 2: Corollary 4.6 downstream excess-risk transfer
---<!-- trackio-cell{"type": "markdown", "id": "cell_6ed1cb9e8ba8", "created_at": "2026-07-19T09:32:03+00:00", "title": "Claim 2: Corollary 4.6 downstream excess-risk transfer"}-->Document setup, runs, and results for **Claim 2: Corollary 4.6 downstream excess-risk transfer**.
---<!-- trackio-cell{"type": "markdown", "id": "cell_130e10d00f66", "created_at": "2026-07-19T09:54:23+00:00", "title": "Evidence and status"}-->[Corollary 4.6 in the arXiv PDF](https://arxiv.org/pdf/2603.02233) states . Its Appendix F.4 proof expands population and weighted empirical risks through KMEs, applies optimality of , then Cauchy–Schwarz twice. Thus the claimed direct transfer from KME estimation error to task excess risk is supported by the paper. **Status: source-verified theorem/proof audit; optimization error remains outside the corollary’s scope.**
---<!-- trackio-cell{"type": "markdown", "id": "cell_efe13b52d7af", "created_at": "2026-07-19T09:56:17+00:00", "title": "Clarified evidence"}-->Clarification: Corollary 4.6 gives expected target excess risk at most 2 R_Theta times expected MMD between the learned empirical mixture and P_1. Appendix F.4 derives it by KME risk representation, weighted empirical-risk optimality, and Cauchy-Schwarz. Source: https://arxiv.org/pdf/2603.02233 .12345678910111213141516171819202122# Claim 3: Example 4.5 automatic adaptive collaboration
---<!-- trackio-cell{"type": "markdown", "id": "cell_3bda5e9c37b3", "created_at": "2026-07-19T09:32:03+00:00", "title": "Claim 3: Example 4.5 automatic adaptive collaboration"}-->Document setup, runs, and results for **Claim 3: Example 4.5 automatic adaptive collaboration**.
---<!-- trackio-cell{"type": "markdown", "id": "cell_632280fed65b", "created_at": "2026-07-19T09:54:23+00:00", "title": "Evidence and status"}-->[Example 4.5](https://arxiv.org/pdf/2603.02233) specializes Theorem 4.4 to identical agents: the leading error becomes (up to lower-order terms), while returns the local rate. This verifies the stated oracle-style pooling/local regimes at the level of the theorem. In the independent implementation below (Claim 5), the literal RFF Q-objective did not recover the paper’s empirical transition; see that page for the non-replication result. **Status: source-verified asymptotic example; empirical adaptivity not reproduced by this implementation.**
---<!-- trackio-cell{"type": "markdown", "id": "cell_d6652be82cbd", "created_at": "2026-07-19T09:56:34+00:00", "title": "Clarified evidence"}-->Clarification: Example 4.5 gives leading KME error Tr Sigma_1/n_V for an identical-agent set V, whereas V={1} recovers Tr Sigma_1/n_1. It establishes the pooling versus local statistical regimes in theory. Source: https://arxiv.org/pdf/2603.02233 .123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302# Claim 4: Theorem 5.2 random Fourier-feature tradeoff
---<!-- trackio-cell{"type": "markdown", "id": "cell_3385698671bb", "created_at": "2026-07-19T09:32:03+00:00", "title": "Claim 4: Theorem 5.2 random Fourier-feature tradeoff"}-->Document setup, runs, and results for **Claim 4: Theorem 5.2 random Fourier-feature tradeoff**.
---<!-- trackio-cell{"type": "code", "id": "cell_e08f5b2ace5f", "created_at": "2026-07-19T09:53:12+00:00", "title": "Run: python reproduce.py (exit 0)", "command": ["/home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python", "src/reproduce.py", "rff", "--repeats", "100", "--rff-grid", "16", "32", "64", "128", "256", "512", "1024", "--output", "outputs/rff_tradeoff_100seeds.csv", "--device", "cuda"], "exit_code": 0, "duration_s": 1.465}-->````bash$ /home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python src/reproduce.py rff --repeats 100 --rff-grid 16 32 64 128 256 512 1024 --output outputs/rff_tradeoff_100seeds.csv --device cuda````
exit 0 · 1.5s
````python title=reproduce.py#!/usr/bin/env python3"""Independent, GPU-capable checks for Fermanian et al. (2026), arXiv:2603.02233.
The implementation follows Algorithms 1--2 at a scaled experimental budget. Ituses RFF KMEs to choose a target client's collaboration weights and fits theweighted empirical-risk minimizer exactly for linear regression. The FEMNISTmode uses the public natural writer partition and a linear softmax model."""from __future__ import annotations
import argparseimport csvimport jsonimport mathfrom pathlib import Pathfrom time import perf_counter
import numpy as npimport torch
ROOT = Path(__file__).resolve().parents[1]
def device_from_arg(name: str) -> torch.device: if name == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") return torch.device(name)
def rff(z: torch.Tensor, d_rff: int, generator: torch.Generator, scale: torch.Tensor) -> torch.Tensor: """Gaussian-kernel RFF, with a supplied coordinate rescaling.""" w = torch.randn((z.shape[1], d_rff), generator=generator, device=z.device, dtype=z.dtype) w = w * scale[:, None] b = 2 * math.pi * torch.rand((d_rff,), generator=generator, device=z.device, dtype=z.dtype) return math.sqrt(2.0 / d_rff) * torch.cos(z @ w + b)
def simplex_weights(means: torch.Tensor, target_phi: torch.Tensor, steps: int = 900) -> torch.Tensor: """Solve Algorithm 1's empirical Q-aggregation objective by projected GD.""" b_agents = means.shape[0] n1 = target_phi.shape[0] centered = target_phi - means[0] cov = centered.T @ centered / max(n1 - 1, 1) trace = torch.trace(cov) diffs = means[1:] - means[0] q_terms = torch.sqrt(torch.clamp(torch.einsum("bd,df,bf->b", diffs, cov, diffs), min=0.0) + 1e-12) p_terms = torch.linalg.vector_norm(diffs, dim=1) # Table 1 uses CQ^2=CP=log B: CQ=sqrt(log B), CP=log B. cq, cp = math.sqrt(math.log(b_agents)), math.log(b_agents) w = torch.full((b_agents,), 1.0 / b_agents, device=means.device, dtype=means.dtype) for _ in range(steps): w.requires_grad_(True) mixture = w @ means loss = torch.sum((mixture - means[0]) ** 2) + 2.0 * w[0] * trace / n1 loss = loss + cq / math.sqrt(n1) * torch.dot(w[1:], q_terms) loss = loss + cp / n1 * torch.dot(w[1:], p_terms) (grad,) = torch.autograd.grad(loss, w) with torch.no_grad(): # Euclidean projection on the simplex, Duchi et al. (2008). v = w - 0.04 * grad u, _ = torch.sort(v, descending=True) cssv = torch.cumsum(u, 0) - 1 ind = torch.arange(1, b_agents + 1, device=v.device, dtype=v.dtype) rho = torch.nonzero(u - cssv / ind > 0, as_tuple=False)[-1, 0] theta = cssv[rho] / (rho + 1) w = torch.clamp(v - theta, min=0) return w.detach()
def weighted_linear_fit(xs: torch.Tensor, ys: torch.Tensor, weights: torch.Tensor, ridge: float = 1e-3) -> torch.Tensor: """Exact weighted empirical-risk minimizer for linear regression.""" b_agents, n, dim = xs.shape x = torch.cat([xs, torch.ones((b_agents, n, 1), device=xs.device, dtype=xs.dtype)], dim=-1) sample_w = (weights[:, None] / n).expand(b_agents, n).reshape(-1) flat_x, flat_y = x.reshape(-1, dim + 1), ys.reshape(-1) lhs = flat_x.T @ (flat_x * sample_w[:, None]) + ridge * torch.eye(dim + 1, device=xs.device) rhs = flat_x.T @ (flat_y * sample_w) return torch.linalg.solve(lhs, rhs)
def concept_trial(seed: int, sigma2: float, d_rff: int, device: torch.device) -> dict: g = torch.Generator(device=device).manual_seed(seed) b_agents, n, dim, n_test = 100, 10, 20, 1000 signs = torch.where(torch.rand((b_agents,), generator=g, device=device) > .5, 1., -1.) beta0 = torch.randn((dim,), generator=g, device=device) eps = torch.randn((b_agents, dim), generator=g, device=device) betas = signs[:, None] * math.sqrt(1 - sigma2) * beta0 + math.sqrt(sigma2) * eps x = 1.0 + torch.randn((b_agents, n, dim), generator=g, device=device) y = torch.einsum("bnd,bd->bn", x, betas) + math.sqrt(2.0) * torch.randn((b_agents, n), generator=g, device=device) x_test = 1.0 + torch.randn((n_test, dim), generator=g, device=device) y_test = x_test @ betas[0] + math.sqrt(2.0) * torch.randn((n_test,), generator=g, device=device) # The paper's weighted Gaussian KME kernel gives X a 1/sqrt(d) scaling. z = torch.cat([x, y[..., None]], dim=-1).reshape(-1, dim + 1) scale = torch.cat([torch.full((dim,), 1 / math.sqrt(dim), device=device), torch.ones((1,), device=device)]) phi = rff(z, d_rff, g, scale).reshape(b_agents, n, d_rff) means = phi.mean(1) q_w = simplex_weights(means, phi[0]) local = torch.zeros(b_agents, device=device); local[0] = 1 grand = torch.full((b_agents,), 1 / b_agents, device=device) oracle = (signs == signs[0]).float(); oracle /= oracle.sum() result = {"sigma2": sigma2, "seed": seed, "q_local_weight": float(q_w[0]), "q_same_group_weight": float(q_w[signs == signs[0]].sum())} for name, weights in [("local", local), ("grandmean", grand), ("oracle", oracle), ("qaggregation", q_w)]: beta = weighted_linear_fit(x, y, weights) pred = x_test @ beta[:-1] + beta[-1] result[f"{name}_mse"] = float(torch.mean((pred - y_test) ** 2)) return result
def run_concept(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) rows = [] for sigma2 in args.sigmas: for rep in range(args.repeats): rows.append(concept_trial(args.seed + rep * 101 + int(sigma2 * 1000), sigma2, args.rff_dim, device)) return rows
def exact_rbf_mmd(x: torch.Tensor, y: torch.Tensor, bandwidth: float = 1.0) -> torch.Tensor: def k(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: return torch.exp(-torch.cdist(a, b).square() / (2 * bandwidth * bandwidth)) return torch.sqrt(torch.clamp(k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean(), min=0.0))
def run_rff(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) g = torch.Generator(device=device).manual_seed(args.seed) x = torch.randn((300, 8), generator=g, device=device) y = torch.randn((300, 8), generator=g, device=device) + torch.tensor([0.35] + [0.] * 7, device=device) exact = float(exact_rbf_mmd(x, y)) rows = [] for d_rff in args.rff_grid: errors = [] for trial in range(args.repeats): tg = torch.Generator(device=device).manual_seed(args.seed + 1000 * d_rff + trial) phi = rff(torch.cat([x, y]), d_rff, tg, torch.ones(8, device=device)) approx = torch.linalg.vector_norm(phi[:len(x)].mean(0) - phi[len(x):].mean(0)).item() errors.append(abs(approx - exact)) rows.append({"rff_dim": d_rff, "exact_mmd": exact, "mean_abs_error": float(np.mean(errors)), "std_abs_error": float(np.std(errors)), "sqrt_logB_over_D": math.sqrt(math.log(100) / d_rff), "one_shot_floats_per_agent": d_rff}) return rows
def run_femnist(args: argparse.Namespace) -> list[dict]: """Actual FEMNIST writer data, deliberately scaled in samples/features/epochs.""" from datasets import load_dataset device = device_from_arg(args.device) local_parquet = ROOT / "data" / "femnist" / "data" / "train-00000-of-00001.parquet" dataset = load_dataset("parquet", data_files=str(local_parquet), split="train", streaming=True) if local_parquet.exists() else load_dataset("flwrlabs/femnist", split="train", streaming=True) by_writer: dict[str, list[tuple[np.ndarray, int]]] = {} want = args.agents for ex in dataset: writer = ex["writer_id"] if writer not in by_writer and len(by_writer) >= want: continue if writer in by_writer or len(by_writer) < want: by_writer.setdefault(writer, []).append((np.asarray(ex["image"], dtype=np.float32) / 255., int(ex["character"]))) if len(by_writer) >= want and all(len(v) >= args.train_per_agent + args.test_per_agent for v in by_writer.values()): break eligible = [v for v in by_writer.values() if len(v) >= args.train_per_agent + args.test_per_agent][:want] if len(eligible) < want: raise RuntimeError(f"Only found {len(eligible)} eligible writers; need {want}") x_train = torch.tensor(np.stack([np.stack([a for a, _ in v[:args.train_per_agent]]) for v in eligible]), device=device) y_train = torch.tensor(np.stack([[b for _, b in v[:args.train_per_agent]] for v in eligible]), device=device, dtype=torch.long) x_test = torch.tensor(np.stack([np.stack([a for a, _ in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]]) for v in eligible]), device=device) y_test = torch.tensor(np.stack([[b for _, b in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]] for v in eligible]), device=device, dtype=torch.long) b_agents, n, raw_dim = x_train.shape[0], x_train.shape[1], 784 flat = x_train.reshape(b_agents, n, raw_dim) # Fixed random projection reduces the RFF input cost while retaining a reproducible vision proxy. g = torch.Generator(device=device).manual_seed(args.seed) proj = torch.randn((raw_dim, args.feature_dim), generator=g, device=device) / math.sqrt(raw_dim) features = flat @ proj phi_all = rff(features.reshape(-1, args.feature_dim), args.rff_dim, g, torch.ones(args.feature_dim, device=device)).reshape(b_agents, n, args.rff_dim) means = phi_all.mean(1) # Fit one regularized softmax classifier for each target using its personalized weights. rows = [] all_x = features.reshape(-1, args.feature_dim) all_y = y_train.reshape(-1) for target in range(b_agents): weights = simplex_weights(means, phi_all[target], steps=300) schemes = {"local": torch.nn.functional.one_hot(torch.tensor(target, device=device), b_agents).float(), "grandmean": torch.full((b_agents,), 1 / b_agents, device=device), "qaggregation": weights} test_feat = x_test[target].reshape(args.test_per_agent, raw_dim) @ proj for name, w in schemes.items(): model = torch.zeros((args.feature_dim, 62), device=device, requires_grad=True) opt = torch.optim.Adam([model], lr=args.lr, weight_decay=1e-4) sample_w = (w[:, None] / n).expand(b_agents, n).reshape(-1) for _ in range(args.epochs): opt.zero_grad() losses = torch.nn.functional.cross_entropy(all_x @ model, all_y, reduction="none") (losses * sample_w).sum().backward(); opt.step() acc = ((test_feat @ model).argmax(1) == y_test[target]).float().mean().item() rows.append({"agent": target, "method": name, "accuracy": acc, "q_local_weight": float(weights[target])}) return rows
def write_rows(rows: list[dict], out: Path) -> None: out.parent.mkdir(parents=True, exist_ok=True) with out.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader(); writer.writerows(rows) out.with_suffix(".json").write_text(json.dumps(rows, indent=2))
def main() -> None: p = argparse.ArgumentParser() p.add_argument("mode", choices=["concept", "rff", "femnist"]) p.add_argument("--output", type=Path, required=True) p.add_argument("--device", default="auto") p.add_argument("--seed", type=int, default=20260719) p.add_argument("--repeats", type=int, default=30) p.add_argument("--rff-dim", type=int, default=500) p.add_argument("--sigmas", type=float, nargs="+", default=[0., .1, .25, .5, .75, 1.]) p.add_argument("--rff-grid", type=int, nargs="+", default=[16, 32, 64, 128, 256, 512, 1024]) p.add_argument("--agents", type=int, default=192) p.add_argument("--train-per-agent", type=int, default=32) p.add_argument("--test-per-agent", type=int, default=16) p.add_argument("--feature-dim", type=int, default=64) p.add_argument("--epochs", type=int, default=20) p.add_argument("--lr", type=float, default=.08) args = p.parse_args() started = perf_counter() rows = {"concept": run_concept, "rff": run_rff, "femnist": run_femnist}[args.mode](args) write_rows(rows, args.output) if args.mode == "concept": summary = {str(s): {k: float(np.mean([r[k] for r in rows if r["sigma2"] == s])) for k in ["local_mse", "grandmean_mse", "oracle_mse", "qaggregation_mse", "q_local_weight", "q_same_group_weight"]} for s in args.sigmas} print(json.dumps({"concept_summary": summary}, indent=2)) elif args.mode == "rff": print(json.dumps({"rff_summary": {str(r["rff_dim"]): r["mean_abs_error"] for r in rows}}, indent=2)) elif args.mode == "femnist": summary = {m: float(np.mean([r["accuracy"] for r in rows if r["method"] == m])) for m in ["local", "grandmean", "qaggregation"]} print(json.dumps({"femnist_accuracy": summary}, indent=2)) print(json.dumps({"mode": args.mode, "rows": len(rows), "output": str(args.output), "seconds": round(perf_counter() - started, 2), "device": str(device_from_arg(args.device))}, indent=2))
if __name__ == "__main__": main()
````
````output{ "rff_summary": { "16": 0.011847271621227264, "32": 0.008519105277955533, "64": 0.005433569923043251, "128": 0.004183858707547188, "256": 0.003424282595515251, "512": 0.0020784523338079454, "1024": 0.0013805751502513886 }}{ "mode": "rff", "rows": 7, "output": "outputs/rff_tradeoff_100seeds.csv", "seconds": 0.47, "device": "cuda"}
````
---<!-- trackio-cell{"type": "artifact", "id": "cell_ffe4264c28a2", "created_at": "2026-07-19T09:53:12+00:00", "title": "Artifact: rff_tradeoff_100seeds.csv", "path": "outputs/rff_tradeoff_100seeds.csv", "size": 721, "artifact_type": "dataset", "auto": true}-->**📦 Artifact** `outputs/rff_tradeoff_100seeds.csv` · dataset · 721 B
https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts#logbook-files/outputs/rff_tradeoff_100seeds.csv
---<!-- trackio-cell{"type": "markdown", "id": "cell_e4032fbdf86b", "created_at": "2026-07-19T09:56:47+00:00", "title": "Clarified evidence"}-->Theorem 5.2 source audit: https://arxiv.org/pdf/2603.02233 adds an RFF approximation contribution of order sqrt(log B / D), so increasing D trades one-shot communication for statistical precision. CUDA 100-seed check: mean absolute MMD error falls from 0.01185 at D=16 to 0.00138 at D=1024, while transmitted floats/client grow from 16 to 1024. Status: mechanism reproduced.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310# Claim 5: Section 6.1 100-agent synthetic concept shift
---<!-- trackio-cell{"type": "markdown", "id": "cell_c62136c62a13", "created_at": "2026-07-19T09:32:03+00:00", "title": "Claim 5: Section 6.1 100-agent synthetic concept shift"}-->Document setup, runs, and results for **Claim 5: Section 6.1 100-agent synthetic concept shift**.
---<!-- trackio-cell{"type": "code", "id": "cell_afaa63e40a29", "created_at": "2026-07-19T09:45:31+00:00", "title": "Run: echo (exit 0)", "command": ["echo", "TRACKIO_CAPTURE_CHECK"], "exit_code": 0, "duration_s": 0.001}-->````bash$ echo TRACKIO_CAPTURE_CHECK````
exit 0 · 0.0s
````outputTRACKIO_CAPTURE_CHECK
````
---<!-- trackio-cell{"type": "code", "id": "cell_ab96ac0a6224", "created_at": "2026-07-19T09:47:33+00:00", "title": "Run: python reproduce.py (exit 0)", "command": ["/home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python", "src/reproduce.py", "concept", "--repeats", "100", "--rff-dim", "500", "--output", "outputs/concept_100agents_100reps.csv", "--device", "cuda"], "exit_code": 0, "duration_s": 287.498}-->````bash$ /home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python src/reproduce.py concept --repeats 100 --rff-dim 500 --output outputs/concept_100agents_100reps.csv --device cuda````
exit 0 · 287.5s
````python title=reproduce.py#!/usr/bin/env python3"""Independent, GPU-capable checks for Fermanian et al. (2026), arXiv:2603.02233.
The implementation follows Algorithms 1--2 at a scaled experimental budget. Ituses RFF KMEs to choose a target client's collaboration weights and fits theweighted empirical-risk minimizer exactly for linear regression. The FEMNISTmode uses the public natural writer partition and a linear softmax model."""from __future__ import annotations
import argparseimport csvimport jsonimport mathfrom pathlib import Pathfrom time import perf_counter
import numpy as npimport torch
ROOT = Path(__file__).resolve().parents[1]
def device_from_arg(name: str) -> torch.device: if name == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") return torch.device(name)
def rff(z: torch.Tensor, d_rff: int, generator: torch.Generator, scale: torch.Tensor) -> torch.Tensor: """Gaussian-kernel RFF, with a supplied coordinate rescaling.""" w = torch.randn((z.shape[1], d_rff), generator=generator, device=z.device, dtype=z.dtype) w = w * scale[:, None] b = 2 * math.pi * torch.rand((d_rff,), generator=generator, device=z.device, dtype=z.dtype) return math.sqrt(2.0 / d_rff) * torch.cos(z @ w + b)
def simplex_weights(means: torch.Tensor, target_phi: torch.Tensor, steps: int = 900) -> torch.Tensor: """Solve Algorithm 1's empirical Q-aggregation objective by projected GD.""" b_agents = means.shape[0] n1 = target_phi.shape[0] centered = target_phi - means[0] cov = centered.T @ centered / max(n1 - 1, 1) trace = torch.trace(cov) diffs = means[1:] - means[0] q_terms = torch.sqrt(torch.clamp(torch.einsum("bd,df,bf->b", diffs, cov, diffs), min=0.0) + 1e-12) p_terms = torch.linalg.vector_norm(diffs, dim=1) # Table 1 uses CQ^2=CP=log B: CQ=sqrt(log B), CP=log B. cq, cp = math.sqrt(math.log(b_agents)), math.log(b_agents) w = torch.full((b_agents,), 1.0 / b_agents, device=means.device, dtype=means.dtype) for _ in range(steps): w.requires_grad_(True) mixture = w @ means loss = torch.sum((mixture - means[0]) ** 2) + 2.0 * w[0] * trace / n1 loss = loss + cq / math.sqrt(n1) * torch.dot(w[1:], q_terms) loss = loss + cp / n1 * torch.dot(w[1:], p_terms) (grad,) = torch.autograd.grad(loss, w) with torch.no_grad(): # Euclidean projection on the simplex, Duchi et al. (2008). v = w - 0.04 * grad u, _ = torch.sort(v, descending=True) cssv = torch.cumsum(u, 0) - 1 ind = torch.arange(1, b_agents + 1, device=v.device, dtype=v.dtype) rho = torch.nonzero(u - cssv / ind > 0, as_tuple=False)[-1, 0] theta = cssv[rho] / (rho + 1) w = torch.clamp(v - theta, min=0) return w.detach()
def weighted_linear_fit(xs: torch.Tensor, ys: torch.Tensor, weights: torch.Tensor, ridge: float = 1e-3) -> torch.Tensor: """Exact weighted empirical-risk minimizer for linear regression.""" b_agents, n, dim = xs.shape x = torch.cat([xs, torch.ones((b_agents, n, 1), device=xs.device, dtype=xs.dtype)], dim=-1) sample_w = (weights[:, None] / n).expand(b_agents, n).reshape(-1) flat_x, flat_y = x.reshape(-1, dim + 1), ys.reshape(-1) lhs = flat_x.T @ (flat_x * sample_w[:, None]) + ridge * torch.eye(dim + 1, device=xs.device) rhs = flat_x.T @ (flat_y * sample_w) return torch.linalg.solve(lhs, rhs)
def concept_trial(seed: int, sigma2: float, d_rff: int, device: torch.device) -> dict: g = torch.Generator(device=device).manual_seed(seed) b_agents, n, dim, n_test = 100, 10, 20, 1000 signs = torch.where(torch.rand((b_agents,), generator=g, device=device) > .5, 1., -1.) beta0 = torch.randn((dim,), generator=g, device=device) eps = torch.randn((b_agents, dim), generator=g, device=device) betas = signs[:, None] * math.sqrt(1 - sigma2) * beta0 + math.sqrt(sigma2) * eps x = 1.0 + torch.randn((b_agents, n, dim), generator=g, device=device) y = torch.einsum("bnd,bd->bn", x, betas) + math.sqrt(2.0) * torch.randn((b_agents, n), generator=g, device=device) x_test = 1.0 + torch.randn((n_test, dim), generator=g, device=device) y_test = x_test @ betas[0] + math.sqrt(2.0) * torch.randn((n_test,), generator=g, device=device) # The paper's weighted Gaussian KME kernel gives X a 1/sqrt(d) scaling. z = torch.cat([x, y[..., None]], dim=-1).reshape(-1, dim + 1) scale = torch.cat([torch.full((dim,), 1 / math.sqrt(dim), device=device), torch.ones((1,), device=device)]) phi = rff(z, d_rff, g, scale).reshape(b_agents, n, d_rff) means = phi.mean(1) q_w = simplex_weights(means, phi[0]) local = torch.zeros(b_agents, device=device); local[0] = 1 grand = torch.full((b_agents,), 1 / b_agents, device=device) oracle = (signs == signs[0]).float(); oracle /= oracle.sum() result = {"sigma2": sigma2, "seed": seed, "q_local_weight": float(q_w[0]), "q_same_group_weight": float(q_w[signs == signs[0]].sum())} for name, weights in [("local", local), ("grandmean", grand), ("oracle", oracle), ("qaggregation", q_w)]: beta = weighted_linear_fit(x, y, weights) pred = x_test @ beta[:-1] + beta[-1] result[f"{name}_mse"] = float(torch.mean((pred - y_test) ** 2)) return result
def run_concept(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) rows = [] for sigma2 in args.sigmas: for rep in range(args.repeats): rows.append(concept_trial(args.seed + rep * 101 + int(sigma2 * 1000), sigma2, args.rff_dim, device)) return rows
def exact_rbf_mmd(x: torch.Tensor, y: torch.Tensor, bandwidth: float = 1.0) -> torch.Tensor: def k(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: return torch.exp(-torch.cdist(a, b).square() / (2 * bandwidth * bandwidth)) return torch.sqrt(torch.clamp(k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean(), min=0.0))
def run_rff(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) g = torch.Generator(device=device).manual_seed(args.seed) x = torch.randn((300, 8), generator=g, device=device) y = torch.randn((300, 8), generator=g, device=device) + torch.tensor([0.35] + [0.] * 7, device=device) exact = float(exact_rbf_mmd(x, y)) rows = [] for d_rff in args.rff_grid: errors = [] for trial in range(args.repeats): tg = torch.Generator(device=device).manual_seed(args.seed + 1000 * d_rff + trial) phi = rff(torch.cat([x, y]), d_rff, tg, torch.ones(8, device=device)) approx = torch.linalg.vector_norm(phi[:len(x)].mean(0) - phi[len(x):].mean(0)).item() errors.append(abs(approx - exact)) rows.append({"rff_dim": d_rff, "exact_mmd": exact, "mean_abs_error": float(np.mean(errors)), "std_abs_error": float(np.std(errors)), "sqrt_logB_over_D": math.sqrt(math.log(100) / d_rff), "one_shot_floats_per_agent": d_rff}) return rows
def run_femnist(args: argparse.Namespace) -> list[dict]: """Actual FEMNIST writer data, deliberately scaled in samples/features/epochs.""" from datasets import load_dataset device = device_from_arg(args.device) local_parquet = ROOT / "data" / "femnist" / "data" / "train-00000-of-00001.parquet" dataset = load_dataset("parquet", data_files=str(local_parquet), split="train", streaming=True) if local_parquet.exists() else load_dataset("flwrlabs/femnist", split="train", streaming=True) by_writer: dict[str, list[tuple[np.ndarray, int]]] = {} want = args.agents for ex in dataset: writer = ex["writer_id"] if writer not in by_writer and len(by_writer) >= want: continue if writer in by_writer or len(by_writer) < want: by_writer.setdefault(writer, []).append((np.asarray(ex["image"], dtype=np.float32) / 255., int(ex["character"]))) if len(by_writer) >= want and all(len(v) >= args.train_per_agent + args.test_per_agent for v in by_writer.values()): break eligible = [v for v in by_writer.values() if len(v) >= args.train_per_agent + args.test_per_agent][:want] if len(eligible) < want: raise RuntimeError(f"Only found {len(eligible)} eligible writers; need {want}") x_train = torch.tensor(np.stack([np.stack([a for a, _ in v[:args.train_per_agent]]) for v in eligible]), device=device) y_train = torch.tensor(np.stack([[b for _, b in v[:args.train_per_agent]] for v in eligible]), device=device, dtype=torch.long) x_test = torch.tensor(np.stack([np.stack([a for a, _ in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]]) for v in eligible]), device=device) y_test = torch.tensor(np.stack([[b for _, b in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]] for v in eligible]), device=device, dtype=torch.long) b_agents, n, raw_dim = x_train.shape[0], x_train.shape[1], 784 flat = x_train.reshape(b_agents, n, raw_dim) # Fixed random projection reduces the RFF input cost while retaining a reproducible vision proxy. g = torch.Generator(device=device).manual_seed(args.seed) proj = torch.randn((raw_dim, args.feature_dim), generator=g, device=device) / math.sqrt(raw_dim) features = flat @ proj phi_all = rff(features.reshape(-1, args.feature_dim), args.rff_dim, g, torch.ones(args.feature_dim, device=device)).reshape(b_agents, n, args.rff_dim) means = phi_all.mean(1) # Fit one regularized softmax classifier for each target using its personalized weights. rows = [] all_x = features.reshape(-1, args.feature_dim) all_y = y_train.reshape(-1) for target in range(b_agents): weights = simplex_weights(means, phi_all[target], steps=300) schemes = {"local": torch.nn.functional.one_hot(torch.tensor(target, device=device), b_agents).float(), "grandmean": torch.full((b_agents,), 1 / b_agents, device=device), "qaggregation": weights} test_feat = x_test[target].reshape(args.test_per_agent, raw_dim) @ proj for name, w in schemes.items(): model = torch.zeros((args.feature_dim, 62), device=device, requires_grad=True) opt = torch.optim.Adam([model], lr=args.lr, weight_decay=1e-4) sample_w = (w[:, None] / n).expand(b_agents, n).reshape(-1) for _ in range(args.epochs): opt.zero_grad() losses = torch.nn.functional.cross_entropy(all_x @ model, all_y, reduction="none") (losses * sample_w).sum().backward(); opt.step() acc = ((test_feat @ model).argmax(1) == y_test[target]).float().mean().item() rows.append({"agent": target, "method": name, "accuracy": acc, "q_local_weight": float(weights[target])}) return rows
def write_rows(rows: list[dict], out: Path) -> None: out.parent.mkdir(parents=True, exist_ok=True) with out.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader(); writer.writerows(rows) out.with_suffix(".json").write_text(json.dumps(rows, indent=2))
def main() -> None: p = argparse.ArgumentParser() p.add_argument("mode", choices=["concept", "rff", "femnist"]) p.add_argument("--output", type=Path, required=True) p.add_argument("--device", default="auto") p.add_argument("--seed", type=int, default=20260719) p.add_argument("--repeats", type=int, default=30) p.add_argument("--rff-dim", type=int, default=500) p.add_argument("--sigmas", type=float, nargs="+", default=[0., .1, .25, .5, .75, 1.]) p.add_argument("--rff-grid", type=int, nargs="+", default=[16, 32, 64, 128, 256, 512, 1024]) p.add_argument("--agents", type=int, default=192) p.add_argument("--train-per-agent", type=int, default=32) p.add_argument("--test-per-agent", type=int, default=16) p.add_argument("--feature-dim", type=int, default=64) p.add_argument("--epochs", type=int, default=20) p.add_argument("--lr", type=float, default=.08) args = p.parse_args() started = perf_counter() rows = {"concept": run_concept, "rff": run_rff, "femnist": run_femnist}[args.mode](args) write_rows(rows, args.output) if args.mode == "concept": summary = {str(s): {k: float(np.mean([r[k] for r in rows if r["sigma2"] == s])) for k in ["local_mse", "grandmean_mse", "oracle_mse", "qaggregation_mse", "q_local_weight", "q_same_group_weight"]} for s in args.sigmas} print(json.dumps({"concept_summary": summary}, indent=2)) elif args.mode == "rff": print(json.dumps({"rff_summary": {str(r["rff_dim"]): r["mean_abs_error"] for r in rows}}, indent=2)) elif args.mode == "femnist": summary = {m: float(np.mean([r["accuracy"] for r in rows if r["method"] == m])) for m in ["local", "grandmean", "qaggregation"]} print(json.dumps({"femnist_accuracy": summary}, indent=2)) print(json.dumps({"mode": args.mode, "rows": len(rows), "output": str(args.output), "seconds": round(perf_counter() - started, 2), "device": str(device_from_arg(args.device))}, indent=2))
if __name__ == "__main__": main()
````
````output{ "concept_summary": { "0.0": { "local_mse": 15.748318042755127, "grandmean_mse": 40.606961507797244, "oracle_mse": 2.0862513756752015, "qaggregation_mse": 17.83958231449127, "q_local_weight": 0.9771137142181396, "q_same_group_weight": 0.9975556522607804 }, "0.1": { "local_mse": 15.361917610168456, "grandmean_mse": 45.73134832382202, "oracle_mse": 6.119768922328949, "qaggregation_mse": 18.07122127532959, "q_local_weight": 0.9787336409091949, "q_same_group_weight": 0.9981670784950256 }, "0.25": { "local_mse": 15.827756361961365, "grandmean_mse": 39.008377923965455, "oracle_mse": 11.351614267826081, "qaggregation_mse": 25.339054584503174, "q_local_weight": 0.9825072956085205, "q_same_group_weight": 0.99599778175354 }, "0.5": { "local_mse": 14.459182372093201, "grandmean_mse": 45.512830362319946, "oracle_mse": 24.322485909461975, "qaggregation_mse": 25.430337595939637, "q_local_weight": 0.9876203048229217, "q_same_group_weight": 0.9948384702205658 }, "0.75": { "local_mse": 15.87236515045166, "grandmean_mse": 39.63199781417847, "oracle_mse": 30.853181953430177, "qaggregation_mse": 33.74232290267944, "q_local_weight": 0.9877495408058167, "q_same_group_weight": 0.9943676108121872 }, "1.0": { "local_mse": 15.390748682022094, "grandmean_mse": 39.16119129180908, "oracle_mse": 40.00151491165161, "qaggregation_mse": 30.293080587387085, "q_local_weight": 0.9896031093597412, "q_same_group_weight": 0.9947122848033905 } }}{ "mode": "concept", "rows": 600, "output": "outputs/concept_100agents_100reps.csv", "seconds": 286.58, "device": "cuda"}
````
---<!-- trackio-cell{"type": "artifact", "id": "cell_edfa78971b70", "created_at": "2026-07-19T09:47:34+00:00", "title": "Artifact: concept_100agents_100reps.csv", "path": "outputs/concept_100agents_100reps.csv", "size": 63718, "artifact_type": "dataset", "auto": true}-->**📦 Artifact** `outputs/concept_100agents_100reps.csv` · dataset · 63.7 kB
https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts#logbook-files/outputs/concept_100agents_100reps.csv
---<!-- trackio-cell{"type": "code", "id": "cell_1d5aa5c25cad", "created_at": "2026-07-19T09:49:48+00:00", "title": "Run: python reproduce.py (exit 0)", "command": ["/home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python", "src/reproduce.py", "concept", "--repeats", "100", "--rff-dim", "500", "--output", "outputs/concept_100agents_100reps.csv", "--device", "cuda"], "exit_code": 0, "duration_s": 333.017}-->````bash$ /home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python src/reproduce.py concept --repeats 100 --rff-dim 500 --output outputs/concept_100agents_100reps.csv --device cuda````
exit 0 · 333.0s
````python title=reproduce.py#!/usr/bin/env python3"""Independent, GPU-capable checks for Fermanian et al. (2026), arXiv:2603.02233.
The implementation follows Algorithms 1--2 at a scaled experimental budget. Ituses RFF KMEs to choose a target client's collaboration weights and fits theweighted empirical-risk minimizer exactly for linear regression. The FEMNISTmode uses the public natural writer partition and a linear softmax model."""from __future__ import annotations
import argparseimport csvimport jsonimport mathfrom pathlib import Pathfrom time import perf_counter
import numpy as npimport torch
ROOT = Path(__file__).resolve().parents[1]
def device_from_arg(name: str) -> torch.device: if name == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") return torch.device(name)
def rff(z: torch.Tensor, d_rff: int, generator: torch.Generator, scale: torch.Tensor) -> torch.Tensor: """Gaussian-kernel RFF, with a supplied coordinate rescaling.""" w = torch.randn((z.shape[1], d_rff), generator=generator, device=z.device, dtype=z.dtype) w = w * scale[:, None] b = 2 * math.pi * torch.rand((d_rff,), generator=generator, device=z.device, dtype=z.dtype) return math.sqrt(2.0 / d_rff) * torch.cos(z @ w + b)
def simplex_weights(means: torch.Tensor, target_phi: torch.Tensor, steps: int = 900) -> torch.Tensor: """Solve Algorithm 1's empirical Q-aggregation objective by projected GD.""" b_agents = means.shape[0] n1 = target_phi.shape[0] centered = target_phi - means[0] cov = centered.T @ centered / max(n1 - 1, 1) trace = torch.trace(cov) diffs = means[1:] - means[0] q_terms = torch.sqrt(torch.clamp(torch.einsum("bd,df,bf->b", diffs, cov, diffs), min=0.0) + 1e-12) p_terms = torch.linalg.vector_norm(diffs, dim=1) # Table 1 uses CQ^2=CP=log B: CQ=sqrt(log B), CP=log B. cq, cp = math.sqrt(math.log(b_agents)), math.log(b_agents) w = torch.full((b_agents,), 1.0 / b_agents, device=means.device, dtype=means.dtype) for _ in range(steps): w.requires_grad_(True) mixture = w @ means loss = torch.sum((mixture - means[0]) ** 2) + 2.0 * w[0] * trace / n1 loss = loss + cq / math.sqrt(n1) * torch.dot(w[1:], q_terms) loss = loss + cp / n1 * torch.dot(w[1:], p_terms) (grad,) = torch.autograd.grad(loss, w) with torch.no_grad(): # Euclidean projection on the simplex, Duchi et al. (2008). v = w - 0.04 * grad u, _ = torch.sort(v, descending=True) cssv = torch.cumsum(u, 0) - 1 ind = torch.arange(1, b_agents + 1, device=v.device, dtype=v.dtype) rho = torch.nonzero(u - cssv / ind > 0, as_tuple=False)[-1, 0] theta = cssv[rho] / (rho + 1) w = torch.clamp(v - theta, min=0) return w.detach()
def weighted_linear_fit(xs: torch.Tensor, ys: torch.Tensor, weights: torch.Tensor, ridge: float = 1e-3) -> torch.Tensor: """Exact weighted empirical-risk minimizer for linear regression.""" b_agents, n, dim = xs.shape x = torch.cat([xs, torch.ones((b_agents, n, 1), device=xs.device, dtype=xs.dtype)], dim=-1) sample_w = (weights[:, None] / n).expand(b_agents, n).reshape(-1) flat_x, flat_y = x.reshape(-1, dim + 1), ys.reshape(-1) lhs = flat_x.T @ (flat_x * sample_w[:, None]) + ridge * torch.eye(dim + 1, device=xs.device) rhs = flat_x.T @ (flat_y * sample_w) return torch.linalg.solve(lhs, rhs)
def concept_trial(seed: int, sigma2: float, d_rff: int, device: torch.device) -> dict: g = torch.Generator(device=device).manual_seed(seed) b_agents, n, dim, n_test = 100, 10, 20, 1000 signs = torch.where(torch.rand((b_agents,), generator=g, device=device) > .5, 1., -1.) beta0 = torch.randn((dim,), generator=g, device=device) eps = torch.randn((b_agents, dim), generator=g, device=device) betas = signs[:, None] * math.sqrt(1 - sigma2) * beta0 + math.sqrt(sigma2) * eps x = 1.0 + torch.randn((b_agents, n, dim), generator=g, device=device) y = torch.einsum("bnd,bd->bn", x, betas) + math.sqrt(2.0) * torch.randn((b_agents, n), generator=g, device=device) x_test = 1.0 + torch.randn((n_test, dim), generator=g, device=device) y_test = x_test @ betas[0] + math.sqrt(2.0) * torch.randn((n_test,), generator=g, device=device) # The paper's weighted Gaussian KME kernel gives X a 1/sqrt(d) scaling. z = torch.cat([x, y[..., None]], dim=-1).reshape(-1, dim + 1) scale = torch.cat([torch.full((dim,), 1 / math.sqrt(dim), device=device), torch.ones((1,), device=device)]) phi = rff(z, d_rff, g, scale).reshape(b_agents, n, d_rff) means = phi.mean(1) q_w = simplex_weights(means, phi[0]) local = torch.zeros(b_agents, device=device); local[0] = 1 grand = torch.full((b_agents,), 1 / b_agents, device=device) oracle = (signs == signs[0]).float(); oracle /= oracle.sum() result = {"sigma2": sigma2, "seed": seed, "q_local_weight": float(q_w[0]), "q_same_group_weight": float(q_w[signs == signs[0]].sum())} for name, weights in [("local", local), ("grandmean", grand), ("oracle", oracle), ("qaggregation", q_w)]: beta = weighted_linear_fit(x, y, weights) pred = x_test @ beta[:-1] + beta[-1] result[f"{name}_mse"] = float(torch.mean((pred - y_test) ** 2)) return result
def run_concept(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) rows = [] for sigma2 in args.sigmas: for rep in range(args.repeats): rows.append(concept_trial(args.seed + rep * 101 + int(sigma2 * 1000), sigma2, args.rff_dim, device)) return rows
def exact_rbf_mmd(x: torch.Tensor, y: torch.Tensor, bandwidth: float = 1.0) -> torch.Tensor: def k(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: return torch.exp(-torch.cdist(a, b).square() / (2 * bandwidth * bandwidth)) return torch.sqrt(torch.clamp(k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean(), min=0.0))
def run_rff(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) g = torch.Generator(device=device).manual_seed(args.seed) x = torch.randn((300, 8), generator=g, device=device) y = torch.randn((300, 8), generator=g, device=device) + torch.tensor([0.35] + [0.] * 7, device=device) exact = float(exact_rbf_mmd(x, y)) rows = [] for d_rff in args.rff_grid: errors = [] for trial in range(args.repeats): tg = torch.Generator(device=device).manual_seed(args.seed + 1000 * d_rff + trial) phi = rff(torch.cat([x, y]), d_rff, tg, torch.ones(8, device=device)) approx = torch.linalg.vector_norm(phi[:len(x)].mean(0) - phi[len(x):].mean(0)).item() errors.append(abs(approx - exact)) rows.append({"rff_dim": d_rff, "exact_mmd": exact, "mean_abs_error": float(np.mean(errors)), "std_abs_error": float(np.std(errors)), "sqrt_logB_over_D": math.sqrt(math.log(100) / d_rff), "one_shot_floats_per_agent": d_rff}) return rows
def run_femnist(args: argparse.Namespace) -> list[dict]: """Actual FEMNIST writer data, deliberately scaled in samples/features/epochs.""" from datasets import load_dataset device = device_from_arg(args.device) local_parquet = ROOT / "data" / "femnist" / "data" / "train-00000-of-00001.parquet" dataset = load_dataset("parquet", data_files=str(local_parquet), split="train", streaming=True) if local_parquet.exists() else load_dataset("flwrlabs/femnist", split="train", streaming=True) by_writer: dict[str, list[tuple[np.ndarray, int]]] = {} want = args.agents for ex in dataset: writer = ex["writer_id"] if writer not in by_writer and len(by_writer) >= want: continue if writer in by_writer or len(by_writer) < want: by_writer.setdefault(writer, []).append((np.asarray(ex["image"], dtype=np.float32) / 255., int(ex["character"]))) if len(by_writer) >= want and all(len(v) >= args.train_per_agent + args.test_per_agent for v in by_writer.values()): break eligible = [v for v in by_writer.values() if len(v) >= args.train_per_agent + args.test_per_agent][:want] if len(eligible) < want: raise RuntimeError(f"Only found {len(eligible)} eligible writers; need {want}") x_train = torch.tensor(np.stack([np.stack([a for a, _ in v[:args.train_per_agent]]) for v in eligible]), device=device) y_train = torch.tensor(np.stack([[b for _, b in v[:args.train_per_agent]] for v in eligible]), device=device, dtype=torch.long) x_test = torch.tensor(np.stack([np.stack([a for a, _ in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]]) for v in eligible]), device=device) y_test = torch.tensor(np.stack([[b for _, b in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]] for v in eligible]), device=device, dtype=torch.long) b_agents, n, raw_dim = x_train.shape[0], x_train.shape[1], 784 flat = x_train.reshape(b_agents, n, raw_dim) # Fixed random projection reduces the RFF input cost while retaining a reproducible vision proxy. g = torch.Generator(device=device).manual_seed(args.seed) proj = torch.randn((raw_dim, args.feature_dim), generator=g, device=device) / math.sqrt(raw_dim) features = flat @ proj phi_all = rff(features.reshape(-1, args.feature_dim), args.rff_dim, g, torch.ones(args.feature_dim, device=device)).reshape(b_agents, n, args.rff_dim) means = phi_all.mean(1) # Fit one regularized softmax classifier for each target using its personalized weights. rows = [] all_x = features.reshape(-1, args.feature_dim) all_y = y_train.reshape(-1) for target in range(b_agents): weights = simplex_weights(means, phi_all[target], steps=300) schemes = {"local": torch.nn.functional.one_hot(torch.tensor(target, device=device), b_agents).float(), "grandmean": torch.full((b_agents,), 1 / b_agents, device=device), "qaggregation": weights} test_feat = x_test[target].reshape(args.test_per_agent, raw_dim) @ proj for name, w in schemes.items(): model = torch.zeros((args.feature_dim, 62), device=device, requires_grad=True) opt = torch.optim.Adam([model], lr=args.lr, weight_decay=1e-4) sample_w = (w[:, None] / n).expand(b_agents, n).reshape(-1) for _ in range(args.epochs): opt.zero_grad() losses = torch.nn.functional.cross_entropy(all_x @ model, all_y, reduction="none") (losses * sample_w).sum().backward(); opt.step() acc = ((test_feat @ model).argmax(1) == y_test[target]).float().mean().item() rows.append({"agent": target, "method": name, "accuracy": acc, "q_local_weight": float(weights[target])}) return rows
def write_rows(rows: list[dict], out: Path) -> None: out.parent.mkdir(parents=True, exist_ok=True) with out.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader(); writer.writerows(rows) out.with_suffix(".json").write_text(json.dumps(rows, indent=2))
def main() -> None: p = argparse.ArgumentParser() p.add_argument("mode", choices=["concept", "rff", "femnist"]) p.add_argument("--output", type=Path, required=True) p.add_argument("--device", default="auto") p.add_argument("--seed", type=int, default=20260719) p.add_argument("--repeats", type=int, default=30) p.add_argument("--rff-dim", type=int, default=500) p.add_argument("--sigmas", type=float, nargs="+", default=[0., .1, .25, .5, .75, 1.]) p.add_argument("--rff-grid", type=int, nargs="+", default=[16, 32, 64, 128, 256, 512, 1024]) p.add_argument("--agents", type=int, default=192) p.add_argument("--train-per-agent", type=int, default=32) p.add_argument("--test-per-agent", type=int, default=16) p.add_argument("--feature-dim", type=int, default=64) p.add_argument("--epochs", type=int, default=20) p.add_argument("--lr", type=float, default=.08) args = p.parse_args() started = perf_counter() rows = {"concept": run_concept, "rff": run_rff, "femnist": run_femnist}[args.mode](args) write_rows(rows, args.output) if args.mode == "concept": summary = {str(s): {k: float(np.mean([r[k] for r in rows if r["sigma2"] == s])) for k in ["local_mse", "grandmean_mse", "oracle_mse", "qaggregation_mse", "q_local_weight", "q_same_group_weight"]} for s in args.sigmas} print(json.dumps({"concept_summary": summary}, indent=2)) elif args.mode == "rff": print(json.dumps({"rff_summary": {str(r["rff_dim"]): r["mean_abs_error"] for r in rows}}, indent=2)) elif args.mode == "femnist": summary = {m: float(np.mean([r["accuracy"] for r in rows if r["method"] == m])) for m in ["local", "grandmean", "qaggregation"]} print(json.dumps({"femnist_accuracy": summary}, indent=2)) print(json.dumps({"mode": args.mode, "rows": len(rows), "output": str(args.output), "seconds": round(perf_counter() - started, 2), "device": str(device_from_arg(args.device))}, indent=2))
if __name__ == "__main__": main()
````
````output{ "concept_summary": { "0.0": { "local_mse": 15.748318042755127, "grandmean_mse": 40.606961507797244, "oracle_mse": 2.0862513756752015, "qaggregation_mse": 17.83958231449127, "q_local_weight": 0.9771137142181396, "q_same_group_weight": 0.9975556522607804 }, "0.1": { "local_mse": 15.361917610168456, "grandmean_mse": 45.73134832382202, "oracle_mse": 6.119768922328949, "qaggregation_mse": 18.07122127532959, "q_local_weight": 0.9787336409091949, "q_same_group_weight": 0.9981670784950256 }, "0.25": { "local_mse": 15.827756361961365, "grandmean_mse": 39.008377923965455, "oracle_mse": 11.351614267826081, "qaggregation_mse": 25.339054584503174, "q_local_weight": 0.9825072956085205, "q_same_group_weight": 0.99599778175354 }, "0.5": { "local_mse": 14.459182372093201, "grandmean_mse": 45.512830362319946, "oracle_mse": 24.322485909461975, "qaggregation_mse": 25.430337595939637, "q_local_weight": 0.9876203048229217, "q_same_group_weight": 0.9948384702205658 }, "0.75": { "local_mse": 15.87236515045166, "grandmean_mse": 39.63199781417847, "oracle_mse": 30.853181953430177, "qaggregation_mse": 33.74232290267944, "q_local_weight": 0.9877495408058167, "q_same_group_weight": 0.9943676108121872 }, "1.0": { "local_mse": 15.390748682022094, "grandmean_mse": 39.16119129180908, "oracle_mse": 40.00151491165161, "qaggregation_mse": 30.293080587387085, "q_local_weight": 0.9896031093597412, "q_same_group_weight": 0.9947122848033905 } }}{ "mode": "concept", "rows": 600, "output": "outputs/concept_100agents_100reps.csv", "seconds": 332.1, "device": "cuda"}
````
---<!-- trackio-cell{"type": "artifact", "id": "cell_5838f11deee2", "created_at": "2026-07-19T09:49:49+00:00", "title": "Artifact: concept_100agents_100reps.csv", "path": "outputs/concept_100agents_100reps.csv", "size": 63718, "artifact_type": "dataset", "auto": true}-->**📦 Artifact** `outputs/concept_100agents_100reps.csv` · dataset · 63.7 kB
https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts#logbook-files/outputs/concept_100agents_100reps.csv
---<!-- trackio-cell{"type": "code", "id": "cell_0e566181e79c", "created_at": "2026-07-19T09:50:42+00:00", "title": "Run: python reproduce.py (exit 0)", "command": ["/home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python", "src/reproduce.py", "concept", "--repeats", "100", "--rff-dim", "500", "--output", "outputs/concept_100agents_100reps.csv", "--device", "cuda"], "exit_code": 0, "duration_s": 300.077}-->````bash$ /home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python src/reproduce.py concept --repeats 100 --rff-dim 500 --output outputs/concept_100agents_100reps.csv --device cuda````
exit 0 · 300.1s
````python title=reproduce.py#!/usr/bin/env python3"""Independent, GPU-capable checks for Fermanian et al. (2026), arXiv:2603.02233.
The implementation follows Algorithms 1--2 at a scaled experimental budget. Ituses RFF KMEs to choose a target client's collaboration weights and fits theweighted empirical-risk minimizer exactly for linear regression. The FEMNISTmode uses the public natural writer partition and a linear softmax model."""from __future__ import annotations
import argparseimport csvimport jsonimport mathfrom pathlib import Pathfrom time import perf_counter
import numpy as npimport torch
ROOT = Path(__file__).resolve().parents[1]
def device_from_arg(name: str) -> torch.device: if name == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") return torch.device(name)
def rff(z: torch.Tensor, d_rff: int, generator: torch.Generator, scale: torch.Tensor) -> torch.Tensor: """Gaussian-kernel RFF, with a supplied coordinate rescaling.""" w = torch.randn((z.shape[1], d_rff), generator=generator, device=z.device, dtype=z.dtype) w = w * scale[:, None] b = 2 * math.pi * torch.rand((d_rff,), generator=generator, device=z.device, dtype=z.dtype) return math.sqrt(2.0 / d_rff) * torch.cos(z @ w + b)
def simplex_weights(means: torch.Tensor, target_phi: torch.Tensor, steps: int = 900) -> torch.Tensor: """Solve Algorithm 1's empirical Q-aggregation objective by projected GD.""" b_agents = means.shape[0] n1 = target_phi.shape[0] centered = target_phi - means[0] cov = centered.T @ centered / max(n1 - 1, 1) trace = torch.trace(cov) diffs = means[1:] - means[0] q_terms = torch.sqrt(torch.clamp(torch.einsum("bd,df,bf->b", diffs, cov, diffs), min=0.0) + 1e-12) p_terms = torch.linalg.vector_norm(diffs, dim=1) # Table 1 uses CQ^2=CP=log B: CQ=sqrt(log B), CP=log B. cq, cp = math.sqrt(math.log(b_agents)), math.log(b_agents) w = torch.full((b_agents,), 1.0 / b_agents, device=means.device, dtype=means.dtype) for _ in range(steps): w.requires_grad_(True) mixture = w @ means loss = torch.sum((mixture - means[0]) ** 2) + 2.0 * w[0] * trace / n1 loss = loss + cq / math.sqrt(n1) * torch.dot(w[1:], q_terms) loss = loss + cp / n1 * torch.dot(w[1:], p_terms) (grad,) = torch.autograd.grad(loss, w) with torch.no_grad(): # Euclidean projection on the simplex, Duchi et al. (2008). v = w - 0.04 * grad u, _ = torch.sort(v, descending=True) cssv = torch.cumsum(u, 0) - 1 ind = torch.arange(1, b_agents + 1, device=v.device, dtype=v.dtype) rho = torch.nonzero(u - cssv / ind > 0, as_tuple=False)[-1, 0] theta = cssv[rho] / (rho + 1) w = torch.clamp(v - theta, min=0) return w.detach()
def weighted_linear_fit(xs: torch.Tensor, ys: torch.Tensor, weights: torch.Tensor, ridge: float = 1e-3) -> torch.Tensor: """Exact weighted empirical-risk minimizer for linear regression.""" b_agents, n, dim = xs.shape x = torch.cat([xs, torch.ones((b_agents, n, 1), device=xs.device, dtype=xs.dtype)], dim=-1) sample_w = (weights[:, None] / n).expand(b_agents, n).reshape(-1) flat_x, flat_y = x.reshape(-1, dim + 1), ys.reshape(-1) lhs = flat_x.T @ (flat_x * sample_w[:, None]) + ridge * torch.eye(dim + 1, device=xs.device) rhs = flat_x.T @ (flat_y * sample_w) return torch.linalg.solve(lhs, rhs)
def concept_trial(seed: int, sigma2: float, d_rff: int, device: torch.device) -> dict: g = torch.Generator(device=device).manual_seed(seed) b_agents, n, dim, n_test = 100, 10, 20, 1000 signs = torch.where(torch.rand((b_agents,), generator=g, device=device) > .5, 1., -1.) beta0 = torch.randn((dim,), generator=g, device=device) eps = torch.randn((b_agents, dim), generator=g, device=device) betas = signs[:, None] * math.sqrt(1 - sigma2) * beta0 + math.sqrt(sigma2) * eps x = 1.0 + torch.randn((b_agents, n, dim), generator=g, device=device) y = torch.einsum("bnd,bd->bn", x, betas) + math.sqrt(2.0) * torch.randn((b_agents, n), generator=g, device=device) x_test = 1.0 + torch.randn((n_test, dim), generator=g, device=device) y_test = x_test @ betas[0] + math.sqrt(2.0) * torch.randn((n_test,), generator=g, device=device) # The paper's weighted Gaussian KME kernel gives X a 1/sqrt(d) scaling. z = torch.cat([x, y[..., None]], dim=-1).reshape(-1, dim + 1) scale = torch.cat([torch.full((dim,), 1 / math.sqrt(dim), device=device), torch.ones((1,), device=device)]) phi = rff(z, d_rff, g, scale).reshape(b_agents, n, d_rff) means = phi.mean(1) q_w = simplex_weights(means, phi[0]) local = torch.zeros(b_agents, device=device); local[0] = 1 grand = torch.full((b_agents,), 1 / b_agents, device=device) oracle = (signs == signs[0]).float(); oracle /= oracle.sum() result = {"sigma2": sigma2, "seed": seed, "q_local_weight": float(q_w[0]), "q_same_group_weight": float(q_w[signs == signs[0]].sum())} for name, weights in [("local", local), ("grandmean", grand), ("oracle", oracle), ("qaggregation", q_w)]: beta = weighted_linear_fit(x, y, weights) pred = x_test @ beta[:-1] + beta[-1] result[f"{name}_mse"] = float(torch.mean((pred - y_test) ** 2)) return result
def run_concept(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) rows = [] for sigma2 in args.sigmas: for rep in range(args.repeats): rows.append(concept_trial(args.seed + rep * 101 + int(sigma2 * 1000), sigma2, args.rff_dim, device)) return rows
def exact_rbf_mmd(x: torch.Tensor, y: torch.Tensor, bandwidth: float = 1.0) -> torch.Tensor: def k(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: return torch.exp(-torch.cdist(a, b).square() / (2 * bandwidth * bandwidth)) return torch.sqrt(torch.clamp(k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean(), min=0.0))
def run_rff(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) g = torch.Generator(device=device).manual_seed(args.seed) x = torch.randn((300, 8), generator=g, device=device) y = torch.randn((300, 8), generator=g, device=device) + torch.tensor([0.35] + [0.] * 7, device=device) exact = float(exact_rbf_mmd(x, y)) rows = [] for d_rff in args.rff_grid: errors = [] for trial in range(args.repeats): tg = torch.Generator(device=device).manual_seed(args.seed + 1000 * d_rff + trial) phi = rff(torch.cat([x, y]), d_rff, tg, torch.ones(8, device=device)) approx = torch.linalg.vector_norm(phi[:len(x)].mean(0) - phi[len(x):].mean(0)).item() errors.append(abs(approx - exact)) rows.append({"rff_dim": d_rff, "exact_mmd": exact, "mean_abs_error": float(np.mean(errors)), "std_abs_error": float(np.std(errors)), "sqrt_logB_over_D": math.sqrt(math.log(100) / d_rff), "one_shot_floats_per_agent": d_rff}) return rows
def run_femnist(args: argparse.Namespace) -> list[dict]: """Actual FEMNIST writer data, deliberately scaled in samples/features/epochs.""" from datasets import load_dataset device = device_from_arg(args.device) local_parquet = ROOT / "data" / "femnist" / "data" / "train-00000-of-00001.parquet" dataset = load_dataset("parquet", data_files=str(local_parquet), split="train", streaming=True) if local_parquet.exists() else load_dataset("flwrlabs/femnist", split="train", streaming=True) by_writer: dict[str, list[tuple[np.ndarray, int]]] = {} want = args.agents for ex in dataset: writer = ex["writer_id"] if writer not in by_writer and len(by_writer) >= want: continue if writer in by_writer or len(by_writer) < want: by_writer.setdefault(writer, []).append((np.asarray(ex["image"], dtype=np.float32) / 255., int(ex["character"]))) if len(by_writer) >= want and all(len(v) >= args.train_per_agent + args.test_per_agent for v in by_writer.values()): break eligible = [v for v in by_writer.values() if len(v) >= args.train_per_agent + args.test_per_agent][:want] if len(eligible) < want: raise RuntimeError(f"Only found {len(eligible)} eligible writers; need {want}") x_train = torch.tensor(np.stack([np.stack([a for a, _ in v[:args.train_per_agent]]) for v in eligible]), device=device) y_train = torch.tensor(np.stack([[b for _, b in v[:args.train_per_agent]] for v in eligible]), device=device, dtype=torch.long) x_test = torch.tensor(np.stack([np.stack([a for a, _ in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]]) for v in eligible]), device=device) y_test = torch.tensor(np.stack([[b for _, b in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]] for v in eligible]), device=device, dtype=torch.long) b_agents, n, raw_dim = x_train.shape[0], x_train.shape[1], 784 flat = x_train.reshape(b_agents, n, raw_dim) # Fixed random projection reduces the RFF input cost while retaining a reproducible vision proxy. g = torch.Generator(device=device).manual_seed(args.seed) proj = torch.randn((raw_dim, args.feature_dim), generator=g, device=device) / math.sqrt(raw_dim) features = flat @ proj phi_all = rff(features.reshape(-1, args.feature_dim), args.rff_dim, g, torch.ones(args.feature_dim, device=device)).reshape(b_agents, n, args.rff_dim) means = phi_all.mean(1) # Fit one regularized softmax classifier for each target using its personalized weights. rows = [] all_x = features.reshape(-1, args.feature_dim) all_y = y_train.reshape(-1) for target in range(b_agents): weights = simplex_weights(means, phi_all[target], steps=300) schemes = {"local": torch.nn.functional.one_hot(torch.tensor(target, device=device), b_agents).float(), "grandmean": torch.full((b_agents,), 1 / b_agents, device=device), "qaggregation": weights} test_feat = x_test[target].reshape(args.test_per_agent, raw_dim) @ proj for name, w in schemes.items(): model = torch.zeros((args.feature_dim, 62), device=device, requires_grad=True) opt = torch.optim.Adam([model], lr=args.lr, weight_decay=1e-4) sample_w = (w[:, None] / n).expand(b_agents, n).reshape(-1) for _ in range(args.epochs): opt.zero_grad() losses = torch.nn.functional.cross_entropy(all_x @ model, all_y, reduction="none") (losses * sample_w).sum().backward(); opt.step() acc = ((test_feat @ model).argmax(1) == y_test[target]).float().mean().item() rows.append({"agent": target, "method": name, "accuracy": acc, "q_local_weight": float(weights[target])}) return rows
def write_rows(rows: list[dict], out: Path) -> None: out.parent.mkdir(parents=True, exist_ok=True) with out.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader(); writer.writerows(rows) out.with_suffix(".json").write_text(json.dumps(rows, indent=2))
def main() -> None: p = argparse.ArgumentParser() p.add_argument("mode", choices=["concept", "rff", "femnist"]) p.add_argument("--output", type=Path, required=True) p.add_argument("--device", default="auto") p.add_argument("--seed", type=int, default=20260719) p.add_argument("--repeats", type=int, default=30) p.add_argument("--rff-dim", type=int, default=500) p.add_argument("--sigmas", type=float, nargs="+", default=[0., .1, .25, .5, .75, 1.]) p.add_argument("--rff-grid", type=int, nargs="+", default=[16, 32, 64, 128, 256, 512, 1024]) p.add_argument("--agents", type=int, default=192) p.add_argument("--train-per-agent", type=int, default=32) p.add_argument("--test-per-agent", type=int, default=16) p.add_argument("--feature-dim", type=int, default=64) p.add_argument("--epochs", type=int, default=20) p.add_argument("--lr", type=float, default=.08) args = p.parse_args() started = perf_counter() rows = {"concept": run_concept, "rff": run_rff, "femnist": run_femnist}[args.mode](args) write_rows(rows, args.output) if args.mode == "concept": summary = {str(s): {k: float(np.mean([r[k] for r in rows if r["sigma2"] == s])) for k in ["local_mse", "grandmean_mse", "oracle_mse", "qaggregation_mse", "q_local_weight", "q_same_group_weight"]} for s in args.sigmas} print(json.dumps({"concept_summary": summary}, indent=2)) elif args.mode == "rff": print(json.dumps({"rff_summary": {str(r["rff_dim"]): r["mean_abs_error"] for r in rows}}, indent=2)) elif args.mode == "femnist": summary = {m: float(np.mean([r["accuracy"] for r in rows if r["method"] == m])) for m in ["local", "grandmean", "qaggregation"]} print(json.dumps({"femnist_accuracy": summary}, indent=2)) print(json.dumps({"mode": args.mode, "rows": len(rows), "output": str(args.output), "seconds": round(perf_counter() - started, 2), "device": str(device_from_arg(args.device))}, indent=2))
if __name__ == "__main__": main()
````
````output{ "concept_summary": { "0.0": { "local_mse": 15.748318042755127, "grandmean_mse": 40.606961507797244, "oracle_mse": 2.0862513756752015, "qaggregation_mse": 17.83958231449127, "q_local_weight": 0.9771137142181396, "q_same_group_weight": 0.9975556522607804 }, "0.1": { "local_mse": 15.361917610168456, "grandmean_mse": 45.73134832382202, "oracle_mse": 6.119768922328949, "qaggregation_mse": 18.07122127532959, "q_local_weight": 0.9787336409091949, "q_same_group_weight": 0.9981670784950256 }, "0.25": { "local_mse": 15.827756361961365, "grandmean_mse": 39.008377923965455, "oracle_mse": 11.351614267826081, "qaggregation_mse": 25.339054584503174, "q_local_weight": 0.9825072956085205, "q_same_group_weight": 0.99599778175354 }, "0.5": { "local_mse": 14.459182372093201, "grandmean_mse": 45.512830362319946, "oracle_mse": 24.322485909461975, "qaggregation_mse": 25.430337595939637, "q_local_weight": 0.9876203048229217, "q_same_group_weight": 0.9948384702205658 }, "0.75": { "local_mse": 15.87236515045166, "grandmean_mse": 39.63199781417847, "oracle_mse": 30.853181953430177, "qaggregation_mse": 33.74232290267944, "q_local_weight": 0.9877495408058167, "q_same_group_weight": 0.9943676108121872 }, "1.0": { "local_mse": 15.390748682022094, "grandmean_mse": 39.16119129180908, "oracle_mse": 40.00151491165161, "qaggregation_mse": 30.293080587387085, "q_local_weight": 0.9896031093597412, "q_same_group_weight": 0.9947122848033905 } }}{ "mode": "concept", "rows": 600, "output": "outputs/concept_100agents_100reps.csv", "seconds": 299.14, "device": "cuda"}
````
---<!-- trackio-cell{"type": "artifact", "id": "cell_40a11b9e84e9", "created_at": "2026-07-19T09:50:42+00:00", "title": "Artifact: concept_100agents_100reps.csv", "path": "outputs/concept_100agents_100reps.csv", "size": 63718, "artifact_type": "dataset", "auto": true}-->**📦 Artifact** `outputs/concept_100agents_100reps.csv` · dataset · 63.7 kB
https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts#logbook-files/outputs/concept_100agents_100reps.csv
---<!-- trackio-cell{"type": "code", "id": "cell_09cae6dd6213", "created_at": "2026-07-19T09:51:35+00:00", "title": "Run: python reproduce.py (exit 0)", "command": ["/home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python", "src/reproduce.py", "--help"], "exit_code": 0, "duration_s": 0.941}-->````bash$ /home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python src/reproduce.py --help````
exit 0 · 0.9s
````python title=reproduce.py#!/usr/bin/env python3"""Independent, GPU-capable checks for Fermanian et al. (2026), arXiv:2603.02233.
The implementation follows Algorithms 1--2 at a scaled experimental budget. Ituses RFF KMEs to choose a target client's collaboration weights and fits theweighted empirical-risk minimizer exactly for linear regression. The FEMNISTmode uses the public natural writer partition and a linear softmax model."""from __future__ import annotations
import argparseimport csvimport jsonimport mathfrom pathlib import Pathfrom time import perf_counter
import numpy as npimport torch
ROOT = Path(__file__).resolve().parents[1]
def device_from_arg(name: str) -> torch.device: if name == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") return torch.device(name)
def rff(z: torch.Tensor, d_rff: int, generator: torch.Generator, scale: torch.Tensor) -> torch.Tensor: """Gaussian-kernel RFF, with a supplied coordinate rescaling.""" w = torch.randn((z.shape[1], d_rff), generator=generator, device=z.device, dtype=z.dtype) w = w * scale[:, None] b = 2 * math.pi * torch.rand((d_rff,), generator=generator, device=z.device, dtype=z.dtype) return math.sqrt(2.0 / d_rff) * torch.cos(z @ w + b)
def simplex_weights(means: torch.Tensor, target_phi: torch.Tensor, steps: int = 900) -> torch.Tensor: """Solve Algorithm 1's empirical Q-aggregation objective by projected GD.""" b_agents = means.shape[0] n1 = target_phi.shape[0] centered = target_phi - means[0] cov = centered.T @ centered / max(n1 - 1, 1) trace = torch.trace(cov) diffs = means[1:] - means[0] q_terms = torch.sqrt(torch.clamp(torch.einsum("bd,df,bf->b", diffs, cov, diffs), min=0.0) + 1e-12) p_terms = torch.linalg.vector_norm(diffs, dim=1) # Table 1 uses CQ^2=CP=log B: CQ=sqrt(log B), CP=log B. cq, cp = math.sqrt(math.log(b_agents)), math.log(b_agents) w = torch.full((b_agents,), 1.0 / b_agents, device=means.device, dtype=means.dtype) for _ in range(steps): w.requires_grad_(True) mixture = w @ means loss = torch.sum((mixture - means[0]) ** 2) + 2.0 * w[0] * trace / n1 loss = loss + cq / math.sqrt(n1) * torch.dot(w[1:], q_terms) loss = loss + cp / n1 * torch.dot(w[1:], p_terms) (grad,) = torch.autograd.grad(loss, w) with torch.no_grad(): # Euclidean projection on the simplex, Duchi et al. (2008). v = w - 0.04 * grad u, _ = torch.sort(v, descending=True) cssv = torch.cumsum(u, 0) - 1 ind = torch.arange(1, b_agents + 1, device=v.device, dtype=v.dtype) rho = torch.nonzero(u - cssv / ind > 0, as_tuple=False)[-1, 0] theta = cssv[rho] / (rho + 1) w = torch.clamp(v - theta, min=0) return w.detach()
def weighted_linear_fit(xs: torch.Tensor, ys: torch.Tensor, weights: torch.Tensor, ridge: float = 1e-3) -> torch.Tensor: """Exact weighted empirical-risk minimizer for linear regression.""" b_agents, n, dim = xs.shape x = torch.cat([xs, torch.ones((b_agents, n, 1), device=xs.device, dtype=xs.dtype)], dim=-1) sample_w = (weights[:, None] / n).expand(b_agents, n).reshape(-1) flat_x, flat_y = x.reshape(-1, dim + 1), ys.reshape(-1) lhs = flat_x.T @ (flat_x * sample_w[:, None]) + ridge * torch.eye(dim + 1, device=xs.device) rhs = flat_x.T @ (flat_y * sample_w) return torch.linalg.solve(lhs, rhs)
def concept_trial(seed: int, sigma2: float, d_rff: int, device: torch.device) -> dict: g = torch.Generator(device=device).manual_seed(seed) b_agents, n, dim, n_test = 100, 10, 20, 1000 signs = torch.where(torch.rand((b_agents,), generator=g, device=device) > .5, 1., -1.) beta0 = torch.randn((dim,), generator=g, device=device) eps = torch.randn((b_agents, dim), generator=g, device=device) betas = signs[:, None] * math.sqrt(1 - sigma2) * beta0 + math.sqrt(sigma2) * eps x = 1.0 + torch.randn((b_agents, n, dim), generator=g, device=device) y = torch.einsum("bnd,bd->bn", x, betas) + math.sqrt(2.0) * torch.randn((b_agents, n), generator=g, device=device) x_test = 1.0 + torch.randn((n_test, dim), generator=g, device=device) y_test = x_test @ betas[0] + math.sqrt(2.0) * torch.randn((n_test,), generator=g, device=device) # The paper's weighted Gaussian KME kernel gives X a 1/sqrt(d) scaling. z = torch.cat([x, y[..., None]], dim=-1).reshape(-1, dim + 1) scale = torch.cat([torch.full((dim,), 1 / math.sqrt(dim), device=device), torch.ones((1,), device=device)]) phi = rff(z, d_rff, g, scale).reshape(b_agents, n, d_rff) means = phi.mean(1) q_w = simplex_weights(means, phi[0]) local = torch.zeros(b_agents, device=device); local[0] = 1 grand = torch.full((b_agents,), 1 / b_agents, device=device) oracle = (signs == signs[0]).float(); oracle /= oracle.sum() result = {"sigma2": sigma2, "seed": seed, "q_local_weight": float(q_w[0]), "q_same_group_weight": float(q_w[signs == signs[0]].sum())} for name, weights in [("local", local), ("grandmean", grand), ("oracle", oracle), ("qaggregation", q_w)]: beta = weighted_linear_fit(x, y, weights) pred = x_test @ beta[:-1] + beta[-1] result[f"{name}_mse"] = float(torch.mean((pred - y_test) ** 2)) return result
def run_concept(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) rows = [] for sigma2 in args.sigmas: for rep in range(args.repeats): rows.append(concept_trial(args.seed + rep * 101 + int(sigma2 * 1000), sigma2, args.rff_dim, device)) return rows
def exact_rbf_mmd(x: torch.Tensor, y: torch.Tensor, bandwidth: float = 1.0) -> torch.Tensor: def k(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: return torch.exp(-torch.cdist(a, b).square() / (2 * bandwidth * bandwidth)) return torch.sqrt(torch.clamp(k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean(), min=0.0))
def run_rff(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) g = torch.Generator(device=device).manual_seed(args.seed) x = torch.randn((300, 8), generator=g, device=device) y = torch.randn((300, 8), generator=g, device=device) + torch.tensor([0.35] + [0.] * 7, device=device) exact = float(exact_rbf_mmd(x, y)) rows = [] for d_rff in args.rff_grid: errors = [] for trial in range(args.repeats): tg = torch.Generator(device=device).manual_seed(args.seed + 1000 * d_rff + trial) phi = rff(torch.cat([x, y]), d_rff, tg, torch.ones(8, device=device)) approx = torch.linalg.vector_norm(phi[:len(x)].mean(0) - phi[len(x):].mean(0)).item() errors.append(abs(approx - exact)) rows.append({"rff_dim": d_rff, "exact_mmd": exact, "mean_abs_error": float(np.mean(errors)), "std_abs_error": float(np.std(errors)), "sqrt_logB_over_D": math.sqrt(math.log(100) / d_rff), "one_shot_floats_per_agent": d_rff}) return rows
def run_femnist(args: argparse.Namespace) -> list[dict]: """Actual FEMNIST writer data, deliberately scaled in samples/features/epochs.""" from datasets import load_dataset device = device_from_arg(args.device) local_parquet = ROOT / "data" / "femnist" / "data" / "train-00000-of-00001.parquet" dataset = load_dataset("parquet", data_files=str(local_parquet), split="train", streaming=True) if local_parquet.exists() else load_dataset("flwrlabs/femnist", split="train", streaming=True) by_writer: dict[str, list[tuple[np.ndarray, int]]] = {} want = args.agents for ex in dataset: writer = ex["writer_id"] if writer not in by_writer and len(by_writer) >= want: continue if writer in by_writer or len(by_writer) < want: by_writer.setdefault(writer, []).append((np.asarray(ex["image"], dtype=np.float32) / 255., int(ex["character"]))) if len(by_writer) >= want and all(len(v) >= args.train_per_agent + args.test_per_agent for v in by_writer.values()): break eligible = [v for v in by_writer.values() if len(v) >= args.train_per_agent + args.test_per_agent][:want] if len(eligible) < want: raise RuntimeError(f"Only found {len(eligible)} eligible writers; need {want}") x_train = torch.tensor(np.stack([np.stack([a for a, _ in v[:args.train_per_agent]]) for v in eligible]), device=device) y_train = torch.tensor(np.stack([[b for _, b in v[:args.train_per_agent]] for v in eligible]), device=device, dtype=torch.long) x_test = torch.tensor(np.stack([np.stack([a for a, _ in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]]) for v in eligible]), device=device) y_test = torch.tensor(np.stack([[b for _, b in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]] for v in eligible]), device=device, dtype=torch.long) b_agents, n, raw_dim = x_train.shape[0], x_train.shape[1], 784 flat = x_train.reshape(b_agents, n, raw_dim) # Fixed random projection reduces the RFF input cost while retaining a reproducible vision proxy. g = torch.Generator(device=device).manual_seed(args.seed) proj = torch.randn((raw_dim, args.feature_dim), generator=g, device=device) / math.sqrt(raw_dim) features = flat @ proj phi_all = rff(features.reshape(-1, args.feature_dim), args.rff_dim, g, torch.ones(args.feature_dim, device=device)).reshape(b_agents, n, args.rff_dim) means = phi_all.mean(1) # Fit one regularized softmax classifier for each target using its personalized weights. rows = [] all_x = features.reshape(-1, args.feature_dim) all_y = y_train.reshape(-1) for target in range(b_agents): weights = simplex_weights(means, phi_all[target], steps=300) schemes = {"local": torch.nn.functional.one_hot(torch.tensor(target, device=device), b_agents).float(), "grandmean": torch.full((b_agents,), 1 / b_agents, device=device), "qaggregation": weights} test_feat = x_test[target].reshape(args.test_per_agent, raw_dim) @ proj for name, w in schemes.items(): model = torch.zeros((args.feature_dim, 62), device=device, requires_grad=True) opt = torch.optim.Adam([model], lr=args.lr, weight_decay=1e-4) sample_w = (w[:, None] / n).expand(b_agents, n).reshape(-1) for _ in range(args.epochs): opt.zero_grad() losses = torch.nn.functional.cross_entropy(all_x @ model, all_y, reduction="none") (losses * sample_w).sum().backward(); opt.step() acc = ((test_feat @ model).argmax(1) == y_test[target]).float().mean().item() rows.append({"agent": target, "method": name, "accuracy": acc, "q_local_weight": float(weights[target])}) return rows
def write_rows(rows: list[dict], out: Path) -> None: out.parent.mkdir(parents=True, exist_ok=True) with out.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader(); writer.writerows(rows) out.with_suffix(".json").write_text(json.dumps(rows, indent=2))
def main() -> None: p = argparse.ArgumentParser() p.add_argument("mode", choices=["concept", "rff", "femnist"]) p.add_argument("--output", type=Path, required=True) p.add_argument("--device", default="auto") p.add_argument("--seed", type=int, default=20260719) p.add_argument("--repeats", type=int, default=30) p.add_argument("--rff-dim", type=int, default=500) p.add_argument("--sigmas", type=float, nargs="+", default=[0., .1, .25, .5, .75, 1.]) p.add_argument("--rff-grid", type=int, nargs="+", default=[16, 32, 64, 128, 256, 512, 1024]) p.add_argument("--agents", type=int, default=192) p.add_argument("--train-per-agent", type=int, default=32) p.add_argument("--test-per-agent", type=int, default=16) p.add_argument("--feature-dim", type=int, default=64) p.add_argument("--epochs", type=int, default=20) p.add_argument("--lr", type=float, default=.08) args = p.parse_args() started = perf_counter() rows = {"concept": run_concept, "rff": run_rff, "femnist": run_femnist}[args.mode](args) write_rows(rows, args.output) if args.mode == "concept": summary = {str(s): {k: float(np.mean([r[k] for r in rows if r["sigma2"] == s])) for k in ["local_mse", "grandmean_mse", "oracle_mse", "qaggregation_mse", "q_local_weight", "q_same_group_weight"]} for s in args.sigmas} print(json.dumps({"concept_summary": summary}, indent=2)) elif args.mode == "rff": print(json.dumps({"rff_summary": {str(r["rff_dim"]): r["mean_abs_error"] for r in rows}}, indent=2)) elif args.mode == "femnist": summary = {m: float(np.mean([r["accuracy"] for r in rows if r["method"] == m])) for m in ["local", "grandmean", "qaggregation"]} print(json.dumps({"femnist_accuracy": summary}, indent=2)) print(json.dumps({"mode": args.mode, "rows": len(rows), "output": str(args.output), "seconds": round(perf_counter() - started, 2), "device": str(device_from_arg(args.device))}, indent=2))
if __name__ == "__main__": main()
````
````outputusage: reproduce.py [-h] --output OUTPUT [--device DEVICE] [--seed SEED] [--repeats REPEATS] [--rff-dim RFF_DIM] [--sigmas SIGMAS [SIGMAS ...]] [--rff-grid RFF_GRID [RFF_GRID ...]] [--agents AGENTS] [--train-per-agent TRAIN_PER_AGENT] [--test-per-agent TEST_PER_AGENT] [--feature-dim FEATURE_DIM] [--epochs EPOCHS] [--lr LR] {concept,rff,femnist}
positional arguments: {concept,rff,femnist}
options: -h, --help show this help message and exit --output OUTPUT --device DEVICE --seed SEED --repeats REPEATS --rff-dim RFF_DIM --sigmas SIGMAS [SIGMAS ...] --rff-grid RFF_GRID [RFF_GRID ...] --agents AGENTS --train-per-agent TRAIN_PER_AGENT --test-per-agent TEST_PER_AGENT --feature-dim FEATURE_DIM --epochs EPOCHS --lr LR
````
---<!-- trackio-cell{"type": "markdown", "id": "cell_8356b325c920", "created_at": "2026-07-19T09:54:23+00:00", "title": "Evidence and status"}-->Independent CUDA reproduction used the paper’s , , , noise variance 2, , and 100 repetitions ([paper](https://arxiv.org/pdf/2603.02233), Sec. 6.1/Table 1). It uses an independent projected-gradient implementation of Algorithm 1 and exact weighted linear-risk minimization. Contrary to the paper’s transition claim, its Q weights remained almost local (mean target weight 0.977–0.990) and Q MSE was worse than Local at all tested (e.g. 17.84 vs 15.75 at 0; 25.43 vs 14.46 at .5). **Status: not reproduced by this independent implementation.** The full configuration, CUDA run, and CSV are captured here; no official code was found.
---<!-- trackio-cell{"type": "markdown", "id": "cell_4a35924ff734", "created_at": "2026-07-19T09:57:06+00:00", "title": "Clarified evidence"}-->Clarification of measured scope: B=100, n=10/client, d=20, noise variance 2, D=500, 100 repetitions, CUDA. Q target weight was 0.977 to 0.990 across sigma_c squared values and Q MSE was worse than local at every tested value. This independent literal implementation does not reproduce the reported transition; it is not presented as a refutation because official code was unavailable.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298# Claim 6: Section 6.3 FEMNIST 192-agent benchmark
---<!-- trackio-cell{"type": "markdown", "id": "cell_80ab313b85c0", "created_at": "2026-07-19T09:32:03+00:00", "title": "Claim 6: Section 6.3 FEMNIST 192-agent benchmark"}-->Document setup, runs, and results for **Claim 6: Section 6.3 FEMNIST 192-agent benchmark**.
---<!-- trackio-cell{"type": "code", "id": "cell_5675f10a2abb", "created_at": "2026-07-19T09:52:42+00:00", "title": "Run: env reproduce.py (exit 0)", "command": ["env", "CUDA_VISIBLE_DEVICES=1", "/home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python", "src/reproduce.py", "femnist", "--agents", "192", "--train-per-agent", "32", "--test-per-agent", "16", "--feature-dim", "64", "--rff-dim", "1000", "--epochs", "20", "--lr", "0.08", "--output", "outputs/femnist_192agents_scaled.csv", "--device", "cuda"], "exit_code": 0, "duration_s": 33.426}-->````bash$ env CUDA_VISIBLE_DEVICES=1 /home/vim/miniconda3/envs/pytorch-gpu-hf/bin/python src/reproduce.py femnist --agents 192 --train-per-agent 32 --test-per-agent 16 --feature-dim 64 --rff-dim 1000 --epochs 20 --lr 0.08 --output outputs/femnist_192agents_scaled.csv --device cuda````
exit 0 · 33.4s
````python title=reproduce.py#!/usr/bin/env python3"""Independent, GPU-capable checks for Fermanian et al. (2026), arXiv:2603.02233.
The implementation follows Algorithms 1--2 at a scaled experimental budget. Ituses RFF KMEs to choose a target client's collaboration weights and fits theweighted empirical-risk minimizer exactly for linear regression. The FEMNISTmode uses the public natural writer partition and a linear softmax model."""from __future__ import annotations
import argparseimport csvimport jsonimport mathfrom pathlib import Pathfrom time import perf_counter
import numpy as npimport torch
ROOT = Path(__file__).resolve().parents[1]
def device_from_arg(name: str) -> torch.device: if name == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") return torch.device(name)
def rff(z: torch.Tensor, d_rff: int, generator: torch.Generator, scale: torch.Tensor) -> torch.Tensor: """Gaussian-kernel RFF, with a supplied coordinate rescaling.""" w = torch.randn((z.shape[1], d_rff), generator=generator, device=z.device, dtype=z.dtype) w = w * scale[:, None] b = 2 * math.pi * torch.rand((d_rff,), generator=generator, device=z.device, dtype=z.dtype) return math.sqrt(2.0 / d_rff) * torch.cos(z @ w + b)
def simplex_weights(means: torch.Tensor, target_phi: torch.Tensor, steps: int = 900) -> torch.Tensor: """Solve Algorithm 1's empirical Q-aggregation objective by projected GD.""" b_agents = means.shape[0] n1 = target_phi.shape[0] centered = target_phi - means[0] cov = centered.T @ centered / max(n1 - 1, 1) trace = torch.trace(cov) diffs = means[1:] - means[0] q_terms = torch.sqrt(torch.clamp(torch.einsum("bd,df,bf->b", diffs, cov, diffs), min=0.0) + 1e-12) p_terms = torch.linalg.vector_norm(diffs, dim=1) # Table 1 uses CQ^2=CP=log B: CQ=sqrt(log B), CP=log B. cq, cp = math.sqrt(math.log(b_agents)), math.log(b_agents) w = torch.full((b_agents,), 1.0 / b_agents, device=means.device, dtype=means.dtype) for _ in range(steps): w.requires_grad_(True) mixture = w @ means loss = torch.sum((mixture - means[0]) ** 2) + 2.0 * w[0] * trace / n1 loss = loss + cq / math.sqrt(n1) * torch.dot(w[1:], q_terms) loss = loss + cp / n1 * torch.dot(w[1:], p_terms) (grad,) = torch.autograd.grad(loss, w) with torch.no_grad(): # Euclidean projection on the simplex, Duchi et al. (2008). v = w - 0.04 * grad u, _ = torch.sort(v, descending=True) cssv = torch.cumsum(u, 0) - 1 ind = torch.arange(1, b_agents + 1, device=v.device, dtype=v.dtype) rho = torch.nonzero(u - cssv / ind > 0, as_tuple=False)[-1, 0] theta = cssv[rho] / (rho + 1) w = torch.clamp(v - theta, min=0) return w.detach()
def weighted_linear_fit(xs: torch.Tensor, ys: torch.Tensor, weights: torch.Tensor, ridge: float = 1e-3) -> torch.Tensor: """Exact weighted empirical-risk minimizer for linear regression.""" b_agents, n, dim = xs.shape x = torch.cat([xs, torch.ones((b_agents, n, 1), device=xs.device, dtype=xs.dtype)], dim=-1) sample_w = (weights[:, None] / n).expand(b_agents, n).reshape(-1) flat_x, flat_y = x.reshape(-1, dim + 1), ys.reshape(-1) lhs = flat_x.T @ (flat_x * sample_w[:, None]) + ridge * torch.eye(dim + 1, device=xs.device) rhs = flat_x.T @ (flat_y * sample_w) return torch.linalg.solve(lhs, rhs)
def concept_trial(seed: int, sigma2: float, d_rff: int, device: torch.device) -> dict: g = torch.Generator(device=device).manual_seed(seed) b_agents, n, dim, n_test = 100, 10, 20, 1000 signs = torch.where(torch.rand((b_agents,), generator=g, device=device) > .5, 1., -1.) beta0 = torch.randn((dim,), generator=g, device=device) eps = torch.randn((b_agents, dim), generator=g, device=device) betas = signs[:, None] * math.sqrt(1 - sigma2) * beta0 + math.sqrt(sigma2) * eps x = 1.0 + torch.randn((b_agents, n, dim), generator=g, device=device) y = torch.einsum("bnd,bd->bn", x, betas) + math.sqrt(2.0) * torch.randn((b_agents, n), generator=g, device=device) x_test = 1.0 + torch.randn((n_test, dim), generator=g, device=device) y_test = x_test @ betas[0] + math.sqrt(2.0) * torch.randn((n_test,), generator=g, device=device) # The paper's weighted Gaussian KME kernel gives X a 1/sqrt(d) scaling. z = torch.cat([x, y[..., None]], dim=-1).reshape(-1, dim + 1) scale = torch.cat([torch.full((dim,), 1 / math.sqrt(dim), device=device), torch.ones((1,), device=device)]) phi = rff(z, d_rff, g, scale).reshape(b_agents, n, d_rff) means = phi.mean(1) q_w = simplex_weights(means, phi[0]) local = torch.zeros(b_agents, device=device); local[0] = 1 grand = torch.full((b_agents,), 1 / b_agents, device=device) oracle = (signs == signs[0]).float(); oracle /= oracle.sum() result = {"sigma2": sigma2, "seed": seed, "q_local_weight": float(q_w[0]), "q_same_group_weight": float(q_w[signs == signs[0]].sum())} for name, weights in [("local", local), ("grandmean", grand), ("oracle", oracle), ("qaggregation", q_w)]: beta = weighted_linear_fit(x, y, weights) pred = x_test @ beta[:-1] + beta[-1] result[f"{name}_mse"] = float(torch.mean((pred - y_test) ** 2)) return result
def run_concept(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) rows = [] for sigma2 in args.sigmas: for rep in range(args.repeats): rows.append(concept_trial(args.seed + rep * 101 + int(sigma2 * 1000), sigma2, args.rff_dim, device)) return rows
def exact_rbf_mmd(x: torch.Tensor, y: torch.Tensor, bandwidth: float = 1.0) -> torch.Tensor: def k(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: return torch.exp(-torch.cdist(a, b).square() / (2 * bandwidth * bandwidth)) return torch.sqrt(torch.clamp(k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean(), min=0.0))
def run_rff(args: argparse.Namespace) -> list[dict]: device = device_from_arg(args.device) g = torch.Generator(device=device).manual_seed(args.seed) x = torch.randn((300, 8), generator=g, device=device) y = torch.randn((300, 8), generator=g, device=device) + torch.tensor([0.35] + [0.] * 7, device=device) exact = float(exact_rbf_mmd(x, y)) rows = [] for d_rff in args.rff_grid: errors = [] for trial in range(args.repeats): tg = torch.Generator(device=device).manual_seed(args.seed + 1000 * d_rff + trial) phi = rff(torch.cat([x, y]), d_rff, tg, torch.ones(8, device=device)) approx = torch.linalg.vector_norm(phi[:len(x)].mean(0) - phi[len(x):].mean(0)).item() errors.append(abs(approx - exact)) rows.append({"rff_dim": d_rff, "exact_mmd": exact, "mean_abs_error": float(np.mean(errors)), "std_abs_error": float(np.std(errors)), "sqrt_logB_over_D": math.sqrt(math.log(100) / d_rff), "one_shot_floats_per_agent": d_rff}) return rows
def run_femnist(args: argparse.Namespace) -> list[dict]: """Actual FEMNIST writer data, deliberately scaled in samples/features/epochs.""" from datasets import load_dataset device = device_from_arg(args.device) local_parquet = ROOT / "data" / "femnist" / "data" / "train-00000-of-00001.parquet" dataset = load_dataset("parquet", data_files=str(local_parquet), split="train", streaming=True) if local_parquet.exists() else load_dataset("flwrlabs/femnist", split="train", streaming=True) by_writer: dict[str, list[tuple[np.ndarray, int]]] = {} want = args.agents for ex in dataset: writer = ex["writer_id"] if writer not in by_writer and len(by_writer) >= want: continue if writer in by_writer or len(by_writer) < want: by_writer.setdefault(writer, []).append((np.asarray(ex["image"], dtype=np.float32) / 255., int(ex["character"]))) if len(by_writer) >= want and all(len(v) >= args.train_per_agent + args.test_per_agent for v in by_writer.values()): break eligible = [v for v in by_writer.values() if len(v) >= args.train_per_agent + args.test_per_agent][:want] if len(eligible) < want: raise RuntimeError(f"Only found {len(eligible)} eligible writers; need {want}") x_train = torch.tensor(np.stack([np.stack([a for a, _ in v[:args.train_per_agent]]) for v in eligible]), device=device) y_train = torch.tensor(np.stack([[b for _, b in v[:args.train_per_agent]] for v in eligible]), device=device, dtype=torch.long) x_test = torch.tensor(np.stack([np.stack([a for a, _ in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]]) for v in eligible]), device=device) y_test = torch.tensor(np.stack([[b for _, b in v[args.train_per_agent:args.train_per_agent + args.test_per_agent]] for v in eligible]), device=device, dtype=torch.long) b_agents, n, raw_dim = x_train.shape[0], x_train.shape[1], 784 flat = x_train.reshape(b_agents, n, raw_dim) # Fixed random projection reduces the RFF input cost while retaining a reproducible vision proxy. g = torch.Generator(device=device).manual_seed(args.seed) proj = torch.randn((raw_dim, args.feature_dim), generator=g, device=device) / math.sqrt(raw_dim) features = flat @ proj phi_all = rff(features.reshape(-1, args.feature_dim), args.rff_dim, g, torch.ones(args.feature_dim, device=device)).reshape(b_agents, n, args.rff_dim) means = phi_all.mean(1) # Fit one regularized softmax classifier for each target using its personalized weights. rows = [] all_x = features.reshape(-1, args.feature_dim) all_y = y_train.reshape(-1) for target in range(b_agents): weights = simplex_weights(means, phi_all[target], steps=300) schemes = {"local": torch.nn.functional.one_hot(torch.tensor(target, device=device), b_agents).float(), "grandmean": torch.full((b_agents,), 1 / b_agents, device=device), "qaggregation": weights} test_feat = x_test[target].reshape(args.test_per_agent, raw_dim) @ proj for name, w in schemes.items(): model = torch.zeros((args.feature_dim, 62), device=device, requires_grad=True) opt = torch.optim.Adam([model], lr=args.lr, weight_decay=1e-4) sample_w = (w[:, None] / n).expand(b_agents, n).reshape(-1) for _ in range(args.epochs): opt.zero_grad() losses = torch.nn.functional.cross_entropy(all_x @ model, all_y, reduction="none") (losses * sample_w).sum().backward(); opt.step() acc = ((test_feat @ model).argmax(1) == y_test[target]).float().mean().item() rows.append({"agent": target, "method": name, "accuracy": acc, "q_local_weight": float(weights[target])}) return rows
def write_rows(rows: list[dict], out: Path) -> None: out.parent.mkdir(parents=True, exist_ok=True) with out.open("w", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader(); writer.writerows(rows) out.with_suffix(".json").write_text(json.dumps(rows, indent=2))
def main() -> None: p = argparse.ArgumentParser() p.add_argument("mode", choices=["concept", "rff", "femnist"]) p.add_argument("--output", type=Path, required=True) p.add_argument("--device", default="auto") p.add_argument("--seed", type=int, default=20260719) p.add_argument("--repeats", type=int, default=30) p.add_argument("--rff-dim", type=int, default=500) p.add_argument("--sigmas", type=float, nargs="+", default=[0., .1, .25, .5, .75, 1.]) p.add_argument("--rff-grid", type=int, nargs="+", default=[16, 32, 64, 128, 256, 512, 1024]) p.add_argument("--agents", type=int, default=192) p.add_argument("--train-per-agent", type=int, default=32) p.add_argument("--test-per-agent", type=int, default=16) p.add_argument("--feature-dim", type=int, default=64) p.add_argument("--epochs", type=int, default=20) p.add_argument("--lr", type=float, default=.08) args = p.parse_args() started = perf_counter() rows = {"concept": run_concept, "rff": run_rff, "femnist": run_femnist}[args.mode](args) write_rows(rows, args.output) if args.mode == "concept": summary = {str(s): {k: float(np.mean([r[k] for r in rows if r["sigma2"] == s])) for k in ["local_mse", "grandmean_mse", "oracle_mse", "qaggregation_mse", "q_local_weight", "q_same_group_weight"]} for s in args.sigmas} print(json.dumps({"concept_summary": summary}, indent=2)) elif args.mode == "rff": print(json.dumps({"rff_summary": {str(r["rff_dim"]): r["mean_abs_error"] for r in rows}}, indent=2)) elif args.mode == "femnist": summary = {m: float(np.mean([r["accuracy"] for r in rows if r["method"] == m])) for m in ["local", "grandmean", "qaggregation"]} print(json.dumps({"femnist_accuracy": summary}, indent=2)) print(json.dumps({"mode": args.mode, "rows": len(rows), "output": str(args.output), "seconds": round(perf_counter() - started, 2), "device": str(device_from_arg(args.device))}, indent=2))
if __name__ == "__main__": main()
````
````output{ "femnist_accuracy": { "local": 0.2503255208333333, "grandmean": 0.24283854166666666, "qaggregation": 0.17578125 }}{ "mode": "femnist", "rows": 576, "output": "outputs/femnist_192agents_scaled.csv", "seconds": 32.19, "device": "cuda"}
````
---<!-- trackio-cell{"type": "artifact", "id": "cell_a404932005b6", "created_at": "2026-07-19T09:52:42+00:00", "title": "Artifact: femnist_192agents_scaled.csv", "path": "outputs/femnist_192agents_scaled.csv", "size": 14226, "artifact_type": "dataset", "auto": true}-->**�� Artifact** `outputs/femnist_192agents_scaled.csv` · dataset · 14.2 kB
https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts#logbook-files/outputs/femnist_192agents_scaled.csv
---<!-- trackio-cell{"type": "markdown", "id": "cell_87c9b71c7614", "created_at": "2026-07-19T09:57:23+00:00", "title": "Clarified evidence"}-->Actual public dataset: https://huggingface.co/datasets/flwrlabs/femnist . Scope: 192 natural writer partitions, D=1000, CUDA; scaled to 32 train and 16 test examples/writer, 64 projected features, and 20 linear-softmax epochs. Mean accuracy: local 0.2503, grand mean 0.2428, Q aggregation 0.1758. The full paper MLP uses 2000 epochs, so this is a non-reproducing scaled check, not a full replication.12345678910111213141516171819# Conclusion
---<!-- trackio-cell{"type": "markdown", "id": "cell_5ef64984e3ab", "created_at": "2026-07-19T09:32:03+00:00", "title": "Reproduction bundle"}-->The reproduction bundle contains the independent GPU-capable implementation, CSV results, rendered Posterly artifact, gate report, and rerun instructions. It excludes local caches and the replaceable FEMNIST Parquet download.
After publication, download the bundle from the artifact cell, open `README.md`, and run its CUDA commands. Public data source: https://huggingface.co/datasets/flwrlabs/femnist .
---<!-- trackio-cell{"type": "artifact", "id": "cell_175c3d4d70bd", "created_at": "2026-07-19T10:07:56+00:00", "title": "Reproduction bundle", "artifact": "repro-adaptive-personalized-federated-learning-via-multi-task-averaging-of-kernel-mean-embedding/repro-bundle:v0", "artifact_type": "dataset"}-->**📦 Artifact** `repro-adaptive-personalized-federated-learning-via-multi-task-averaging-of-kernel-mean-embedding/repro-bundle:v0` · dataset
https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts#repro-adaptive-personalized-federated-learning-via-multi-task-averaging-of-kernel-mean-embedding/repro-bundle:v012345678910111213141516# Reproduction: Adaptive Personalized Federated Learning via Multi-task Averaging of Kernel Mean Embeddings
[OpenReview paper](https://openreview.net/forum?id=ADHGbxsREr)
## Pages
| Page || --- || [Executive summary](#/executive-summary) || [Claim 1: Theorem 4.4 finite-sample KME guarantee](#/claim-1-theorem-4-4-finite-sample-kme-guarantee) || [Claim 2: Corollary 4.6 downstream excess-risk transfer](#/claim-2-corollary-4-6-downstream-excess-risk-transfer) || [Claim 3: Example 4.5 automatic adaptive collaboration](#/claim-3-example-4-5-automatic-adaptive-collaboration) || [Claim 4: Theorem 5.2 random Fourier-feature tradeoff](#/claim-4-theorem-5-2-random-fourier-feature-tradeoff) || [Claim 5: Section 6.1 100-agent synthetic concept shift](#/claim-5-section-6-1-100-agent-synthetic-concept-shift) || [Claim 6: Section 6.3 FEMNIST 192-agent benchmark](#/claim-6-section-6-3-femnist-192-agent-benchmark) || [Conclusion](#/conclusion) |1234567891011121314151617181920212223242526272829{ "schema_version": 1, "file_count": 0, "total_size": 0, "files": [], "hub_refs": [ { "url": "https://huggingface.co/jobs/vimarsh/6a5c9e7cbee6ee1cf4ed0df8", "type": "Jobs", "label": "vimarsh/6a5c9e7cbee6ee1cf4ed0df8" }, { "url": "https://huggingface.co/buckets/vimarsh/jobs-artifacts", "type": "Buckets", "label": "vimarsh/jobs-artifacts" }, { "url": "https://huggingface.co/buckets/vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts#logbook-files/outputs/rff_tradeoff_100seeds.csv", "type": "Buckets", "label": "vimarsh/repro-adaptive-personalized-fl-multi-task-averaging-kernel-mean-embedding-artifacts" }, { "url": "https://huggingface.co/datasets/flwrlabs/femnist", "type": "Datasets", "label": "flwrlabs/femnist" } ], "reference_only": true}README.md+14-5
bucket-icon.svgAdded
index.html+82-17
logbook.cssAdded+2142
logbook.jsAdded
logbook.jsonAdded+87
pages/claim-1-theorem-4-4-finite-sample-kme-guarantee/page.mdAdded+22
pages/claim-2-corollary-4-6-downstream-excess-risk-transfer/page.mdAdded+22
pages/claim-3-example-4-5-automatic-adaptive-collaboration/page.mdAdded+22
pages/claim-4-theorem-5-2-random-fourier-feature-tradeoff/page.mdAdded+302
pages/claim-5-section-6-1-100-agent-synthetic-concept-shift/page.mdAdded+1310
pages/claim-6-section-6-3-femnist-192-agent-benchmark/page.mdAdded+298
pages/conclusion/page.mdAdded+19
pages/executive-summary/page.mdAdded
pages/index.mdAdded+16
trackio-logo-light.pngAdded

trackio-logo.pngAdded

trackio-wordmark-dark.pngAdded

workspace.jsonAdded+29