Files
2026-08-01 19:55:12 -07:00

166 lines
7.1 KiB
Swift

// 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)
}
}