EvoSec-TorchTPU: 317 Faster Byzantine-Resilient FL & Privacy Kernels on Cloud TPU v6e
Most PyTorch security and privacy libraries were written for CPUs and GPUs, relying on dynamic boolean masking (updates[mask]), greedy Python loops, and ragged per-layer tensor slices. When we ported our IEEE CCNC 2027
Most PyTorch security and privacy libraries were written for CPUs and GPUs, relying on dynamic boolean masking (updates[mask]), greedy Python loops, and ragged per-layer tensor slices.
When we ported our IEEE CCNC 2027 Federated Learning defense research (Evo-FedAgg) onto a live Google Cloud TPU v6e-1 (torch-tpu==0.3.0) for TorchTPU Sprint 2026 (#TorchTPUSprint), naive PyTorch security code didn't just run slowly—it crashed on unimplemented ops, stalled for 55 seconds compiling, suffered 99.73% bfloat16 distance error, and exploded small Differential Privacy gradients by 1,256×!
In this tutorial, we walk through the whole journey from first principles—no prior Federated Learning or TPU compiler background required:
- Introduction: What Federated Learning, Byzantine-Resilient Aggregation, and Differential Privacy actually are (and why they matter).
-
What We Evolved with AlphaEvolve: The exact 3-line defenseless Python seed we started from, how live Google Cloud AlphaEvolve (
gemini-4-argon) mutated it, and the two champion algorithms it discovered (+108.5%and+100.3%gains). -
7 Things That Broke on Cloud TPU
v6e-1(torch-tpu 0.3.0) and the exact static-shape PyTorch fixes. -
How We Benchmarked Everything: 4 TorchTPU execution modes + a custom Pallas VMEM kernel (
@torch.tpu.pallas.jax_op) hitting0.306 ms(316.8×faster than Multi-Krum,583K clients/secatN=512). -
The XProf Plot Twist: Reading real XLA HLO hardware traces to see why
torch.compile(backend="tpu")beat our first-pass Pallas kernel pastd = 512K. -
1-Click Colab (
v6e-1) + Gemma 4 E4B: Run the full suite and live on-TPU adversarial co-evolution yourself.
Open-Source Repo & 1-Click Colab (
v6e-1TPU):
- GitHub: https://github.com/Unisvet/evosec-torchtpu
- Colab Notebook: Open EvoSec_TorchTPU_Sprint_2026.ipynb in Colab
1. Intro: Federated Learning, Byzantine Attacks & Privacy
If you've never worked on distributed AI security before, here is the 60-second intuition:
What is Federated Learning (FL)?
Imagine 200 hospitals, smartphones, or edge IoT sensors that want to train one shared AI model together—without ever uploading their private raw data to the cloud.
- Every round, each device trains locally on its own private data and computes a model update (a flat vector of
dnumbers showing which direction to nudge the shared model's weights). - All
Ndevices send only their update vectorsU(a matrix of shape[N, d]) to a central aggregator. - The aggregator combines them into one clean global update—usually by taking a simple average (FedAvg).
What does "Byzantine-Resilient" mean?
Because the central server never sees the raw local data, it cannot verify whether a device is telling the truth. What if 30%–40% of the devices are hacked, broken, or actively malicious?
- Gaussian Noise Storm: Rogue nodes blast huge random numbers that drown out the average.
- Sign-Flip ("Flipped Compass"): Rogue nodes send the exact opposite of the true gradient to push the model backwards.
- Sybil Gang ("Fake Choir"): Hacked nodes collude and send identical poisoned vectors to outvote honest devices.
- ALIE & Orthogonal-Projection Stealth: Subtle attackers hide inside the statistical variance of honest updates—or inject poison orthogonal to the current global model direction—so simple distance or norm filters miss them!
A Byzantine-resilient aggregator acts like a mathematical Maxwell's Demon: using only the geometry of the N update vectors, it spots and discards the saboteurs while preserving honest diverse voices.
What about Gradient Privacy (DLG Attacks)?
Even if all devices are honest, a curious server can run a Deep Leakage from Gradients (DLG / iDLG) attack—inverting a client's shared gradient vector back into their private training image! Adding Differential Privacy (DP) noise blocks this inversion, but naive uniform DP-SGD destroys training accuracy. We want high reconstruction MSE (attacker fails to recover the image) and high gradient cosine similarity (model still learns accurately).
2. What Code Did We Evolve with Live AlphaEvolve?
Instead of hand-tuning brittle defense heuristics, we used Google Cloud AlphaEvolve (ae 0.2.8, powered by gemini-4-argon) to evolve pure Python/NumPy defense algorithms offline, guided by a multi-objective fitness judge.
Experiment 1 (evo_fedagg_tpu): Evolving a Byzantine Aggregator from Zero Defense Hints
We started AlphaEvolve from a 3-line, completely defenseless FedAvg seed (prog-cream-silkworm, score 94.55 / 200):
# Seed G0 (defenseless baseline fed to AlphaEvolve — zero defense hints!)
def aggregate_updates(updates, weights, global_model, alpha=0.30):
w = weights / (np.sum(weights) + 1e-12)
return np.sum(updates * w[:, None], axis=0)
Every time AlphaEvolve proposed a mutated Python function, our automated evaluator graded it across 5 tough criteria:
- Clean Accuracy (don't hurt learning when nobody is attacking).
- Classic Byzantine Arena (Gaussian noise, Sign-Flip, and Sybil gangs at 30% corruption).
- Stealth Arena (ALIE variance-hiding + targeted Orthogonal-Projection Stealth attacks).
-
bfloat16Numerical Stability (simulating Cloud TPUbf16rounding & cancellation). -
TPU Static-Shape AST Audit + Speed Timer (automatically penalizing Python loops over
Nand dynamic boolean indexing likeupdates[mask]that break XLA compilation!).
Across 30 successful evaluations (exp-vigorous-crayfish), AlphaEvolve climbed from 94.55 → 197.16 / 200 (+108.5%) and invented champion prog-deft-cuscus:
-
Attack error dropped from
10.3813→0.0005on classic attacks,0.0005on ALIE,0.0005on orthogonal-projection stealth, and9.2973→0.0007underbfloat16! -
The TPU-friendly mathematical trick AlphaEvolve invented: Naive orthogonal-subspace detectors project every client vector onto the subspace perpendicular to the global model
g_hatand compute a second expensiveO(N²·d)matrix multiply. Instead,prog-deft-cuscuscomputes the Gram matrixG = U @ U.Tonce on thebf16MXU, and derives all orthogonal-subspace distances purely via exactO(N²)rank-1 updates:
p[i] = dot(u[i], g_hat) # 1D projection onto global model direction
G_perp = G - outer(p, p) # Exact O(N²) rank-1 Gram update (no 2nd O(N²·d) matmul!)
D_perp = sqrt(max(0, diag(G_perp) + diag(G_perp).T - 2 * G_perp))
It then combines de-cloned k-NN geometry with a smooth Landau phase-transition gate—meaning zero dynamic boolean masks and 100% static tensor shapes for Cloud TPU!
Experiment 2 (evo_privedge_tpu): Evolving a Privacy-Preserving DP Sanitizer
In parallel (exp-apricot-crane), we started from a standard Uniform DP-SGD seed (71.95 / 150) and evaluated candidates against a real 2-layer tanh MLP DLG / iDLG gradient-inversion attacker plus a bfloat16 small-gradient stability test.
AlphaEvolve climbed to 144.12 / 150 (+100.3%) with champion prog-pompous-orangutan, inventing Scale-Invariant Weighted Gram-Schmidt Orthogonalized Noise:
- It applies stronger structured noise to high-leakage input-layer weights (breaking the rank-1 outer-product leakage that iDLG exploits),
- Projects the noise orthogonal to the useful gradient direction so training stays sharp (
0.9692cosine similarity vs0.7304baseline), - Preserves exact gradient norms (
norm_fidelity = 1.0000,bf16_stability = 1.000,DLG MSE = 2.9059vs1.0411baseline).
3. Seven Things That Actually Broke on Cloud TPU v6e-1 (torch-tpu 0.3.0)
Next, we ported both AlphaEvolve champions—plus naive PyTorch baselines—into our reusable evosec_tpu package and ran them live on a Google Cloud TPU v6e-1 VM (europe-west4-a, v2-alpha-tpuv6e, torch-tpu==0.3.0, torch==2.15.0+cpu, jax==0.10.2).
Here are the 7 real failure modes we hit and fixed:
4 Algorithmic & bfloat16 Numerical Traps
Dynamic Boolean Indexing (
U[keep_mask]):
Classic Z-score filters select survivors viaU[z < 2.5]. Because the number of surviving rows changes every round, XLA cannot keep a static graph and stalls on host-device syncs—burning230.8 msinsideaten::_to_copyacross 8 steps (32.16 ms/step).
Fix: Keep shapes static! Compute soft[N]weights withtorch.where+torch.topk/torch.sortand reduce viaw @ U.Greedy Multi-Krum Python Loop (
O(m·N²·d)):
Standard Multi-Krum loops in Pythonm = N - ftimes updating selection masks. On Cloud TPUv6e-1, warmup compilation thrashed for47.2 s–55.5 satN=64–128, d=65,536, and steady-state latency crawled at96.81 ms.
Fix: Single-passbf16MXU Gram matmul + rank-1O(N²)updates (0.306 mscompiled—316.8×faster!).Catastrophic
bfloat16Cancellation in Pairwise Distances:
Honest FL updates cluster closely around the true descent direction. Computingsq + sq.T - 2 * (U @ U.T)directly inbfloat16(only 7 mantissa bits!) wipes out the small difference between large squared norms:
# BROKEN on TPU bf16: 99.73% relative distance error on clustered FL updates!
sq = (u_bf16 * u_bf16).sum(dim=-1, keepdim=True)
dmat = torch.sqrt(sq + sq.T - 2.0 * (u_bf16 @ u_bf16.T))
Measured on v6e-1: 99.73% relative distance error vs fp32 torch.cdist!
Fix: Scale-normalize inputs before the bf16 MXU dot product, accumulate Gram entries and squared norms in fp32, and clamp >= 0.0 before sqrt (0.0% NaN, < 0.0023 aggregation error).
-
Small-Gradient
bfloat16DP Underflow (1,256×Norm Explosion): Slicing ragged layer views (g[:, start:end]) and clipping1e-4late-stage gradients inbf16underflows the norm and explodes output norms by1,255.95×! Fix: Precompute contiguous[1, d]static layer masks and run scale-invariantfp32orthogonal DP—achieving0.9999×exact norm fidelity!
3 Real torch-tpu 0.3.0 Platform Gotchas (Field Notes)
-
Use
torch.accelerator, NOTtorch.tpu.is_available(): Intorch-tpu 0.3.0,torch.tpu.is_available()raises aRuntimeError("internal to TorchTPU"). Use PyTorch's portable accelerator API instead:
import torch_tpu # noqa: F401 - registers PrivateUse1 -> 'tpu'
is_tpu = torch.accelerator.is_available() and torch.accelerator.current_accelerator().type == "tpu"
torch.accelerator.synchronize()
-
aten::medianis not yet implemented on TPU (torch-tpu 0.3.0): Callingtorch.median(x, dim=0)raisesRuntimeError: operator 'aten::median' is not implemented for TPU—immediately breaking Coordinate Median and MAD defenses. Replacing it with a static-shapetorch.sort-basedtpu_median()works cleanly in both eager andtorch.compile(backend="tpu"). -
Pallas
jax_op,/dev/vfio/0, and Dual Profiler Isolation:- Avoid
from __future__ import annotationsin files defining@torch.tpu.pallas.jax_opwhenjaxis imported lazily (TorchTPU evaluates annotations witheval_str=True, throwingNameError: name 'jax' is not defined). - Single-chip TPU
v6e-1locks/dev/vfio/0to one process at a time—runTORCH_TPU_DEFER_AND_FUSE=1as a sequential standalone command, not a child subprocess. - Never start
jax.profiler.start_trace()inside an activetorch.profiler.profile(activities=[..., TPU])block (triggers libtpuperiodicclosure.cc:33SIGABRT). Runtorch.profilerandjax.profilersequentially!
- Avoid
4. How We Benchmarked All 4 TorchTPU Modes + Custom Pallas VMEM
To understand how PyTorch security kernels actually scale on Cloud TPU v6e-1, we built a three-layer benchmark suite:
-
Microbenchmarks (
benchmarks/run_tpu_modes.py): Sweeps 8 realistic(N, d)Federated Learning workloads—from small edge models (N=20, d=7,850) and 128-aligned MXU tiles (N=128, d=65,536) up to 0.5M–1M parameter HBM stress tests (N=256, d=1,048,576) and large cohorts (N=512, d=65,536)—measuring warmup time, steady-state median (15iterations), p95 latency, throughput (clients/sec), and accuracy error vs the honest mean. -
Execution Modes Tested:
- Naive Broken PyTorch: Greedy Multi-Krum loop & Dynamic Boolean Z-Mask.
-
TorchTPU Strict Eager (
TORCH_TPU_DEFER_AND_FUSE=0): Static-shapev2champion executed op-by-op. -
TorchTPU DeferAndFuse (
TORCH_TPU_DEFER_AND_FUSE=1): Fused eager mode. -
torch.compile(backend="tpu", dynamic=False): Full XLA compiler lowering and fusion. -
Custom Block-Fused Pallas VMEM Kernel (
@torch.tpu.pallas.jax_op): Hand-written(128, 128)Mosaic VMEM tiled Gram + statistics kernel inpallas_kernel.py.
-
Hardware Profiling (
benchmarks/run_xprof_capture.py) & End-to-End FL/DLG (benchmarks/run_fl_benchmarks.py): Captures real TPU XLA HLO traces + real non-IID MNIST training and DLG image-inversion curves.
Measured Steady-State Latency on Cloud TPU v6e-1 (0 unbounded dynamic compilations)
(N, d) Workload |
Naive Multi-Krum | Naive Z-Mask (err) | Strict Eager (v2) |
DeferAndFuse (v2) |
Pallas VMEM (jax_op) |
torch.compile(tpu) |
Speedup |
|---|---|---|---|---|---|---|---|
(20, 7,850) (Edge Ref)
|
9.56 ms |
1.30 ms (0.307)
|
4.23 ms |
3.02 ms |
0.362 ms |
0.213 ms |
45.0× vs MK |
(32, 8,192) (Small Tile)
|
16.55 ms |
1.32 ms (0.274)
|
5.03 ms |
2.59 ms |
0.234 ms |
0.210 ms |
78.8× vs MK / 23.9× vs Eager |
(64, 65,536) (CNN/LoRA)
|
45.48 ms |
1.89 ms (0.371)
|
4.38 ms |
2.62 ms |
0.383 ms |
0.260 ms |
175.0× vs MK |
(128, 65,536) (MXU Tile)
|
96.81 ms |
2.89 ms (0.318)
|
4.15 ms |
2.89 ms |
0.422 ms |
0.306 ms |
316.8× vs MK (418.8K cli/s) |
(512, 65,536) (Large Cohort)
|
skipped |
9.11 ms (0.274)
|
5.23 ms |
3.48 ms |
5.17 ms |
0.878 ms |
10.4× vs Z-Mask (583.1K cli/s) |
(128, 524,288) (0.5M Params)
|
skipped |
15.70 ms (0.597)
|
6.49 ms |
5.32 ms |
5.46 ms |
2.37 ms |
6.6× vs Z-Mask |
(256, 524,288) (XProf Scale)
|
skipped |
32.04 ms (0.459)
|
10.20 ms |
8.57 ms |
14.31 ms |
4.71 ms |
6.8× vs Z-Mask |
(256, 1,048,576) (1M HBM)
|
skipped |
63.60 ms (0.596)
|
20.14 ms |
15.17 ms |
28.70 ms |
9.21 ms |
6.9× vs Z-Mask |
Look at that textbook TorchTPU ladder at N=128, d=65,536:
-
Naive Multi-Krum (
96.81 ms) → Strict Eager (4.15 ms) → DeferAndFuse (2.89 ms,1.44×over Eager) → Custom Pallas VMEM (0.422 ms,230×over MK) →torch.compile(backend="tpu")(0.306 ms,317×over MK!).
5. The XProf Plot Twist: Why torch.compile Beat Our First-Pass Pallas Kernel at d = 512K
This was our favorite engineering lesson of the sprint. Up to d = 65K, our custom Pallas VMEM kernel (0.234–0.422 ms) ran nearly neck-and-neck with torch.compile(backend="tpu"). So why did Pallas slow to 14.31–16.10 ms at (N=256, d=524,288) while torch.compile flew at 4.71 ms?
Our real torch.profiler (TpuKinetoProfilerSession, 5 XSpace planes) and native XProf .xplane.pb captures (xprof_summary.json) answered the question directly in the XLA HLO IR:
-
Naive Z-Mask (
32.16 ms/step):aten::_to_copystalled the host CPU for230.8 ms(8 steps), whilett_jit_sort(193.6 ms) andX64Combine(53.7 ms) thrashed HBM transposingf32[256, 524288]layouts back and forth. -
torch.compile(backend="tpu")(4.75 ms/step): XLA collapsed the entire evolved aggregator into one fused executable (aggregators_L130_split0_fwd,4.48 ms/steppure TPU time), streaming nativebf16[256, 524288]{1,0:T(8,128)(2,1)}tiles into the MXU with asynchronous VMEM prefetch (copy-start/copy-doneinto:S(1)). -
Pallas VMEM (
16.10 ms/stepat512K): XProf showed our two custom Mosaic calls:
%fused_vmem_gram_and_stats.2 = f32[256,256] custom-call(bf16[256,524288], ...), target="tpu_custom_call" (55.36 ms / 8 steps)
%fused_vmem_gram_and_stats.3 = f32[256,128] custom-call(bf16[256,524288], bf16[8,524288]), target="tpu_custom_call" (21.43 ms / 8 steps)
Plus 55.5 ms stalled on synchronous copy-start DMA barriers! Because our first-pass Pallas jax_op launched two separate tpu_custom_call passes over HBM without double-buffered d-tile pipelining, XLA's compiler-pipelined bf16 fusion beat it once HBM bandwidth dominated past d = 512K.
Golden rule for TorchTPU developers: Fix dynamic shapes and bf16 numerics first, turn on torch.compile(backend="tpu", dynamic=False), and always inspect XProf HLO traces before hand-writing multi-buffered Pallas kernels!
6. End-to-End FL Resilience, DLG Privacy Frontier & Gemma 4 E4B on Colab
Does TPU acceleration weaken real-world security or privacy? We verified on real Non-IID MNIST Federated Learning (N=20 clients, T=25 rounds, Dirichlet(0.5), 9 aggregators × 8 attacks) and a 2-layer tanh MLP DLG / iDLG gradient-inversion benchmark:
-
Byzantine Resilience:
FedAvgcollapses to6.5%(Gaussian) and37.5%(40% Sign-Flip);Multi-Krumcollapses to11.6%(Gaussian).EvoSec-TPU v2 (Champ)holds83.0%–83.2%across Gaussian, Sign-Flip, Sybil, unseen ALIE, unseen Label-Flip, and 40% Sign-Flip! -
DLG Privacy Frontier: At
ε = 1.0,Evo-PrivEdge v2 (Champ)pushes attacker reconstruction MSE to2.516(well above the1.85inversion-failure threshold) while keeping0.959gradient cosine utility (vs Uniform DP-SGDMSE = 1.253atcos = 0.499). -
Live Gemma 4 E4B Co-Evolution on Colab
v6e-1: In Lab 4 of our Colab notebook, we load open-weightsgoogle/gemma-4-E4B-itdirectly into TPUv6e-1's 32 GB HBM via Hugging Face Transformers v5 (device_map="tpu",dtype=torch.bfloat16) to propose adaptive red-team attack parameters and stress-testEvo Top-K (v1)vsEvoSec-TPU v2 (Champ)in a closed co-evolution loop.
7. Constructive Feedback for the TorchTPU Team (#TorchTPUSprint)
Building end-to-end on torch-tpu==0.3.0 was a blast—torch.compile(backend="tpu") delivered 316.8× over naive Multi-Krum and 13.6×–23.9× over Strict Eager out of the box! Three small ergonomic improvements would make TorchTPU even smoother for security & scientific PyTorch developers:
- Implement
aten::mediannatively on TPU (critical for robust statistics, MAD, and Byzantine FL defenses). - Allow
@torch.tpu.pallas.jax_opto resolve type annotations cleanly whenfrom __future__ import annotationsis active. - Emit a clear warning (instead of a libtpu
periodicclosure.cc:33SIGABRT) ifjax.profiler.start_trace()is invoked whiletorch.profiler.ProfilerActivity.TPUis active.
Try It Yourself
- GitHub Repo: github.com/Unisvet/evosec-torchtpu
-
1-Click Colab (
v6e-1TPU): Launch EvoSec_TorchTPU_Sprint_2026.ipynb
Supported by the German Federal Ministry of Research, Technology and Space (BMFTR), Project AI-DISCO (Grant ID: 16ME1127), Chair of Wireless Systems, Brandenburg University of Technology (BTU) Cottbus-Senftenberg.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.



