Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 77580ee98e | |||
| ea0aa84ca7 |
+12
@@ -7,6 +7,18 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 1.7.1 — Neural-amp model importer
|
||||
|
||||
A patch release. One backward-compatible addition:
|
||||
|
||||
- **`ProteusModelImporter`** — loads a GuitarML **Proteus / NeuralPi** model JSON (single-layer
|
||||
LSTM capture) into a `NeuralAmpModel` for `LSTMAmp`. The state-dict tensors map straight onto
|
||||
`NeuralAmpModel`'s layout (PyTorch gate order; `skip` → residual); unsupported topologies and
|
||||
inconsistent tensor shapes throw. Model files are user-supplied — none are bundled (GuitarML
|
||||
models are GPL-3.0). A binary NAM `.nam` importer remains future work.
|
||||
|
||||
---
|
||||
|
||||
## 1.7.0 — Amp-modeling core: tone stack, triode stage, neural amp
|
||||
|
||||
A minor release. Three new, backward-compatible generators — the DSP core for guitar-amp
|
||||
|
||||
@@ -21,8 +21,8 @@ import Darwin
|
||||
/// Output is mono. The `Double` output is whatever the trained model produces; a well-trained
|
||||
/// capture stays roughly in `[-1, 1]`, but this generator does not clamp.
|
||||
///
|
||||
/// > Note: An importer for external NAM `.nam` / Proteus JSON model files onto
|
||||
/// > ``NeuralAmpModel`` is a planned follow-up; construct a `NeuralAmpModel` directly for now.
|
||||
/// > Note: Load a GuitarML Proteus / NeuralPi JSON model with ``ProteusModelImporter``, or
|
||||
/// > construct a ``NeuralAmpModel`` directly. A binary NAM `.nam` importer is a planned follow-up.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to process (dry guitar DI).
|
||||
|
||||
@@ -20,10 +20,9 @@
|
||||
/// - `biasIH`, `biasHH` — `4·H` each (PyTorch keeps two bias vectors; they are summed).
|
||||
/// - `denseWeight` — `H` entries, `denseBias` — scalar.
|
||||
///
|
||||
/// This is Lyrebird's native, `Codable` container. An importer for external NAM `.nam` /
|
||||
/// Proteus JSON model files is a planned follow-up (it maps those schemas onto this layout);
|
||||
/// it is intentionally not included here so the format mapping can be validated against real
|
||||
/// model files rather than guessed.
|
||||
/// This is Lyrebird's native, `Codable` container. Load a GuitarML Proteus / NeuralPi JSON
|
||||
/// model onto this layout with ``ProteusModelImporter``; a binary NAM `.nam` importer is a
|
||||
/// planned follow-up.
|
||||
public struct NeuralAmpModel: Codable, Sendable {
|
||||
|
||||
/// Number of LSTM hidden units.
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
// ProteusModelImporter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Imports a GuitarML **Proteus / NeuralPi** model JSON into a ``NeuralAmpModel``.
|
||||
///
|
||||
/// Those tools export a single-layer PyTorch LSTM as JSON with two objects:
|
||||
///
|
||||
/// ```json
|
||||
/// { "model_data": { "unit_type": "LSTM", "input_size": 1, "hidden_size": 20,
|
||||
/// "num_layers": 1, "skip": 1, "output_size": 1 },
|
||||
/// "state_dict": { "rec.weight_ih_l0": [[…]], // 4H × input_size
|
||||
/// "rec.weight_hh_l0": [[…]], // 4H × H
|
||||
/// "rec.bias_ih_l0": [ … ], // 4H
|
||||
/// "rec.bias_hh_l0": [ … ], // 4H
|
||||
/// "lin.weight": [[…]], // output_size × H
|
||||
/// "lin.bias": [ … ] } } // output_size
|
||||
/// ```
|
||||
///
|
||||
/// PyTorch stacks the LSTM gates in the order **input, forget, cell, output** (i, f, g, o) —
|
||||
/// the same order ``NeuralAmpModel`` documents — so the tensors flatten straight onto its
|
||||
/// layout. `skip == 1` maps to ``NeuralAmpModel/residual``.
|
||||
///
|
||||
/// Only the single-layer, `input_size == 1`, `output_size == 1`, `unit_type == "LSTM"` shape
|
||||
/// (the Proteus/NeuralPi capture topology `LSTMAmp` runs) is supported; anything else throws.
|
||||
///
|
||||
/// > The model files themselves are **not** redistributed with Lyrebird — this only parses a
|
||||
/// > file the user supplies. GuitarML models are GPL-licensed; keep them out of MIT bundles.
|
||||
public enum ProteusModelImporter {
|
||||
|
||||
/// Errors thrown while importing a Proteus/NeuralPi model.
|
||||
public enum ImportError: Error, Equatable {
|
||||
/// `model_data.unit_type` was not `"LSTM"` (the only recurrent unit `LSTMAmp` runs).
|
||||
case unsupportedUnitType(String)
|
||||
/// A tensor shape (or `input_size`/`output_size`/`num_layers`) was inconsistent with the
|
||||
/// single-layer, mono LSTM topology or with `hidden_size`. The message names the field.
|
||||
case unsupportedShape(String)
|
||||
}
|
||||
|
||||
private static let supportedInputSize: Int = 1
|
||||
private static let supportedOutputSize: Int = 1
|
||||
private static let supportedLayerCount: Int = 1
|
||||
|
||||
/// Parses Proteus/NeuralPi model JSON into a validated ``NeuralAmpModel``.
|
||||
///
|
||||
/// - Parameter data: The raw JSON file contents.
|
||||
/// - Returns: The imported model.
|
||||
/// - Throws: `DecodingError` if the JSON is malformed, or ``ImportError`` if the topology is
|
||||
/// unsupported or a tensor shape is inconsistent with `hidden_size`.
|
||||
public static func model(fromProteusJSON data: Data) throws -> NeuralAmpModel {
|
||||
let file: ProteusFile = try JSONDecoder().decode(ProteusFile.self, from: data)
|
||||
let meta: ProteusFile.ModelData = file.modelData
|
||||
let dict: ProteusFile.StateDict = file.stateDict
|
||||
|
||||
guard meta.unitType.uppercased() == "LSTM" else {
|
||||
throw ImportError.unsupportedUnitType(meta.unitType)
|
||||
}
|
||||
let hidden: Int = meta.hiddenSize
|
||||
guard hidden > 0 else { throw ImportError.unsupportedShape("hidden_size must be > 0; got \(hidden)") }
|
||||
guard meta.numLayers == supportedLayerCount else {
|
||||
throw ImportError.unsupportedShape("only num_layers == 1 is supported; got \(meta.numLayers)")
|
||||
}
|
||||
guard meta.inputSize == supportedInputSize else {
|
||||
throw ImportError.unsupportedShape("only input_size == 1 is supported; got \(meta.inputSize)")
|
||||
}
|
||||
guard meta.outputSize == supportedOutputSize else {
|
||||
throw ImportError.unsupportedShape("only output_size == 1 is supported; got \(meta.outputSize)")
|
||||
}
|
||||
|
||||
let gated: Int = NeuralAmpModel.gateCount * hidden
|
||||
|
||||
// rec.weight_ih_l0: 4H × input_size(1) → 4H (take the single column).
|
||||
guard dict.weightIH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.weight_ih_l0 rows must be 4·hidden (\(gated)); got \(dict.weightIH.count)")
|
||||
}
|
||||
var weightIH: [Double] = [Double](repeating: 0.0, count: gated)
|
||||
for r: Int in 0..<gated {
|
||||
guard dict.weightIH[r].count == supportedInputSize else {
|
||||
throw ImportError.unsupportedShape("rec.weight_ih_l0 row \(r) must have input_size (1) columns; got \(dict.weightIH[r].count)")
|
||||
}
|
||||
weightIH[r] = dict.weightIH[r][0]
|
||||
}
|
||||
|
||||
// rec.weight_hh_l0: 4H × H → flatten row-major to (r·H + j).
|
||||
guard dict.weightHH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.weight_hh_l0 rows must be 4·hidden (\(gated)); got \(dict.weightHH.count)")
|
||||
}
|
||||
var weightHH: [Double] = [Double](repeating: 0.0, count: gated * hidden)
|
||||
for r: Int in 0..<gated {
|
||||
guard dict.weightHH[r].count == hidden else {
|
||||
throw ImportError.unsupportedShape("rec.weight_hh_l0 row \(r) must have hidden (\(hidden)) columns; got \(dict.weightHH[r].count)")
|
||||
}
|
||||
let base: Int = r * hidden
|
||||
for j: Int in 0..<hidden { weightHH[base + j] = dict.weightHH[r][j] }
|
||||
}
|
||||
|
||||
guard dict.biasIH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.bias_ih_l0 must be 4·hidden (\(gated)); got \(dict.biasIH.count)")
|
||||
}
|
||||
guard dict.biasHH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.bias_hh_l0 must be 4·hidden (\(gated)); got \(dict.biasHH.count)")
|
||||
}
|
||||
|
||||
// lin.weight: output_size(1) × H → H.
|
||||
guard dict.linWeight.count == supportedOutputSize, dict.linWeight[0].count == hidden else {
|
||||
throw ImportError.unsupportedShape("lin.weight must be 1 × hidden (\(hidden))")
|
||||
}
|
||||
guard dict.linBias.count == supportedOutputSize else {
|
||||
throw ImportError.unsupportedShape("lin.bias must have output_size (1) entries; got \(dict.linBias.count)")
|
||||
}
|
||||
|
||||
return NeuralAmpModel(
|
||||
hiddenSize: hidden,
|
||||
residual: meta.skip != 0,
|
||||
weightIH: weightIH,
|
||||
weightHH: weightHH,
|
||||
biasIH: dict.biasIH,
|
||||
biasHH: dict.biasHH,
|
||||
denseWeight: dict.linWeight[0],
|
||||
denseBias: dict.linBias[0])
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodable mirror of the Proteus/NeuralPi model-file schema.
|
||||
private struct ProteusFile: Decodable {
|
||||
let modelData: ModelData
|
||||
let stateDict: StateDict
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case modelData = "model_data"
|
||||
case stateDict = "state_dict"
|
||||
}
|
||||
|
||||
struct ModelData: Decodable {
|
||||
let unitType: String
|
||||
let inputSize: Int
|
||||
let hiddenSize: Int
|
||||
let numLayers: Int
|
||||
let outputSize: Int
|
||||
let skip: Int
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case unitType = "unit_type"
|
||||
case inputSize = "input_size"
|
||||
case hiddenSize = "hidden_size"
|
||||
case numLayers = "num_layers"
|
||||
case outputSize = "output_size"
|
||||
case skip
|
||||
}
|
||||
}
|
||||
|
||||
struct StateDict: Decodable {
|
||||
let weightIH: [[Double]]
|
||||
let weightHH: [[Double]]
|
||||
let biasIH: [Double]
|
||||
let biasHH: [Double]
|
||||
let linWeight: [[Double]]
|
||||
let linBias: [Double]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case weightIH = "rec.weight_ih_l0"
|
||||
case weightHH = "rec.weight_hh_l0"
|
||||
case biasIH = "rec.bias_ih_l0"
|
||||
case biasHH = "rec.bias_hh_l0"
|
||||
case linWeight = "lin.weight"
|
||||
case linBias = "lin.bias"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,17 @@
|
||||
|
||||
/// Maps an Int32 counter to [-1, 1].
|
||||
private let grayNoiseScalingFactor: Double = 1.0 / Double(Int32.max)
|
||||
|
||||
/// Scales a Gray-code counter to `[-1, 1]`, clamping the one out-of-range edge.
|
||||
///
|
||||
/// `Int32.max` scales to exactly `1.0`, but `Int32.min` (magnitude one greater) scales to
|
||||
/// ≈ `-1.0000000005`, just below the contract — so the result is clamped. Only that single
|
||||
/// counter value is affected; every other passes through unchanged, preserving the
|
||||
/// bitwise-quantized property (the clamped `-1.0 × Int32.max = -Int32.max` is still integral).
|
||||
/// Factored out so the boundary is unit-testable directly.
|
||||
func grayNoiseClampedScale(_ counter: Int32) -> Double {
|
||||
Swift.max(-1.0, Swift.min(1.0, Double(counter) * grayNoiseScalingFactor))
|
||||
}
|
||||
/// Bit mask to pick a random bit position in 0…31 from the raw PRNG word.
|
||||
private let grayNoiseBitMask: UInt64 = 31
|
||||
|
||||
@@ -44,7 +55,7 @@ public enum GrayNoise {
|
||||
let raw: UInt64 = xorshift64NextRaw(&rngState)
|
||||
let bitPos: Int = Int(raw & grayNoiseBitMask)
|
||||
counter ^= Int32(bitPattern: UInt32(1) << bitPos)
|
||||
return Double(counter) * grayNoiseScalingFactor
|
||||
return grayNoiseClampedScale(counter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,13 +58,36 @@ public final class TriodeStage: GeneratorBase, AudioGenerator {
|
||||
|
||||
private var _dcX1: Double = 0.0
|
||||
private var _dcY1: Double = 0.0
|
||||
/// Cached coupling pole and the sample rate it was computed for, so the `exp` is evaluated only
|
||||
/// when the rate changes (never mid-render), not per block.
|
||||
private var _cachedCouplingPole: Double = 0.0
|
||||
private var _cachedCouplingSampleRate: Double = 0.0
|
||||
/// Coupling-cap corner in Hz, evaluated once at `init` (off the RT thread) into a plain stored
|
||||
/// field so `_computeSamples` never touches a lazily-initialised `static`/global (which would
|
||||
/// pay a `swift_once` lock on first access, on the RT thread).
|
||||
private let _couplingCornerHz: Double = TriodeStage.couplingCornerHz()
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Coupling-cap DC-blocker pole. Shared with `LeakDC`'s audio default so the two stay in
|
||||
/// sync if it is ever retuned. The corner is sample-rate-dependent (≈ a few tens of Hz at
|
||||
/// 44.1 / 48 kHz), matching the `LeakDC` convention.
|
||||
private let couplingPole: Double = leakDCDefaultAudioCoef
|
||||
/// Reference sample rate at which the coupling corner is pinned to the legacy fixed pole.
|
||||
private static let couplingReferenceSampleRate: Double = 44_100.0
|
||||
|
||||
/// Coupling-cap DC-blocker corner in Hz, chosen so the one-pole coefficient equals
|
||||
/// `leakDCDefaultAudioCoef` at ``couplingReferenceSampleRate`` — i.e. identical to the old fixed
|
||||
/// pole at 44.1 kHz (≈ 35 Hz). Unlike the old fixed coefficient, whose corner drifted *up* with
|
||||
/// the sample rate (thinning the low end at 88.2 / 96 kHz+), this corner is held constant in Hz
|
||||
/// across sample rates by recomputing the pole from the live rate (see `_computeSamples`). A pure
|
||||
/// function so no lazy `static` storage is read on the RT thread.
|
||||
static func couplingCornerHz() -> Double {
|
||||
-log(leakDCDefaultAudioCoef) * couplingReferenceSampleRate / (2.0 * Double.pi)
|
||||
}
|
||||
|
||||
/// The DC-blocker pole for a given sample rate, holding the corner at ``couplingCornerHz()``.
|
||||
/// `exp(-2π·fc/Fs)` — equals `leakDCDefaultAudioCoef` at the reference rate. For tests /
|
||||
/// introspection; the render path uses the cached `_couplingCornerHz` instead.
|
||||
static func couplingPole(sampleRate: Double) -> Double {
|
||||
exp(-2.0 * Double.pi * couplingCornerHz() / sampleRate)
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
@@ -114,7 +137,15 @@ public final class TriodeStage: GeneratorBase, AudioGenerator {
|
||||
_biasInput, isGenerator: _biasIsGenerator, graph: graph, count: count)
|
||||
// Subtract the static operating point so only the dynamic (asymmetric) response passes.
|
||||
let biasOffset: Double = tanh(bias)
|
||||
let pole: Double = couplingPole
|
||||
// Recompute the coupling pole only when the sample rate changes, so the DC-blocker corner
|
||||
// stays fixed in Hz across rates (no low-end thinning at high sample rates).
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
if sampleRate != _cachedCouplingSampleRate {
|
||||
// Uses the instance `_couplingCornerHz` (evaluated at init) — no lazy static/global read.
|
||||
_cachedCouplingPole = exp(-2.0 * Double.pi * _couplingCornerHz / sampleRate)
|
||||
_cachedCouplingSampleRate = sampleRate
|
||||
}
|
||||
let pole: Double = _cachedCouplingPole
|
||||
let useFourX: Bool = _oversampleFactor == 4
|
||||
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
|
||||
@@ -7,17 +7,20 @@
|
||||
/// A passive guitar-amplifier tone-stack topology, selecting the resistor/capacitor values
|
||||
/// used by ``ToneStack``.
|
||||
///
|
||||
/// All three classic stacks share the same circuit; only the component values differ. The
|
||||
/// values here match the widely-used Yeh/Smith reference set (the same set used by the Faust
|
||||
/// `tonestacks` library).
|
||||
/// All stacks share the same circuit; only the component values differ. The values here match the
|
||||
/// widely-used Yeh/Smith reference set (the same set used by the Faust `tonestacks` library).
|
||||
///
|
||||
/// - `fender`: Fender Bassman / Twin — scooped mids, bright.
|
||||
/// - `marshall`: Marshall JCM800 — more mid, tighter low end.
|
||||
/// - `vox`: Vox AC30 — a different taper, chimey top.
|
||||
/// - `mesa`: Mesa/Boogie Mark — Fender-derived but a deeper mid scoop and fatter low end.
|
||||
/// - `soldano`: Soldano SLO — Marshall-derived with a tighter slope for high-gain lead.
|
||||
public enum ToneStackModel: String, CaseIterable, Sendable {
|
||||
case fender
|
||||
case marshall
|
||||
case vox
|
||||
case mesa
|
||||
case soldano
|
||||
|
||||
/// Human-readable name for pickers.
|
||||
public var displayName: String {
|
||||
@@ -25,6 +28,8 @@ public enum ToneStackModel: String, CaseIterable, Sendable {
|
||||
case .fender: return "Fender"
|
||||
case .marshall: return "Marshall"
|
||||
case .vox: return "Vox"
|
||||
case .mesa: return "Mesa"
|
||||
case .soldano: return "Soldano"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +39,8 @@ public enum ToneStackModel: String, CaseIterable, Sendable {
|
||||
case .fender: return (250_000.0, 1_000_000.0, 25_000.0, 56_000.0)
|
||||
case .marshall: return (220_000.0, 1_000_000.0, 22_000.0, 33_000.0)
|
||||
case .vox: return (1_000_000.0, 1_000_000.0, 10_000.0, 100_000.0)
|
||||
case .mesa: return (250_000.0, 250_000.0, 25_000.0, 100_000.0)
|
||||
case .soldano: return (250_000.0, 1_000_000.0, 25_000.0, 47_000.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +50,8 @@ public enum ToneStackModel: String, CaseIterable, Sendable {
|
||||
case .fender: return (250.0e-12, 20.0e-9, 20.0e-9)
|
||||
case .marshall: return (470.0e-12, 22.0e-9, 22.0e-9)
|
||||
case .vox: return (50.0e-12, 22.0e-9, 22.0e-9)
|
||||
case .mesa: return (250.0e-12, 100.0e-9, 47.0e-9)
|
||||
case .soldano: return (470.0e-12, 20.0e-9, 20.0e-9)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,21 @@ struct ToneStackTests {
|
||||
#expect(relativeDiff > 0.05, "Fender vs Vox 800 Hz response too close: rel=\(relativeDiff)")
|
||||
}
|
||||
|
||||
@Test func mesaAndSoldanoAreDistinctModels() {
|
||||
// The Mesa (deeper mid scoop) and Soldano (tighter Marshall-derived) stacks must voice
|
||||
// differently from Fender and from each other at the midrange.
|
||||
let freq: Double = 800.0
|
||||
func midRMS(_ model: ToneStackModel) -> Double {
|
||||
rms(Array(steadyRMS(freqHz: freq, bass: 0.5, mid: 0.5, treble: 0.5, model: model).suffix(engine.blockSize * 100)))
|
||||
}
|
||||
let fender: Double = midRMS(.fender)
|
||||
let mesa: Double = midRMS(.mesa)
|
||||
let soldano: Double = midRMS(.soldano)
|
||||
#expect(abs(mesa - fender) / Swift.max(mesa, fender) > 0.05, "Mesa too close to Fender: mesa=\(mesa) fender=\(fender)")
|
||||
#expect(abs(mesa - soldano) / Swift.max(mesa, soldano) > 0.05, "Mesa too close to Soldano: mesa=\(mesa) soldano=\(soldano)")
|
||||
#expect(abs(soldano - fender) / Swift.max(soldano, fender) > 0.05, "Soldano too close to Fender: soldano=\(soldano) fender=\(fender)")
|
||||
}
|
||||
|
||||
@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,0 +1,122 @@
|
||||
// ProteusModelImporterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdSynth
|
||||
|
||||
@MainActor
|
||||
@Suite("ProteusModelImporter")
|
||||
struct ProteusModelImporterTests {
|
||||
|
||||
private func makeModel(hiddenSize h: Int, residual: Bool) -> NeuralAmpModel {
|
||||
let gated: Int = NeuralAmpModel.gateCount * h
|
||||
let wih: [Double] = (0..<gated).map { 0.2 * Double($0 + 1) }
|
||||
let whh: [Double] = (0..<(gated * h)).map { -0.05 * Double($0 + 1) }
|
||||
let bih: [Double] = (0..<gated).map { 0.01 * Double($0) }
|
||||
let bhh: [Double] = (0..<gated).map { 0.02 * Double($0) }
|
||||
let wout: [Double] = (0..<h).map { 0.3 * Double($0 + 1) }
|
||||
return NeuralAmpModel(
|
||||
hiddenSize: h, residual: residual,
|
||||
weightIH: wih, weightHH: whh, biasIH: bih, biasHH: bhh,
|
||||
denseWeight: wout, denseBias: 0.07)
|
||||
}
|
||||
|
||||
/// Serializes a `NeuralAmpModel` back into the Proteus/NeuralPi file schema (the inverse of
|
||||
/// the importer), so a round-trip proves the flatten/gate mapping is consistent.
|
||||
private func proteusData(from m: NeuralAmpModel, unitType: String = "LSTM") throws -> Data {
|
||||
let h: Int = m.hiddenSize
|
||||
let gated: Int = NeuralAmpModel.gateCount * h
|
||||
let weightIH: [[Double]] = (0..<gated).map { [m.weightIH[$0]] }
|
||||
let weightHH: [[Double]] = (0..<gated).map { r in (0..<h).map { m.weightHH[r * h + $0] } }
|
||||
let linWeight: [[Double]] = [m.denseWeight]
|
||||
let object: [String: Any] = [
|
||||
"model_data": [
|
||||
"unit_type": unitType, "input_size": 1, "hidden_size": h,
|
||||
"num_layers": 1, "output_size": 1, "skip": m.residual ? 1 : 0,
|
||||
],
|
||||
"state_dict": [
|
||||
"rec.weight_ih_l0": weightIH,
|
||||
"rec.weight_hh_l0": weightHH,
|
||||
"rec.bias_ih_l0": m.biasIH,
|
||||
"rec.bias_hh_l0": m.biasHH,
|
||||
"lin.weight": linWeight,
|
||||
"lin.bias": [m.denseBias],
|
||||
],
|
||||
]
|
||||
return try JSONSerialization.data(withJSONObject: object)
|
||||
}
|
||||
|
||||
private func expectClose(_ a: [Double], _ b: [Double], _ label: String) {
|
||||
#expect(a.count == b.count, "\(label): count \(a.count) != \(b.count)")
|
||||
for i: Int in 0..<Swift.min(a.count, b.count) {
|
||||
#expect(abs(a[i] - b[i]) < 1.0e-12, "\(label)[\(i)]: \(a[i]) != \(b[i])")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func importRoundTripsModel() throws {
|
||||
let original: NeuralAmpModel = makeModel(hiddenSize: 20, residual: true)
|
||||
let data: Data = try proteusData(from: original)
|
||||
let imported: NeuralAmpModel = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
|
||||
#expect(imported.hiddenSize == original.hiddenSize)
|
||||
#expect(imported.residual == original.residual)
|
||||
expectClose(imported.weightIH, original.weightIH, "weightIH")
|
||||
expectClose(imported.weightHH, original.weightHH, "weightHH")
|
||||
expectClose(imported.biasIH, original.biasIH, "biasIH")
|
||||
expectClose(imported.biasHH, original.biasHH, "biasHH")
|
||||
expectClose(imported.denseWeight, original.denseWeight, "denseWeight")
|
||||
#expect(abs(imported.denseBias - original.denseBias) < 1.0e-12)
|
||||
}
|
||||
|
||||
@Test func skipZeroMapsToNoResidual() throws {
|
||||
let original: NeuralAmpModel = makeModel(hiddenSize: 4, residual: false)
|
||||
let data: Data = try proteusData(from: original)
|
||||
let imported: NeuralAmpModel = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
#expect(imported.residual == false)
|
||||
}
|
||||
|
||||
@Test func unsupportedUnitTypeThrows() throws {
|
||||
let data: Data = try proteusData(from: makeModel(hiddenSize: 4, residual: true), unitType: "GRU")
|
||||
#expect(throws: ProteusModelImporter.ImportError.self) {
|
||||
_ = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func inconsistentShapeThrows() throws {
|
||||
// hidden_size says 4 but the recurrent matrix rows won't be 16 → shape error.
|
||||
let object: [String: Any] = [
|
||||
"model_data": [
|
||||
"unit_type": "LSTM", "input_size": 1, "hidden_size": 4,
|
||||
"num_layers": 1, "output_size": 1, "skip": 1,
|
||||
],
|
||||
"state_dict": [
|
||||
"rec.weight_ih_l0": [[0.1], [0.2]], // 2 rows, expected 16
|
||||
"rec.weight_hh_l0": [[0.1, 0.2, 0.3, 0.4]],
|
||||
"rec.bias_ih_l0": [0.0, 0.0],
|
||||
"rec.bias_hh_l0": [0.0, 0.0],
|
||||
"lin.weight": [[0.1, 0.2, 0.3, 0.4]],
|
||||
"lin.bias": [0.0],
|
||||
],
|
||||
]
|
||||
let data: Data = try JSONSerialization.data(withJSONObject: object)
|
||||
#expect(throws: ProteusModelImporter.ImportError.self) {
|
||||
_ = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func importedModelRunsInLSTMAmp() throws {
|
||||
// The imported model must drive LSTMAmp without shape errors and produce finite output.
|
||||
let engine: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: 44100)
|
||||
try engine.start()
|
||||
let original: NeuralAmpModel = makeModel(hiddenSize: 8, residual: true)
|
||||
let imported: NeuralAmpModel = try ProteusModelImporter.model(fromProteusJSON: proteusData(from: original))
|
||||
let amp: LSTMAmp = LSTMAmp(input: OscSin.Audio(freq: 220.0, mul: 0.5), model: imported)
|
||||
let out: [Double] = collectBlocks(amp, engine: engine, blocks: 20)
|
||||
#expect(out.allSatisfy { $0.isFinite })
|
||||
#expect(out.contains { abs($0) > 1.0e-6 })
|
||||
}
|
||||
}
|
||||
@@ -110,4 +110,35 @@ struct TriodeStageTests {
|
||||
#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)")
|
||||
}
|
||||
|
||||
@Test func couplingPoleMatchesLegacyAtReferenceRate() {
|
||||
// The sample-rate-aware coupling pole must equal the legacy fixed coefficient at 44.1 kHz,
|
||||
// so the historical 44.1 / 48 kHz voicing is unchanged.
|
||||
#expect(abs(TriodeStage.couplingPole(sampleRate: 44_100.0) - leakDCDefaultAudioCoef) < 1.0e-12)
|
||||
}
|
||||
|
||||
@Test func couplingCornerIsSampleRateInvariant() throws {
|
||||
// The DC-blocker corner must stay fixed in Hz across sample rates — with the old fixed pole
|
||||
// the corner drifted up with Fs and thinned the low end at 88.2 / 96 kHz. Measure |H| at a
|
||||
// low frequency (small amplitude → near-linear) and confirm it matches across rates.
|
||||
let lowHz: Double = 40.0
|
||||
func lowFreqTransfer(atSampleRate rate: Double) throws -> Double {
|
||||
let eng: SynthesisEngine = makeTestEngine(blockSize: 64, sampleRate: rate)
|
||||
try eng.start()
|
||||
let blocks: Int = 400
|
||||
let tailLen: Int = eng.blockSize * 256
|
||||
let sineIn: OscSin.Audio = OscSin.Audio(freq: lowHz, mul: 0.05)
|
||||
let inTail: [Double] = Array(collectBlocks(sineIn, engine: eng, blocks: blocks).suffix(tailLen))
|
||||
let sine: OscSin.Audio = OscSin.Audio(freq: lowHz, mul: 0.05)
|
||||
let stage: TriodeStage = TriodeStage(input: sine, drive: 1.0, bias: 0.0, oversample: 2)
|
||||
let outTail: [Double] = Array(collectBlocks(stage, engine: eng, blocks: blocks).suffix(tailLen))
|
||||
let cps: Double = lowHz / rate
|
||||
return goertzel(outTail, cyclesPerSample: cps) / goertzel(inTail, cyclesPerSample: cps)
|
||||
}
|
||||
let h48: Double = try lowFreqTransfer(atSampleRate: 48_000.0)
|
||||
let h96: Double = try lowFreqTransfer(atSampleRate: 96_000.0)
|
||||
#expect(h48 > 0.5 && h96 > 0.5, "low-frequency transfer implausibly low (48k=\(h48) 96k=\(h96))")
|
||||
#expect(abs(h96 - h48) / h48 < 0.1,
|
||||
"coupling corner drifts with sample rate: |H(40Hz)| 48k=\(h48) 96k=\(h96)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,11 +727,38 @@ struct GrayNoiseTests {
|
||||
}
|
||||
|
||||
@Test func floatValueInValidRange() {
|
||||
let noise: GrayNoise.Audio = GrayNoise.Audio()
|
||||
// Seeded so the suite is deterministic (an unseeded instance previously flaked when the
|
||||
// counter reached Int32.min, whose scaled magnitude is just over 1 — now clamped).
|
||||
let noise: GrayNoise.Audio = GrayNoise.Audio(seed: 7)
|
||||
let v: Double = noise.floatValue(graph: graph)
|
||||
#expect(v >= -1.0 && v <= 1.0)
|
||||
}
|
||||
|
||||
@Test func clampedScaleBoundsExtremes() {
|
||||
// Deterministic boundary check of the scale+clamp math (the RNG walk realistically never
|
||||
// visits Int32.min, so test it directly).
|
||||
#expect(grayNoiseClampedScale(Int32.min) == -1.0)
|
||||
#expect(grayNoiseClampedScale(Int32.max) == 1.0)
|
||||
#expect(grayNoiseClampedScale(0) == 0.0)
|
||||
// Documents why the clamp is needed: unclamped, Int32.min scales below -1.
|
||||
#expect(Double(Int32.min) * (1.0 / Double(Int32.max)) < -1.0)
|
||||
}
|
||||
|
||||
@Test func boundedAcrossManySeeds() {
|
||||
// Broad deterministic sweep guarding the [-1, 1] contract (regression net for the
|
||||
// Int32.min sign-bit-flip edge that the per-sample clamp fixes).
|
||||
for seed: UInt64 in 1...64 {
|
||||
let noise: GrayNoise.Audio = GrayNoise.Audio(seed: seed)
|
||||
for _ in 0..<8 {
|
||||
let samples: [Double] = noise.calculatedSamples(graph: graph, count: blockSize)[0]
|
||||
for s: Double in samples.prefix(blockSize) {
|
||||
#expect(s >= -1.0 && s <= 1.0, "seed \(seed) produced out-of-range \(s)")
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test func outputIsBitwiseQuantized() {
|
||||
// Every sample × Int32.max should be exactly representable as an integer.
|
||||
let noise: GrayNoise.Audio = GrayNoise.Audio(seed: 99)
|
||||
|
||||
@@ -458,7 +458,7 @@ ToneStack(input: sig, bass: 0.5, mid: 0.7, treble: 0.5, model: .marshall)
|
||||
**Parameters:**
|
||||
- `input`: Signal to filter.
|
||||
- `bass` / `mid` / `treble`: Controls in `[0, 1]` (clamped). Bass uses an exponential taper; mid/treble are linear. Default `0.5`.
|
||||
- `model`: `ToneStackModel` — `.fender` / `.marshall` / `.vox` (component values). Set at init. Default `.fender`.
|
||||
- `model`: `ToneStackModel` — `.fender` / `.marshall` / `.vox` / `.mesa` / `.soldano` (component values). Set at init. Default `.fender`.
|
||||
- Companion type: `ToneStackModel`.
|
||||
|
||||
---
|
||||
@@ -2683,5 +2683,21 @@ let model = NeuralAmpModel(hiddenSize: 20, residual: true,
|
||||
let amp = LSTMAmp(input: di, model: model)
|
||||
```
|
||||
|
||||
An importer for external NAM `.nam` / GuitarML Proteus JSON model files onto `NeuralAmpModel`
|
||||
is a planned follow-up (it maps those schemas onto the documented weight layout).
|
||||
GuitarML Proteus / NeuralPi JSON models load via `ProteusModelImporter` (below). A binary NAM
|
||||
`.nam` importer remains a planned follow-up.
|
||||
|
||||
### ProteusModelImporter
|
||||
|
||||
Imports a GuitarML **Proteus / NeuralPi** model JSON (single-layer PyTorch LSTM, `unit_type`
|
||||
`"LSTM"`, `input_size`/`output_size` 1) into a `NeuralAmpModel` for `LSTMAmp`. The tensors flatten
|
||||
straight onto `NeuralAmpModel`'s layout (PyTorch gate order i,f,g,o); `skip == 1` → `residual`.
|
||||
Unsupported topologies or inconsistent tensor shapes throw.
|
||||
|
||||
```swift
|
||||
let data = try Data(contentsOf: modelURL) // a user-supplied .json
|
||||
let model = try ProteusModelImporter.model(fromProteusJSON: data)
|
||||
let amp = LSTMAmp(input: di, model: model)
|
||||
```
|
||||
|
||||
> Model files are **not** redistributed with Lyrebird — this only parses a file the user
|
||||
> supplies. GuitarML models are GPL-licensed; keep them out of MIT-licensed bundles.
|
||||
|
||||
Reference in New Issue
Block a user