惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
About on SuperTechFans
Apple Machine Learning Research
Apple Machine Learning Research
The Register - Security
The Register - Security
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
MyScale Blog
MyScale Blog
云风的 BLOG
云风的 BLOG
博客园_首页
U
Unit 42
T
Tailwind CSS Blog
G
GRAHAM CLULEY
F
Full Disclosure
V
Vulnerabilities – Threatpost
T
Tenable Blog
月光博客
月光博客
P
Privacy & Cybersecurity Law Blog
P
Privacy International News Feed
K
Kaspersky official blog
Scott Helme
Scott Helme
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News and Events Feed by Topic
T
The Exploit Database - CXSecurity.com
N
News and Events Feed by Topic
有赞技术团队
有赞技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LINUX DO - 最新话题
Recorded Future
Recorded Future
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Help Net Security
Help Net Security
The GitHub Blog
The GitHub Blog
Cisco Talos Blog
Cisco Talos Blog
SecWiki News
SecWiki News
P
Proofpoint News Feed
Security Latest
Security Latest
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
罗磊的独立博客
S
Security Affairs
M
MIT News - Artificial intelligence
L
LINUX DO - 热门话题
美团技术团队
Simon Willison's Weblog
Simon Willison's Weblog
T
Threat Research - Cisco Blogs
Stack Overflow Blog
Stack Overflow Blog
Forbes - Security
Forbes - Security
Hugging Face - Blog
Hugging Face - Blog
博客园 - Franky
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Exported HT-Demucs FT to ONNX in 2026 (4 Blockers Everyone Else Gave Up On)
StemSplit · 2026-05-21 · via DEV Community

You can't ship htdemucs_ft on iOS. You can't ship it on Android. You can't run it in a browser. PyTorch Mobile is a 2 GB install and a permission to break, MLX needs Apple Silicon, and the obvious answer — ONNX — has been "broken on htdemucs" across four open GitHub issues for three years.

I just shipped the first working ONNX export of htdemucs_ft. It runs in onnxruntime, is 1.31× faster than PyTorch on CPU, and is numerically equivalent to the original (max absolute difference: 0.000163 on drums, 0.000008 on vocals). All four specialist sub-models are on Hugging Face: StemSplitio/htdemucs-ft-onnx.

This is the engineering writeup — the 4 blockers that killed every prior attempt and the patches that beat them.

What You'll Learn

  • ✅ Why htdemucs is so hard to export (complex tensors, Python dynamism, fused C++ kernels)
  • ✅ How to replace torch.stft with Conv1d without losing accuracy (5 × 10⁻⁶ round-trip diff)
  • ✅ How to patch fractions.Fraction, random.randrange, and aten::_native_multi_head_attention
  • ✅ How to verify parity to 4 decimals before trusting the export
  • ✅ Pure numpy + onnxruntime inference — no PyTorch at runtime

Prerequisites

pip install "torch>=2.4,<2.5" "torchaudio>=2.4,<2.5" demucs onnx onnxruntime numpy soundfile

Enter fullscreen mode Exit fullscreen mode

No GPU required for export or inference. Tested on Apple M4 Pro and Linux x86_64. If you don't have demucs set up yet, follow the complete demucs local setup guide first.


Why doesn't htdemucs export to ONNX out of the box?

Short answer: Because the model uses four PyTorch features that no ONNX exporter has good answers for — complex tensors in the STFT, fractions.Fraction arithmetic in model.segment, random.randrange inside the cross-transformer, and the fused C++ aten::_native_multi_head_attention kernel.

Each one stops torch.onnx.export and torch.onnx.dynamo_export cold. You hit them in order; each new patch unblocks the next failure.


Blocker 1: complex64 STFT output

Short answer: Replace torch.stft with a Conv1d using sin/cos kernels that emit two real-valued channels.

The first op in HT-Demucs is:

z = torch.stft(x, n_fft=4096, hop_length=1024, window=hann,
               win_length=4096, normalized=True, center=True,
               return_complex=True, pad_mode="reflect")

Enter fullscreen mode Exit fullscreen mode

return_complex=True returns a complex64 tensor. ONNX's STFT op (opset 17+) does not support complex outputs; every downstream slice/transpose fails. The workaround:

