v1.7.0 release: amp-modeling core (ToneStack, TriodeStage, LSTMAmp)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-08-01 19:55:12 -07:00
parent d6875da2cb
commit 3e33f09e07
12 changed files with 1322 additions and 47 deletions
@@ -0,0 +1,94 @@
// ToneStackTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Darwin
@testable import LyrebirdSynth
@MainActor
@Suite("ToneStack")
struct ToneStackTests {
let engine: SynthesisEngine
let sr: Double = 44100.0
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
private func rms(_ samples: [Double]) -> Double {
guard !samples.isEmpty else { return 0 }
let sumSq: Double = samples.reduce(0.0) { $0 + $1 * $1 }
return (sumSq / Double(samples.count)).squareRoot()
}
/// Steady-state output RMS for a sine at `freqHz` through the tone stack at the given settings.
private func steadyRMS(
freqHz: Double,
bass: Double,
mid: Double,
treble: Double,
model: ToneStackModel = .fender
) -> [Double] {
let sine: OscSin.Audio = OscSin.Audio(freq: freqHz, mul: 1.0)
let stack: ToneStack = ToneStack(
input: sine, bass: bass, mid: mid, treble: treble, model: model)
return collectBlocks(stack, engine: engine, blocks: 200)
}
@Test func bassControlBoostsLowEnd() {
let lowFreq: Double = 100.0
let bassDown: Double = rms(Array(steadyRMS(freqHz: lowFreq, bass: 0.0, mid: 0.5, treble: 0.5).suffix(engine.blockSize * 100)))
let bassUp: Double = rms(Array(steadyRMS(freqHz: lowFreq, bass: 1.0, mid: 0.5, treble: 0.5).suffix(engine.blockSize * 100)))
#expect(bassUp > bassDown, "bass control did not boost 100 Hz (up=\(bassUp) down=\(bassDown))")
}
@Test func trebleControlBoostsHighEnd() {
let highFreq: Double = 4000.0
let trebleDown: Double = rms(Array(steadyRMS(freqHz: highFreq, bass: 0.5, mid: 0.5, treble: 0.0).suffix(engine.blockSize * 100)))
let trebleUp: Double = rms(Array(steadyRMS(freqHz: highFreq, bass: 0.5, mid: 0.5, treble: 1.0).suffix(engine.blockSize * 100)))
#expect(trebleUp > trebleDown, "treble control did not boost 4 kHz (up=\(trebleUp) down=\(trebleDown))")
}
@Test func outputStaysFiniteAndBoundedAcrossSettings() {
let settings: [(Double, Double, Double)] = [
(0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (1.0, 0.0, 1.0), (0.0, 1.0, 0.0), (0.5, 0.5, 0.5),
]
for (bass, mid, treble): (Double, Double, Double) in settings {
for model: ToneStackModel in ToneStackModel.allCases {
let out: [Double] = steadyRMS(freqHz: 220.0, bass: bass, mid: mid, treble: treble, model: model)
#expect(out.allSatisfy { $0.isFinite }, "non-finite output at \(model) b=\(bass) m=\(mid) t=\(treble)")
let peak: Double = out.map { abs($0) }.max() ?? 0
// Passive stack: never amplifies above the ±1 input by more than a small margin.
#expect(peak <= 1.5, "tone stack blew up (peak=\(peak)) at \(model) b=\(bass) m=\(mid) t=\(treble)")
}
}
}
@Test func modelsProduceDifferentResponse() {
let freq: Double = 800.0
let fender: Double = rms(Array(steadyRMS(freqHz: freq, bass: 0.5, mid: 0.5, treble: 0.5, model: .fender).suffix(engine.blockSize * 100)))
let vox: Double = rms(Array(steadyRMS(freqHz: freq, bass: 0.5, mid: 0.5, treble: 0.5, model: .vox).suffix(engine.blockSize * 100)))
// Different component sets must give a materially different response, not just any
// float difference — require at least a 5% relative gap.
let relativeDiff: Double = abs(fender - vox) / Swift.max(fender, vox)
#expect(relativeDiff > 0.05, "Fender vs Vox 800 Hz response too close: rel=\(relativeDiff)")
}
@Test func blocksDCInSteadyState() {
// The passive tone stack has series coupling caps → exactly zero DC gain (the numerator
// has no constant term; the discretized B0…B3 sum to 0). A constant input must decay to
// ~0. This is an analytic invariant independent of the exact coefficient values, so it
// guards the transcribed Yeh/Smith numerator against a DC-introducing transcription error.
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.7)
let stack: ToneStack = ToneStack(input: dc, bass: 0.6, mid: 0.5, treble: 0.4, model: .fender)
let out: [Double] = collectBlocks(stack, engine: engine, blocks: 300)
let tail: [Double] = Array(out.suffix(engine.blockSize * 100))
let meanAbs: Double = tail.reduce(0.0) { $0 + abs($1) } / Double(tail.count)
#expect(meanAbs < 1.0e-3, "tone stack did not block DC (meanAbs=\(meanAbs))")
}
}
@@ -0,0 +1,165 @@
// LSTMAmpTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import Darwin
@testable import LyrebirdSynth
@MainActor
@Suite("LSTMAmp")
struct LSTMAmpTests {
let engine: SynthesisEngine
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
// MARK: - Model construction helpers
/// A deterministic (RNG-free) model of the given hidden size, for reproducible golden tests.
private func makeDeterministicModel(hiddenSize h: Int, residual: Bool) -> NeuralAmpModel {
let gated: Int = NeuralAmpModel.gateCount * h
var wih: [Double] = [Double](repeating: 0.0, count: gated)
var bih: [Double] = [Double](repeating: 0.0, count: gated)
var bhh: [Double] = [Double](repeating: 0.0, count: gated)
for k: Int in 0..<gated {
wih[k] = 0.2 * sin(Double(k) + 1.0)
bih[k] = 0.01 * Double(k)
bhh[k] = -0.005 * Double(k)
}
var whh: [Double] = [Double](repeating: 0.0, count: gated * h)
for k: Int in 0..<(gated * h) {
whh[k] = 0.1 * cos(Double(k) + 1.0)
}
var wout: [Double] = [Double](repeating: 0.0, count: h)
for u: Int in 0..<h {
wout[u] = 0.3 * sin(Double(u) + 0.5)
}
return NeuralAmpModel(
hiddenSize: h, residual: residual,
weightIH: wih, weightHH: whh, biasIH: bih, biasHH: bhh,
denseWeight: wout, denseBias: 0.05)
}
private func zeroModel(hiddenSize h: Int, residual: Bool) -> NeuralAmpModel {
let gated: Int = NeuralAmpModel.gateCount * h
return NeuralAmpModel(
hiddenSize: h, residual: residual,
weightIH: [Double](repeating: 0.0, count: gated),
weightHH: [Double](repeating: 0.0, count: gated * h),
biasIH: [Double](repeating: 0.0, count: gated),
biasHH: [Double](repeating: 0.0, count: gated),
denseWeight: [Double](repeating: 0.0, count: h),
denseBias: 0.0)
}
/// Independent, plainly-written LSTM step matching `NeuralAmpModel`'s documented layout —
/// the golden reference the flat-indexed generator kernel is checked against.
private func referenceStep(
_ model: NeuralAmpModel,
x: Double,
h: inout [Double],
c: inout [Double]
) -> Double {
let hid: Int = model.hiddenSize
func sig(_ z: Double) -> Double { 1.0 / (1.0 + exp(-z)) }
var pre: [Double] = [Double](repeating: 0.0, count: NeuralAmpModel.gateCount * hid)
for r: Int in 0..<pre.count {
var acc: Double = model.biasIH[r] + model.biasHH[r] + model.weightIH[r] * x
for j: Int in 0..<hid {
acc += model.weightHH[r * hid + j] * h[j]
}
pre[r] = acc
}
var out: Double = model.denseBias
for u: Int in 0..<hid {
let ig: Double = sig(pre[u])
let fg: Double = sig(pre[hid + u])
let gg: Double = tanh(pre[2 * hid + u])
let og: Double = sig(pre[3 * hid + u])
c[u] = fg * c[u] + ig * gg
h[u] = og * tanh(c[u])
out += model.denseWeight[u] * h[u]
}
if model.residual { out += x }
return out
}
// MARK: - Tests
@Test func matchesReferenceTrajectory() {
// Full sample-by-sample golden match over a DC-excited trajectory (exercises the
// recurrence + state persistence across blocks). Guards gate order, recurrence indexing,
// dense readout, and residual against the flat-array kernel.
let hidden: Int = 3
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: hidden, residual: true)
let xval: Double = 0.5
let amp: LSTMAmp = LSTMAmp(input: ConstantGeneratorInput(xval), model: model)
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 5)
var h: [Double] = [Double](repeating: 0.0, count: hidden)
var c: [Double] = [Double](repeating: 0.0, count: hidden)
for i: Int in 0..<got.count {
let expected: Double = referenceStep(model, x: xval, h: &h, c: &c)
#expect(abs(got[i] - expected) < 1.0e-9, "sample \(i): got \(got[i]) expected \(expected)")
}
}
@Test func zeroWeightsResidualPassesInputThrough() {
// All-zero weights → the LSTM contributes nothing; with residual the output equals input.
let model: NeuralAmpModel = zeroModel(hiddenSize: 4, residual: true)
let xval: Double = 0.3
let amp: LSTMAmp = LSTMAmp(input: ConstantGeneratorInput(xval), model: model)
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 3)
#expect(got.allSatisfy { abs($0 - xval) < 1.0e-12 }, "residual passthrough failed")
}
@Test func zeroWeightsNoResidualIsSilent() {
let model: NeuralAmpModel = zeroModel(hiddenSize: 4, residual: false)
let amp: LSTMAmp = LSTMAmp(input: ConstantGeneratorInput(0.3), model: model)
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 3)
#expect(got.allSatisfy { abs($0) < 1.0e-12 }, "no-residual zero model was not silent")
}
@Test func finiteBoundedOnSine() {
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: 8, residual: true)
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 0.8)
let amp: LSTMAmp = LSTMAmp(input: sine, model: model)
let got: [Double] = collectBlocks(amp, engine: engine, blocks: 50)
#expect(got.allSatisfy { $0.isFinite }, "non-finite output")
#expect(got.contains { abs($0) > 1.0e-4 }, "output was silent")
}
@Test func malformedModelJSONThrows() throws {
// A hand-edited / externally-authored model with a mis-sized weight array must fail at
// decode (the validating init(from:)) rather than decode silently and crash later.
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: 3, residual: true)
let data: Data = try JSONEncoder().encode(model)
guard var object: [String: Any] = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
Issue.record("encoded model was not a JSON object")
return
}
object["weightHH"] = [1.0, 2.0, 3.0] // wrong length for hiddenSize 3
let bad: Data = try JSONSerialization.data(withJSONObject: object)
#expect(throws: DecodingError.self) {
_ = try JSONDecoder().decode(NeuralAmpModel.self, from: bad)
}
}
@Test func modelCodableRoundTrips() throws {
let model: NeuralAmpModel = makeDeterministicModel(hiddenSize: 5, residual: true)
let data: Data = try JSONEncoder().encode(model)
let decoded: NeuralAmpModel = try JSONDecoder().decode(NeuralAmpModel.self, from: data)
#expect(decoded.hiddenSize == model.hiddenSize)
#expect(decoded.residual == model.residual)
#expect(decoded.weightHH == model.weightHH)
#expect(decoded.denseWeight == model.denseWeight)
#expect(decoded.denseBias == model.denseBias)
}
}
@@ -0,0 +1,113 @@
// TriodeStageTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Darwin
@testable import LyrebirdSynth
@MainActor
@Suite("TriodeStage")
struct TriodeStageTests {
let engine: SynthesisEngine
let sr: Double = 44100.0
init() throws {
engine = makeTestEngine(blockSize: 64, sampleRate: 44100)
try engine.start()
}
private func goertzel(_ x: [Double], cyclesPerSample: Double) -> Double {
let omega: Double = 2.0 * Double.pi * cyclesPerSample
let cosine: Double = cos(omega)
let sine: Double = sin(omega)
let coeff: Double = 2.0 * cosine
var s1: Double = 0.0
var s2: Double = 0.0
for v: Double in x {
let s0: Double = v + coeff * s1 - s2
s2 = s1
s1 = s0
}
let real: Double = s1 - s2 * cosine
let imag: Double = s2 * sine
return (real * real + imag * imag).squareRoot()
}
private func steadyTail(_ gen: any Generator, blocks: Int = 200) -> [Double] {
let all: [Double] = collectBlocks(gen, engine: engine, blocks: blocks)
return Array(all.suffix(engine.blockSize * 100))
}
@Test func buildsNonSilentAndBounded() {
let sine: OscSin.Audio = OscSin.Audio(freq: 220.0, mul: 0.8)
let stage: TriodeStage = TriodeStage(input: sine, drive: 2.0, bias: 0.2)
let tail: [Double] = steadyTail(stage)
#expect(tail.contains { abs($0) > 1.0e-4 }, "TriodeStage was silent")
#expect(tail.allSatisfy { $0.isFinite }, "non-finite output")
let peak: Double = tail.map { abs($0) }.max() ?? 0
#expect(peak <= 1.2, "TriodeStage output not bounded near ±1: peak=\(peak)")
}
@Test func biasAddsEvenHarmonics() {
// A symmetric (bias 0) tanh produces only odd harmonics → the 2nd harmonic is ~0.
// Grid bias makes the transfer asymmetric → a real 2nd harmonic appears (tube warmth).
let fundamental: Double = 1000.0
func secondHarmonic(bias: Double) -> Double {
let sine: OscSin.Audio = OscSin.Audio(freq: fundamental, mul: 0.8)
let stage: TriodeStage = TriodeStage(input: sine, drive: 3.0, bias: bias, oversample: 4)
return goertzel(steadyTail(stage), cyclesPerSample: 2.0 * fundamental / sr)
}
let unbiased: Double = secondHarmonic(bias: 0.0)
let biased: Double = secondHarmonic(bias: 0.5)
#expect(biased > unbiased * 3.0, "bias did not add 2nd-harmonic content (biased=\(biased) unbiased=\(unbiased))")
}
@Test func couplingBlocksDC() {
// The output coupling (DC blocker) must remove the standing offset a biased stage adds
// to a constant input — steady output decays to ~0.
let dc: ConstantGeneratorInput = ConstantGeneratorInput(0.5)
let stage: TriodeStage = TriodeStage(input: dc, drive: 2.0, bias: 0.3)
let tail: [Double] = steadyTail(stage, blocks: 300)
let meanAbs: Double = tail.reduce(0.0) { $0 + abs($1) } / Double(tail.count)
#expect(meanAbs < 1.0e-3, "coupling did not block DC (meanAbs=\(meanAbs))")
}
@Test func oversamplingReducesAliasing() {
// 0.3·Fs driven hard: the odd harmonics (3·f0 = 0.9·Fs) fold to a 0.1·Fs alias at base
// rate. Measure alias energy relative to the fundamental vs a naive base-rate stage.
let fundamental: Double = 0.3 * sr
let drive: Double = 3.0
let pole: Double = 0.995
let fundBin: Double = 0.3
let aliasBin: Double = 0.1
let sine: OscSin.Audio = OscSin.Audio(freq: fundamental, mul: 0.9)
let stage: TriodeStage = TriodeStage(input: sine, drive: drive, bias: 0.0, oversample: 4)
let osTail: [Double] = steadyTail(stage)
let osRatio: Double = goertzel(osTail, cyclesPerSample: aliasBin)
/ goertzel(osTail, cyclesPerSample: fundBin)
// Naive base-rate reference: tanh(drive·x) then the same DC blocker, no oversampling.
let cyclesPerSample: Double = fundamental / sr
var naive: [Double] = [Double](repeating: 0.0, count: osTail.count)
var x1: Double = 0.0
var y1: Double = 0.0
for n: Int in 0..<naive.count {
let x: Double = 0.9 * sin(2.0 * Double.pi * cyclesPerSample * Double(n))
let shaped: Double = tanh(drive * x)
let y: Double = shaped - x1 + pole * y1
x1 = shaped
y1 = y
naive[n] = y
}
let naiveRatio: Double = goertzel(naive, cyclesPerSample: aliasBin)
/ goertzel(naive, cyclesPerSample: fundBin)
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
#expect(osRatio < naiveRatio * 0.5, "oversampling did not reduce aliasing: os=\(osRatio) naive=\(naiveRatio)")
}
}