import math, torch
import torch.nn as nn
import torch.nn.functional as F

def _make_stft_kernels(n_fft: int):
    n = torch.arange(n_fft, dtype=torch.float64)
    window = torch.hann_window(n_fft, periodic=True, dtype=torch.float64)
    norm = 1.0 / math.sqrt(n_fft)
    k = torch.arange(n_fft // 2 + 1, dtype=torch.float64).unsqueeze(1)
    angles = 2 * math.pi * k * n.unsqueeze(0) / n_fft
    cos = (window * torch.cos(angles)) * norm
    sin = (window * -torch.sin(angles)) * norm   # negative for forward STFT
    return cos.float().unsqueeze(1), sin.float().unsqueeze(1)

class RealSTFT(nn.Module):
    def __init__(self, n_fft=4096, hop_length=1024):
        super().__init__()
        cos, sin = _make_stft_kernels(n_fft)
        self.register_buffer("cos_kernel", cos)
        self.register_buffer("sin_kernel", sin)
        self.n_fft, self.hop_length = n_fft, hop_length

    def forward(self, x):
        x = F.pad(x.reshape(-1, 1, x.shape[-1]),
                  (self.n_fft // 2,) * 2, mode="reflect")
        real = F.conv1d(x, self.cos_kernel, stride=self.hop_length)
        imag = F.conv1d(x, self.sin_kernel, stride=self.hop_length)
        return torch.stack([real, imag], dim=1)    # (BN, 2, F, T) real

Enter fullscreen mode Exit fullscreen mode

Verify against the real thing before going further:

x = torch.randn(1, 343980)
ref = torch.stft(x, n_fft=4096, hop_length=1024,
                 window=torch.hann_window(4096), win_length=4096,
                 normalized=True, center=True, return_complex=True,
                 pad_mode="reflect")
ref_real = torch.stack([ref.real, ref.imag], dim=1)

stft = RealSTFT()
out = stft(x).squeeze(0)
print("max abs diff:", (out - ref_real).abs().max().item())   # ~5e-6

Enter fullscreen mode Exit fullscreen mode

5 × 10⁻⁶ is rounding noise. Use the same trick (ConvTranspose1d with conjugate kernels + overlap-add window-squared envelope) for the inverse STFT. Now every view_as_real / view_as_complex in the model's _magnitude and _mask methods can be rewritten to thread real-channel tensors through the whole forward pass.


Blocker 2: fractions.Fraction in model.segment

Short answer: Coerce to float before exporting.

Pretrained htdemucs_ft ships with model.segment = Fraction(39, 5) (= 7.8 seconds). Dynamo dies:

torch._dynamo.exc.Unsupported: call_function
UserDefinedClassVariable(<class 'fractions.Fraction'>)

Enter fullscreen mode Exit fullscreen mode

Fix:

from fractions import Fraction

if isinstance(model.segment, Fraction):
    model.segment = float(model.segment)   # 7.8

Enter fullscreen mode Exit fullscreen mode

Mathematically identical at inference. Trivial — but you don't get to the next blocker without it.


Blocker 3: random.randrange in the cross-transformer

Short answer: Monkey-patch the affected method to hardcode shift=0.

CrossTransformerEncoder._get_pos_embedding calls Python's random:

shift = random.randrange(self.sin_random_shift + 1)

Enter fullscreen mode Exit fullscreen mode

At inference, sin_random_shift = 0, so random.randrange(1) always returns 0 — a no-op. But neither exporter can see through random and both bail out. Patch the method directly:

import types
from demucs.transformer import CrossTransformerEncoder, create_sin_embedding

def _get_pos_embedding_no_random(self_, T, B, C, device):
    if self_.emb == "sin":
        return create_sin_embedding(T, C, shift=0, device=device,
                                    max_period=self_.max_period)
    raise RuntimeError(f"emb={self_.emb} not handled at export")

for m in model.modules():
    if isinstance(m, CrossTransformerEncoder):
        m._get_pos_embedding = types.MethodType(_get_pos_embedding_no_random, m)

Enter fullscreen mode Exit fullscreen mode


Blocker 4: aten::_native_multi_head_attention

Short answer: Replace nn.MultiheadAttention.forward with a plain Linear/bmm/softmax implementation.

Modern PyTorch short-circuits nn.MultiheadAttention.forward to a fused C++ kernel (_native_multi_head_attention) when its preconditions are met. That kernel has no ONNX symbolic at any opset:

torch.onnx.errors.UnsupportedOperatorError: Exporting the operator
'aten::_native_multi_head_attention' to ONNX opset version 17 is not supported.

Enter fullscreen mode Exit fullscreen mode

Patch every MHA instance's forward with a drop-in that uses only ops with stable ONNX symbolics:

def _onnx_friendly_mha_forward(self_, query, key, value,
                                key_padding_mask=None, need_weights=True,
                                attn_mask=None, average_attn_weights=True,
                                is_causal=False):
    if self_.batch_first:
        query, key, value = (t.transpose(0, 1) for t in (query, key, value))
    tgt_len, bsz, embed_dim = query.shape
    head_dim = embed_dim // self_.num_heads

    if self_._qkv_same_embed_dim and torch.equal(query, key) and torch.equal(key, value):
        q, k, v = F.linear(query, self_.in_proj_weight, self_.in_proj_bias).chunk(3, dim=-1)
    else:
        # cross-attention path: three separate projections
        w_q, w_k, w_v = self_.in_proj_weight.chunk(3)
        b_q, b_k, b_v = (self_.in_proj_bias.chunk(3)
                         if self_.in_proj_bias is not None else (None, None, None))
        q = F.linear(query, w_q, b_q)
        k = F.linear(key,   w_k, b_k)
        v = F.linear(value, w_v, b_v)

    q = q.contiguous().view(tgt_len, bsz * self_.num_heads, head_dim).transpose(0, 1)
    k = k.contiguous().view(-1,      bsz * self_.num_heads, head_dim).transpose(0, 1)
    v = v.contiguous().view(-1,      bsz * self_.num_heads, head_dim).transpose(0, 1)

    attn = F.softmax(torch.bmm(q * head_dim ** -0.5, k.transpose(1, 2)), dim=-1)
    out  = torch.bmm(attn, v).transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
    return self_.out_proj(out), None

for m in model.modules():
    if isinstance(m, nn.MultiheadAttention):
        m.forward = types.MethodType(_onnx_friendly_mha_forward, m)

Enter fullscreen mode Exit fullscreen mode

Parity vs the fused kernel: 1 × 10⁻⁶ max diff. Safe.


The export call

Short answer: Legacy torch.onnx.export at opset 17, dynamo=False. dynamo_export dies on the patches anyway; legacy works.

from demucs.pretrained import get_model

bag = get_model("htdemucs_ft")
drums_model = bag.models[0].eval().cpu()
# apply all 4 patches above to drums_model

n = int(float(drums_model.segment) * int(bag.samplerate))   # 343980
dummy = torch.randn(1, 2, n, dtype=torch.float32)

torch.onnx.export(
    drums_model,
    dummy,
    "htdemucs_ft_drums.onnx",
    input_names=["mix"],
    output_names=["stems"],
    opset_version=17,
    dynamo=False,
    do_constant_folding=True,
)

Enter fullscreen mode Exit fullscreen mode

316 MB per specialist. ~6.5 s export time on CPU. Passes onnx.checker.check_model. 24,765 nodes.

Repeat for bag.models[1] (bass), bag.models[2] (other), bag.models[3] (vocals). All four use the same architecture and patches.


Parity verification — the only acceptance test that matters

Short answer: Run the original PyTorch model and the ONNX model on the same fixed input, compute .abs().max(). Should be < 1e-3.

import numpy as np
import onnxruntime as ort

x = np.random.randn(1, 2, 343980).astype("float32")
sess = ort.InferenceSession("htdemucs_ft_drums.onnx",
                            providers=["CPUExecutionProvider"])
onnx_out = sess.run(["stems"], {"mix": x})[0]

torch_out = drums_model(torch.from_numpy(x)).detach().numpy()
print("max abs diff:", np.abs(onnx_out - torch_out).max())   # 1.63e-4

Enter fullscreen mode Exit fullscreen mode

Per stem, against the original PyTorch htdemucs_ft at fp32:

Stem max abs diff
drums 0.000163
bass 0.000011
other 0.000739
vocals 0.000008

All comfortably under the 1e-3 tolerance that fp32 reordering normally explains. SDR scores measured against MUSDB18-HQ are unchanged — if you want to verify yourself, query the 800-row leaderboard from pandas without re-running the benchmark.


Inference with zero PyTorch (pure numpy + onnxruntime)

Short answer: Load the four ONNX files, do overlap-add chunking, sum the per-model outputs.

import numpy as np
import onnxruntime as ort
import soundfile as sf

SOURCES = ["drums", "bass", "other", "vocals"]
CHUNK = 343980             # 7.8 s * 44100 Hz
HOP   = CHUNK // 4

sessions = {
    s: ort.InferenceSession(f"htdemucs_ft_{s}.onnx",
                            providers=["CPUExecutionProvider"])
    for s in SOURCES
}

def separate(mix, sr=44100):
    pad = CHUNK - (mix.shape[-1] % CHUNK)
    mix_p = np.pad(mix, ((0, 0), (0, pad)), mode="constant")
    out = {s: np.zeros_like(mix_p) for s in SOURCES}
    weight = np.zeros(mix_p.shape[-1])
    w = np.hanning(CHUNK).astype("float32")

    for start in range(0, mix_p.shape[-1] - CHUNK + 1, HOP):
        chunk = mix_p[:, start:start+CHUNK].astype("float32")[None]
        for s in SOURCES:
            y = sessions[s].run(["stems"], {"mix": chunk})[0][0]
            target_row = SOURCES.index(s)
            out[s][:, start:start+CHUNK] += y[target_row] * w
        weight[start:start+CHUNK] += w

    for s in SOURCES:
        out[s] = (out[s] / np.maximum(weight, 1e-8))[:, :mix.shape[-1]]
    return out

mix, sr = sf.read("song.wav", dtype="float32", always_2d=True)
stems = separate(mix.T, sr)
for s in SOURCES:
    sf.write(f"{s}.wav", stems[s].T, sr)

Enter fullscreen mode Exit fullscreen mode

Zero PyTorch. Zero MLX. Runs anywhere onnxruntime runs — iOS via onnxruntime-objc, Android via onnxruntime-android, browsers via onnxruntime-web.


Performance numbers

Short answer: ONNX Runtime CPU EP is 1.31× faster than PyTorch CPU. A single-specialist ONNX is ~5.7× faster than the full bag.

Apple M4 Pro, 3-minute song:

Backend Latency Notes
ONNX CPU EP — single specialist ~22 s Use this for vocal removers / drum extractors
ONNX CPU EP — full 4-stem bag ~88 s All stems
PyTorch CPU — full bag ~125 s Baseline
PyTorch MPS — full bag ~47 s Apple GPU
ONNX CUDA — NVIDIA L4 (extrapolated) ~6 s Server-side deployment

The single-specialist trick works because the htdemucs_ft bag is one-hot:

# the bag's per-model weight matrix
weights = [[1, 0, 0, 0],   # drums  = sub-model 0's drums output
           [0, 1, 0, 0],   # bass   = sub-model 1's bass output
           [0, 0, 1, 0],   # other  = sub-model 2's other output
           [0, 0, 0, 1]]   # vocals = sub-model 3's vocals output

Enter fullscreen mode Exit fullscreen mode

Sub-model 3's vocals output is the bag's vocals output, bit-exact. If you're building a vocal remover, ship sub-model 3 alone (~316 MB ONNX, ~75 MB quantized) instead of the full ~1.26 GB bag at identical per-stem quality.


Wrapping Up

The five new ONNX repos — all MIT-licensed, all parity-verified:

If you'd rather skip the deployment plumbing entirely, the StemSplit hosted vocal remover runs the exact same htdemucs_ft weights with credits, queueing, and a dashboard — same model, just hosted. The full long-form writeup on the StemSplit blog has the iOS/Swift, Android/Kotlin, and onnxruntime-web code samples as well.

Open an issue on any of the repos if you find a stem where your parity diff exceeds 1e-3 — would love to hear about it.