From 010a0e53bee7ea8867d8c65917e5bdea3babf60f Mon Sep 17 00:00:00 2001 From: Rik Hemsley Date: Wed, 30 Sep 2026 14:27:37 +0100 Subject: [PATCH] Altered partition layout and per-callback work --- NAM/linear.cpp | 849 ++++++++++++++++++++++++++++--------- NAM/linear.h | 20 +- docs/linear.rst | 78 ++++ tools/BENCHMARK_LINEAR.md | 78 ++-- tools/run_tests.cpp | 2 + tools/test/test_linear.cpp | 126 +++++- 6 files changed, 901 insertions(+), 252 deletions(-) diff --git a/NAM/linear.cpp b/NAM/linear.cpp index 3df2f4f6..41847fec 100644 --- a/NAM/linear.cpp +++ b/NAM/linear.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -22,18 +23,36 @@ struct LinearFFTDispatchEntry nam::LinearFFTPlan plan; }; -// Tuned using tools/bench_linear. The table keeps model-size policy separate -// from the DSP implementation. -constexpr std::array _LINEAR_FFT_DISPATCH{{ - {1024, nam::LinearImplementation::Direct, {128, 256}}, - {2048, nam::LinearImplementation::FFT, {128, 512}}, - {4096, nam::LinearImplementation::FFT, {128, 1024}}, - {8192, nam::LinearImplementation::FFT, {128, 2048}}, - {48000, nam::LinearImplementation::FFT, {64, 4096}}, - {240000, nam::LinearImplementation::FFT, {64, 8192}}, - {std::numeric_limits::max(), nam::LinearImplementation::FFT, {64, 8192}}, +// The table keeps model-size policy separate from the DSP implementation. +// +// Chosen on the 99th-percentile callback. +// +// Every transform lands in one callback, so that callback is what decides +// whether a block is late. +// +// Partitions are uniform. A longer partition means fewer partitions to +// multiply but a longer direct head and a larger transform in the callback +// that runs it. +// +// Direct up to 1024 taps. FFT has the lower mean from 513, but with 16- and +// 32-frame callbacks its transform callback is slower than direct convolution's +// flat profile until well past 1024 taps. +// +// Past a second of impulse response, however, uniform partitions cost too many +// multiplies per sample. +constexpr std::array _LINEAR_FFT_DISPATCH{{ + {1024, nam::LinearImplementation::Direct, {256, 256, 0}}, + {2048, nam::LinearImplementation::FFT, {256, 256, 0}}, + {8192, nam::LinearImplementation::FFT, {512, 512, 0}}, + {48000, nam::LinearImplementation::FFT, {1024, 1024, 0}}, + {240000, nam::LinearImplementation::FFT, {1024, 1024, 8192}}, + {std::numeric_limits::max(), nam::LinearImplementation::FFT, {1024, 1024, 16384}}, }}; +// Direct-head history holds this many maximum-size callbacks beyond the head. +// Moving the head back to the start of the buffer is uncommon and cheap. +constexpr int _FFT_HISTORY_CALLBACKS = 8; + int _ceil_div(const int numerator, const int denominator) { return (numerator + denominator - 1) / denominator; @@ -77,44 +96,404 @@ struct nam::LinearFFTState { using Complex = std::complex; - struct TierChannelState + struct InputChannelState + { + // Contiguous float history. + // + // The direct head's window for every sample of a callback lies inside + // it, and so does each block the transforms read, which is the same + // window at the block's last sample. + std::vector history; + // Where the next callback's first sample goes. Always >= direct_taps. + size_t history_index = 0; + // The spectra of the last num_partitions input blocks, as a ring. + std::vector> spectra; + }; + + struct OutputChannelState { - std::vector input_time; - std::vector> input_spectra; + // The next transform's spectrum, summed over every path into this output. std::vector accumulator; - std::vector ifft_time; - int input_pos = 0; - int spectrum_write_index = 0; - int job_spectrum_write_index = 0; - size_t job_work_index = 0; - int job_ticks_remaining = 0; - long long job_block_start = 0; - bool job_active = false; + // The last two inverse transforms, fft_size samples each. + // + // Sample input_pos of the block being collected takes sample input_pos of + // the newer and block_size + input_pos of the older, so each output sample + // does its own overlap-add as it goes out and no transform pays for all of + // it at once. + std::vector ifft_current; + std::vector ifft_previous; }; - struct Tier + Eigen::FFT fft; + // Samples per partition: also the direct head's length, and how many samples + // arrive between transforms. + int block_size = 0; + int fft_size = 0; + // Bins stored and multiplied: fft_size / 2 + 1. Everything convolved here is + // real, so the upper half of every spectrum mirrors the lower half and the + // real-output inverse transform never reads it. + int num_bins = 0; + int direct_taps = 0; + int num_partitions = 0; + + // A path is one (input, kernel, output) triple; see the Linear class comment. + int num_paths = 0; + std::vector path_input; + std::vector path_kernel; + std::vector path_output; + + // [kernel][partition][bin] + std::vector>> kernel_spectra; + std::vector inputs; + std::vector outputs; + // One block of input followed by zeros: what every forward transform reads. + std::vector transform_input; + + // How many samples of the current block have arrived. + int input_pos = 0; + // The ring slot the next transform writes. + int spectrum_write_index = 0; + + // Partitions 1..num_partitions-1 of the next transform multiply spectra of + // blocks that have already arrived, so that work is done ahead, in the + // callbacks that run no transform; only partition 0 has to wait for the + // block that completes. + // + // One unit is one (path, partition, bin), ordered by path, then partition, + // then bin. pending_done is how far this block has got. + int pending_units = 0; + int pending_done = 0; + + // The tail tier + // + // Partitions of tail.block_size (T) taps from 2T on. Its + // blocks arrive T / block_size times less often than the uniform ones and + // each of its transforms covers that many more taps, so a long impulse + // response costs far fewer multiplies per sample. + // + // A tail block's result is first needed T samples after the block completes, + // and all of its work is spread across that gap: not only the multiplies but + // the transforms too. + // + // A 2T-point transform in one callback would be the large, rare callback + // this design exists to avoid, so each one is done as M = 2T / L transforms + // of L = 2 * block_size points, the uniform tier's own size, plus a + // combining pass (Cooley-Tukey with the L-point transforms as the inner + // step). + // + // The job is a fixed sequence of small steps, and each callback does its + // share by estimated cost, so no callback does more than one L-point + // transform beyond its share of the arithmetic. + // + // The sequence and the arithmetic in each step do not depend on how the + // input is split into callbacks, so neither does the output. + struct TailInputState + { + // The block being collected, and the last complete one. + std::vector collecting; + std::vector ready; + // The last num_partitions blocks' spectra, as a ring. + std::vector> spectra; + // [sub][bin]: the L-point transforms of the block's M interleaved phases. + std::vector> sub_spectra; + }; + struct TailOutputState + { + std::vector accumulator; + // [sub][bin]: the inverse's M phases, before their L-point transforms. + std::vector> sub_spectra; + // Tail output still to be played, indexed by sample count modulo its size. + std::vector ring; + }; + struct Tail { Eigen::FFT fft; - int offset = 0; - int block_size = 0; - int fft_size = 0; - int spectrum_size = 0; + int block_size = 0; // T + int fft_size = 0; // N = 2T + int num_bins = 0; // T + 1 int num_partitions = 0; - bool runs_inline = false; + int sub_size = 0; // L + int num_subs = 0; // M = N / L + int sub_bins = 0; // L / 2 + 1 + // twiddle[k] = exp(-2 pi i k / N) + std::vector twiddle; + // [kernel][partition][bin] std::vector>> kernel_spectra; - std::vector channels; + std::vector inputs; + std::vector outputs; + std::vector sub_time; + int collect_pos = 0; + int ring_size = 0; + int ring_pos = 0; + + // The job for the last complete block. Steps run in this order, each + // indexed by a cursor within its stage: + // 0 forward phase transforms (input, sub) one L-point transform each + // 1 forward combine (input, bin) num_subs multiplies each + // 2 multiplies (path, partition, bin) one each + // 3 inverse split (output, sub, bin) num_subs multiplies each + // 4 inverse phase transforms (output, sub) one L-point transform each + bool job_active = false; + int stage = 0; + int cursor = 0; + long long remaining_cost = 0; + int job_clock = 0; // samples since the block completed + int job_output_pos = 0; // ring index where its output starts + int spectrum_write_index = 0; + long long transform_cost = 0; }; + Tail tail; + bool has_tail_tier = false; - struct OutputChannelState + int tail_stage_count(const int stage) const { - std::vector output_ring; - }; + switch (stage) + { + case 0: return (int)tail.inputs.size() * tail.num_subs; + case 1: return (int)tail.inputs.size() * tail.num_bins; + case 2: return num_paths * tail.num_partitions * tail.num_bins; + case 3: return (int)tail.outputs.size() * tail.num_subs * tail.sub_bins; + case 4: return (int)tail.outputs.size() * tail.num_subs; + } + return 0; + } - int direct_taps = 0; - int output_ring_size = 0; - long long sample_index = 0; - std::vector tiers; - std::vector output_channels; + long long tail_step_cost(const int stage) const + { + return stage == 0 || stage == 4 ? tail.transform_cost : stage == 2 ? 1 : tail.num_subs; + } + + long long tail_job_cost() const + { + long long cost = 0; + for (int stage = 0; stage < 5; ++stage) + cost += (long long)tail_stage_count(stage) * tail_step_cost(stage); + return cost; + } + + // X[k] of phase `sub`'s L-point spectrum, for any k: the stored half and its + // conjugate mirror. + static Complex half_bin(const std::vector& spectrum, const int size, int k) + { + k %= size; + return k <= size / 2 ? spectrum[k] : std::conj(spectrum[size - k]); + } + + void tail_step(const int stage, const int index) + { + const int M = tail.num_subs; + const int N = tail.fft_size; + const int L = tail.sub_size; + switch (stage) + { + case 0: + { + // Phase `sub` of the zero-padded block: x[M * n + sub]. + auto& input = tail.inputs[index / M]; + const int sub = index % M; + for (int n = 0; n < L; ++n) + { + const int at = M * n + sub; + tail.sub_time[n] = at < tail.block_size ? input.ready[at] : 0.0f; + } + tail.fft.fwd(input.sub_spectra[sub].data(), tail.sub_time.data(), L); + break; + } + case 1: + { + auto& input = tail.inputs[index / tail.num_bins]; + const int k = index % tail.num_bins; + Complex sum = half_bin(input.sub_spectra[0], L, k); + for (int sub = 1; sub < M; ++sub) + sum += tail.twiddle[(int)(((long long)sub * k) % N)] * half_bin(input.sub_spectra[sub], L, k); + input.spectra[tail.spectrum_write_index][k] = sum; + break; + } + case 3: + { + auto& output = tail.outputs[index / (M * tail.sub_bins)]; + const int within = index % (M * tail.sub_bins); + const int sub = within / tail.sub_bins; + const int k = within % tail.sub_bins; + Complex sum{}; + for (int q = 0; q < M; ++q) + { + const int bin = k + L * q; + const Complex x = bin <= tail.block_size ? output.accumulator[bin] : std::conj(output.accumulator[N - bin]); + sum += x * std::conj(tail.twiddle[(int)(((long long)bin * sub) % N)]); + } + output.sub_spectra[sub][k] = sum; + break; + } + case 4: + { + auto& output = tail.outputs[index / M]; + const int sub = index % M; + tail.fft.inv(tail.sub_time.data(), output.sub_spectra[sub].data(), L); + // The L-point inverse divides by L; the whole transform divides by N. + const float scale = 1.0f / (float)M; + for (int n = 0; n < L; ++n) + { + const int at = M * n + sub; + // Two T-long pieces convolve to 2T - 1 samples; the last is wrap-around. + if (at == N - 1) + continue; + int pos = tail.job_output_pos + at; + if (pos >= tail.ring_size) + pos -= tail.ring_size; + output.ring[pos] += tail.sub_time[n] * scale; + } + break; + } + } + } + + void tail_multiply_add(const int path, const int partition, const int bin_begin, const int bin_end) + { + int input_index = tail.spectrum_write_index - partition; + if (input_index < 0) + input_index += tail.num_partitions; + const Complex* x = tail.inputs[path_input[path]].spectra[input_index].data(); + const Complex* h = tail.kernel_spectra[path_kernel[path]][partition].data(); + Complex* accumulator = tail.outputs[path_output[path]].accumulator.data(); + for (int bin = bin_begin; bin < bin_end; ++bin) + accumulator[bin] += x[bin] * h[bin]; + } + + // Up to `budget` of the job's estimated cost, in order. Always makes + // progress if there is any work left. + void tail_work(long long budget) + { + while (tail.job_active && budget > 0) + { + const int count = tail_stage_count(tail.stage); + if (tail.cursor >= count) + { + if (++tail.stage == 5) + { + tail.job_active = false; + if (++tail.spectrum_write_index == tail.num_partitions) + tail.spectrum_write_index = 0; + } + tail.cursor = 0; + continue; + } + if (tail.stage == 2) + { + const int units_per_path = tail.num_partitions * tail.num_bins; + const int path = tail.cursor / units_per_path; + const int within = tail.cursor - path * units_per_path; + const int partition = within / tail.num_bins; + const int bin = within - partition * tail.num_bins; + const int bin_end = (int)std::min(tail.num_bins, bin + budget); + tail_multiply_add(path, partition, bin, bin_end); + tail.cursor += bin_end - bin; + budget -= bin_end - bin; + tail.remaining_cost -= bin_end - bin; + } + else + { + tail_step(tail.stage, tail.cursor++); + const long long cost = tail_step_cost(tail.stage); + budget -= cost; + tail.remaining_cost -= cost; + } + } + } + + // One input sample, already in every input channel's history at `index`, + // has been played. The tail's output for it was read before it arrived. + void tail_advance(const size_t index) + { + for (size_t ch = 0; ch < tail.inputs.size(); ++ch) + tail.inputs[ch].collecting[tail.collect_pos] = inputs[ch].history[index]; + if (tail.job_active) + ++tail.job_clock; + if (++tail.collect_pos == tail.block_size) + { + // The previous block's job is due now; with regular callbacks there is + // nothing left of it. + tail_work(std::numeric_limits::max()); + for (auto& input : tail.inputs) + input.collecting.swap(input.ready); + tail.collect_pos = 0; + for (auto& output : tail.outputs) + std::fill(output.accumulator.begin(), output.accumulator.end(), Complex{}); + tail.job_active = true; + tail.stage = 0; + tail.cursor = 0; + tail.remaining_cost = tail_job_cost(); + tail.job_clock = 0; + // The block started T - 1 samples ago; its output starts 2T after that. + tail.job_output_pos = (tail.ring_pos + 1 + tail.block_size) % tail.ring_size; + } + if (++tail.ring_pos == tail.ring_size) + tail.ring_pos = 0; + } + + // accumulator += input spectrum * kernel spectrum, for one path and one + // partition over [bin_begin, bin_end), pairing the partition with the input + // block it multiplies in the transform at spectrum_write_index. + void multiply_add(const int path, const int partition, const int bin_begin, const int bin_end) + { + int input_index = spectrum_write_index - partition; + if (input_index < 0) + input_index += num_partitions; + const Complex* x = inputs[path_input[path]].spectra[input_index].data(); + const Complex* h = kernel_spectra[path_kernel[path]][partition].data(); + Complex* accumulator = outputs[path_output[path]].accumulator.data(); + for (int bin = bin_begin; bin < bin_end; ++bin) + accumulator[bin] += x[bin] * h[bin]; + } + + // The next `units` of the pending work. + void do_pending(const int units) + { + const int units_per_path = (num_partitions - 1) * num_bins; + const int end = std::min(pending_units, pending_done + units); + while (pending_done < end) + { + const int path = pending_done / units_per_path; + const int within_path = pending_done - path * units_per_path; + const int partition = 1 + within_path / num_bins; + const int bin = within_path - (partition - 1) * num_bins; + const int bin_end = std::min(num_bins, bin + (end - pending_done)); + multiply_add(path, partition, bin, bin_end); + pending_done += bin_end - bin; + } + } + + // A block has just completed at sample `frame` of the current callback. + void transform(const int frame) + { + for (auto& input : inputs) + { + const float* block = input.history.data() + input.history_index + frame + 1 - block_size; + std::copy_n(block, block_size, transform_input.begin()); + fft.fwd(input.spectra[spectrum_write_index].data(), transform_input.data(), fft_size); + } + + // Whatever the callbacks since the last transform left undone, then + // partition 0, the only one whose input spectrum did not exist until now. + do_pending(pending_units - pending_done); + for (int path = 0; path < num_paths; ++path) + multiply_add(path, 0, 0, num_bins); + + for (auto& output : outputs) + { + output.ifft_current.swap(output.ifft_previous); + fft.inv(output.ifft_current.data(), output.accumulator.data(), fft_size); + // Two block_size-long pieces convolve to 2 * block_size - 1 samples; the + // transform's last sample is circular wrap-around. + output.ifft_current[fft_size - 1] = 0.0f; + std::fill(output.accumulator.begin(), output.accumulator.end(), Complex{}); + } + + pending_done = 0; + input_pos = 0; + if (++spectrum_write_index == num_partitions) + spectrum_write_index = 0; + } }; nam::Linear::Linear(const int in_channels, const int out_channels, const int receptive_field, const bool _bias, @@ -229,91 +608,174 @@ void nam::Linear::_configure_fft_state() this->_fft_state = std::make_unique(); auto& state = *this->_fft_state; const auto plan = linear::select_fft_plan(this->_receptive_field); + + // The transforms read their block from the direct head's window, and the + // first partition's output starts where the head ends. + assert(plan.direct_taps == plan.max_partition_size); + const int in_channels = NumInputChannels(); + const int out_channels = NumOutputChannels(); + const int kernels = (int)this->_impulse_response.size(); + + state.block_size = plan.max_partition_size; + state.fft_size = 2 * state.block_size; + state.num_bins = state.fft_size / 2 + 1; + + // Without this, the forward transform computes the lower half and then copies + // conjugates into the upper half, which would then be multiplied for nothing. + state.fft.SetFlag(Eigen::FFT::HalfSpectrum); state.direct_taps = std::min(this->_receptive_field, plan.direct_taps); - state.sample_index = 0; - this->_fft_direct_weight.resize(this->_impulse_response.size()); - for (size_t k = 0; k < this->_impulse_response.size(); ++k) + // A tail tier takes over at 2 * its partition size, making sense only + // when there are several of its partitions before that mark. + const int tail_size = plan.tail_partition_size; + state.has_tail_tier = tail_size > 0 && this->_receptive_field > 2 * tail_size; + assert(!state.has_tail_tier || (tail_size % state.block_size == 0 && tail_size >= 2 * state.block_size)); + + const int uniform_end = state.has_tail_tier ? 2 * tail_size : this->_receptive_field; + state.num_partitions = + uniform_end > state.direct_taps ? _ceil_div(uniform_end - state.direct_taps, state.block_size) : 0; + + state.num_paths = std::max(in_channels, out_channels); + state.path_input.resize(state.num_paths); + state.path_kernel.resize(state.num_paths); + state.path_output.resize(state.num_paths); + + for (int path = 0; path < state.num_paths; ++path) + { + state.path_input[path] = in_channels == 1 ? 0 : path; + state.path_kernel[path] = this->_kernel_index(path); + state.path_output[path] = out_channels == 1 ? 0 : path; + } + + const long long pending_units = + state.num_partitions > 1 ? (long long)state.num_paths * (state.num_partitions - 1) * state.num_bins : 0; + + if (pending_units > std::numeric_limits::max()) + throw std::length_error("Linear impulse response is too large for the FFT path"); + + state.pending_units = (int)pending_units; + state.pending_done = 0; + state.input_pos = 0; + state.spectrum_write_index = 0; + + this->_fft_direct_weight.resize(kernels); + + for (int k = 0; k < kernels; ++k) { this->_fft_direct_weight[k].resize(state.direct_taps); for (int i = 0; i < state.direct_taps; ++i) this->_fft_direct_weight[k](i) = this->_impulse_response[k][state.direct_taps - 1 - i]; } - // The inline tier covers [head, 4 * head). Every subsequent power-of-two - // tier starts at twice its block size, which gives it one full block of - // scheduling slack. Once the tuned maximum block size is reached, the last - // tier simply contains as many uniform partitions as are needed. - int offset = state.direct_taps; - int block_size = state.direct_taps; - while (offset < this->_receptive_field) + state.kernel_spectra.resize(kernels); + std::vector kernel_time(state.fft_size, 0.0f); + for (int k = 0; k < kernels; ++k) { - const bool first_tier = state.tiers.empty(); - const int partitions = first_tier ? std::min(3, _ceil_div(this->_receptive_field - offset, block_size)) - : block_size == plan.max_partition_size - ? _ceil_div(this->_receptive_field - offset, block_size) - : std::min(2, _ceil_div(this->_receptive_field - offset, block_size)); - - auto& tier = state.tiers.emplace_back(); - tier.fft.SetFlag(Eigen::FFT::HalfSpectrum); - tier.offset = offset; - tier.block_size = block_size; - tier.fft_size = 2 * block_size; - tier.spectrum_size = block_size + 1; - tier.num_partitions = partitions; - tier.runs_inline = first_tier; - tier.kernel_spectra.resize(this->_impulse_response.size()); - std::vector kernel_time(tier.fft_size, 0.0f); - for (size_t k = 0; k < this->_impulse_response.size(); ++k) + auto& spectra = state.kernel_spectra[k]; + spectra.assign(state.num_partitions, std::vector(state.num_bins)); + for (int partition = 0; partition < state.num_partitions; ++partition) { - auto& spectra = tier.kernel_spectra[k]; - spectra.assign(partitions, std::vector(tier.spectrum_size)); - for (int partition = 0; partition < partitions; partition++) - { - std::fill(kernel_time.begin(), kernel_time.end(), 0.0f); - const int start = offset + partition * block_size; - const int partition_size = std::min(block_size, this->_receptive_field - start); - std::copy_n(this->_impulse_response[k].begin() + start, partition_size, kernel_time.begin()); - tier.fft.fwd(spectra[partition].data(), kernel_time.data(), tier.fft_size); - } + std::fill(kernel_time.begin(), kernel_time.end(), 0.0f); + const int start = state.direct_taps + partition * state.block_size; + const int partition_size = std::min(state.block_size, uniform_end - start); + std::copy_n(this->_impulse_response[k].begin() + start, partition_size, kernel_time.begin()); + state.fft.fwd(spectra[partition].data(), kernel_time.data(), state.fft_size); } + } - offset += partitions * block_size; - if (block_size < plan.max_partition_size) - block_size = std::min(2 * block_size, plan.max_partition_size); + const size_t history_size = + (size_t)state.direct_taps + (size_t)_FFT_HISTORY_CALLBACKS * (size_t)std::max(1, GetMaxBufferSize()); + state.inputs.resize(in_channels); + for (auto& input : state.inputs) + { + input.history.assign(history_size, 0.0f); + input.history_index = state.direct_taps; + input.spectra.assign( + state.num_partitions, std::vector(state.num_bins, LinearFFTState::Complex{})); } + state.outputs.resize(out_channels); + for (auto& output : state.outputs) + { + output.accumulator.assign(state.num_bins, LinearFFTState::Complex{}); + output.ifft_current.assign(state.fft_size, 0.0f); + output.ifft_previous.assign(state.fft_size, 0.0f); + } + state.transform_input.assign(state.fft_size, 0.0f); - const int channels_to_process = std::max(NumInputChannels(), NumOutputChannels()); - int largest_block_size = state.direct_taps; - for (auto& tier : state.tiers) + if (state.has_tail_tier) { - largest_block_size = std::max(largest_block_size, tier.block_size); - tier.channels.resize(channels_to_process); - for (auto& channel : tier.channels) + auto& tail = state.tail; + tail.block_size = tail_size; + tail.fft_size = 2 * tail_size; + tail.num_bins = tail_size + 1; + tail.sub_size = state.fft_size; + tail.num_subs = tail.fft_size / tail.sub_size; + tail.sub_bins = tail.sub_size / 2 + 1; + tail.fft.SetFlag(Eigen::FFT::HalfSpectrum); + tail.num_partitions = _ceil_div(this->_receptive_field - uniform_end, tail_size); + if ((long long)state.num_paths * tail.num_partitions * tail.num_bins > std::numeric_limits::max()) + throw std::length_error("Linear impulse response is too large for the FFT path"); + // An L-point real transform, in multiply-equivalents: about (L / 2) log2 L. + int log2_sub = 0; + while ((1 << log2_sub) < tail.sub_size) + ++log2_sub; + tail.transform_cost = (long long)(tail.sub_size / 2) * log2_sub; + tail.twiddle.resize(tail.fft_size); + const double pi = 3.14159265358979323846; + for (int k = 0; k < tail.fft_size; ++k) + { + const double angle = -2.0 * pi * k / tail.fft_size; + tail.twiddle[k] = LinearFFTState::Complex((float)std::cos(angle), (float)std::sin(angle)); + } + // Kernel spectra are computed off the audio thread, whole. + Eigen::FFT whole; + whole.SetFlag(Eigen::FFT::HalfSpectrum); + tail.kernel_spectra.resize(kernels); + std::vector tail_time(tail.fft_size, 0.0f); + for (int k = 0; k < kernels; ++k) + { + auto& spectra = tail.kernel_spectra[k]; + spectra.assign(tail.num_partitions, std::vector(tail.num_bins)); + for (int partition = 0; partition < tail.num_partitions; ++partition) + { + std::fill(tail_time.begin(), tail_time.end(), 0.0f); + const int start = uniform_end + partition * tail_size; + const int partition_size = std::min(tail_size, this->_receptive_field - start); + std::copy_n(this->_impulse_response[k].begin() + start, partition_size, tail_time.begin()); + whole.fwd(spectra[partition].data(), tail_time.data(), tail.fft_size); + } + } + tail.inputs.resize(in_channels); + for (auto& input : tail.inputs) + { + input.collecting.assign(tail_size, 0.0f); + input.ready.assign(tail_size, 0.0f); + input.spectra.assign( + tail.num_partitions, std::vector(tail.num_bins, LinearFFTState::Complex{})); + input.sub_spectra.assign(tail.num_subs, std::vector(tail.sub_bins)); + } + // Output starts 2T after a block's first sample and lasts 2T - 1. + tail.ring_size = 4 * tail_size; + tail.outputs.resize(out_channels); + for (auto& output : tail.outputs) { - channel.input_time.assign(tier.fft_size, 0.0f); - channel.input_spectra.assign( - tier.num_partitions, std::vector(tier.spectrum_size, LinearFFTState::Complex{})); - channel.accumulator.assign(tier.spectrum_size, LinearFFTState::Complex{}); - channel.ifft_time.assign(tier.fft_size, 0.0f); - // Half-block phase offsets keep power-of-two tiers from all transforming - // in the same callback. The leading inline tier must remain unshifted. - channel.input_pos = tier.runs_inline ? 0 : tier.block_size / 2; + output.accumulator.assign(tail.num_bins, LinearFFTState::Complex{}); + output.sub_spectra.assign(tail.num_subs, std::vector(tail.sub_bins)); + output.ring.assign(tail.ring_size, 0.0f); } + tail.sub_time.assign(tail.sub_size, 0.0f); + std::vector warm_spectrum(tail.sub_bins); + tail.fft.fwd(warm_spectrum.data(), tail.sub_time.data(), tail.sub_size); + tail.fft.inv(tail.sub_time.data(), warm_spectrum.data(), tail.sub_size); } - state.output_ring_size = 4 * largest_block_size; - state.output_channels.resize(channels_to_process); - for (auto& channel : state.output_channels) - channel.output_ring.assign(state.output_ring_size, 0.0f); - - // Create all FFT plans outside the audio callback. - for (auto& tier : state.tiers) + // Create the FFT plans outside the audio callback. + if (state.num_partitions > 0) { - std::vector warm_spectrum(tier.spectrum_size); - std::vector warm_time(tier.fft_size, 0.0f); - tier.fft.fwd(warm_spectrum.data(), warm_time.data(), tier.fft_size); - tier.fft.inv(warm_time.data(), warm_spectrum.data(), tier.fft_size); + std::vector warm_spectrum(state.num_bins); + std::vector warm_time(state.fft_size, 0.0f); + state.fft.fwd(warm_spectrum.data(), warm_time.data(), state.fft_size); + state.fft.inv(warm_time.data(), warm_spectrum.data(), state.fft_size); } } @@ -347,131 +809,96 @@ void nam::Linear::_process_direct(NAM_SAMPLE** input, NAM_SAMPLE** output, const void nam::Linear::_process_fft(NAM_SAMPLE** input, NAM_SAMPLE** output, const int num_frames) { - this->nam::Buffer::_update_buffers_(input, num_frames); - - const int in_channels = NumInputChannels(); - const int out_channels = NumOutputChannels(); - const int channels_to_process = std::max(in_channels, out_channels); auto& state = *this->_fft_state; + if (num_frames <= 0) + return; const int direct_taps = state.direct_taps; - for (int i = 0; i < num_frames; i++) + // The whole callback's input goes into history before any output is + // written, because output may alias input. + for (int ch = 0; ch < NumInputChannels(); ++ch) { - for (int ch = 0; ch < out_channels; ++ch) - output[ch][i] = this->_bias[ch]; - const long direct_offset = this->_input_buffer_offset - direct_taps + i + 1; - for (int ch = 0; ch < channels_to_process; ch++) + auto& channel = state.inputs[ch]; + if (channel.history_index + num_frames > channel.history.size()) { - const int input_channel = in_channels == 1 ? 0 : ch; - const int output_channel = out_channels == 1 ? 0 : ch; - this->_advance_fft_jobs(ch); - - const int ring_index = (int)(state.sample_index % state.output_ring_size); - const float tail = state.output_channels[ch].output_ring[ring_index]; - state.output_channels[ch].output_ring[ring_index] = 0.0f; - - auto input_vec = - Eigen::Map(&this->_input_buffers[input_channel][direct_offset], direct_taps); - output[output_channel][i] += this->_fft_direct_weight[this->_kernel_index(ch)].dot(input_vec); - output[output_channel][i] += tail; - - for (size_t tier_index = 0; tier_index < state.tiers.size(); ++tier_index) + const float* head = channel.history.data() + channel.history_index - direct_taps; + if ((size_t)direct_taps + num_frames > channel.history.size()) { - auto& tier = state.tiers[tier_index]; - auto& channel = tier.channels[ch]; - // Read the buffered input so output writes cannot corrupt aliased input. - channel.input_time[channel.input_pos] = this->_input_buffers[input_channel][this->_input_buffer_offset + i]; - channel.input_pos++; - if (channel.input_pos == tier.block_size) - { - const long long block_start = state.sample_index - tier.block_size + 1; - this->_start_fft_block((int)tier_index, ch, block_start); - channel.input_pos = 0; - } + // Only a callback larger than the maximum buffer size gets here. + std::vector grown((size_t)direct_taps + (size_t)_FFT_HISTORY_CALLBACKS * num_frames, 0.0f); + std::copy_n(head, direct_taps, grown.begin()); + channel.history.swap(grown); } + else + std::memmove(channel.history.data(), head, (size_t)direct_taps * sizeof(float)); + channel.history_index = direct_taps; } - - state.sample_index++; + for (int i = 0; i < num_frames; ++i) + channel.history[channel.history_index + i] = (float)input[ch][i]; } - nam::Buffer::_advance_input_buffer_(num_frames); -} - -void nam::Linear::_advance_fft_jobs(const int channel_index) -{ - for (size_t tier_index = 0; tier_index < this->_fft_state->tiers.size(); ++tier_index) - this->_advance_fft_job((int)tier_index, channel_index); -} - -void nam::Linear::_advance_fft_job(const int tier_index, const int channel_index) -{ - auto& tier = this->_fft_state->tiers[tier_index]; - auto& channel = tier.channels[channel_index]; - if (!channel.job_active) - return; - - const size_t total_work = (size_t)tier.num_partitions * tier.spectrum_size; - const size_t remaining_work = total_work - channel.job_work_index; - const size_t work_this_tick = - (remaining_work + (size_t)channel.job_ticks_remaining - 1) / (size_t)channel.job_ticks_remaining; - const size_t work_end = std::min(total_work, channel.job_work_index + work_this_tick); - while (channel.job_work_index < work_end) + const bool has_tail = state.num_partitions > 0; + bool transformed = false; + for (int i = 0; i < num_frames; ++i) { - const int partition = (int)(channel.job_work_index / (size_t)tier.spectrum_size); - const int bin = (int)(channel.job_work_index % (size_t)tier.spectrum_size); - int input_spectrum_index = channel.job_spectrum_write_index - partition; - if (input_spectrum_index < 0) - input_spectrum_index += tier.num_partitions; - channel.accumulator[bin] += channel.input_spectra[input_spectrum_index][bin] - * tier.kernel_spectra[this->_kernel_index(channel_index)][partition][bin]; - channel.job_work_index++; + for (int ch = 0; ch < NumOutputChannels(); ++ch) + { + NAM_SAMPLE value = this->_bias[ch]; + if (has_tail) + { + const auto& tail = state.outputs[ch]; + value += tail.ifft_previous[state.block_size + state.input_pos] + tail.ifft_current[state.input_pos]; + } + if (state.has_tail_tier) + { + float& pending = state.tail.outputs[ch].ring[state.tail.ring_pos]; + value += pending; + pending = 0.0f; + } + output[ch][i] = value; + } + for (int path = 0; path < state.num_paths; ++path) + { + const auto& channel = state.inputs[state.path_input[path]]; + const auto window = + Eigen::Map(channel.history.data() + channel.history_index + i + 1 - direct_taps, direct_taps); + output[state.path_output[path]][i] += this->_fft_direct_weight[state.path_kernel[path]].dot(window); + } + if (has_tail && ++state.input_pos == state.block_size) + { + state.transform(i); + transformed = true; + } + if (state.has_tail_tier) + state.tail_advance(state.inputs.front().history_index + i); } - channel.job_ticks_remaining--; - if (channel.job_work_index == total_work) - this->_finish_fft_block(tier_index, channel_index); -} -void nam::Linear::_start_fft_block(const int tier_index, const int channel_index, const long long block_start) -{ - auto& tier = this->_fft_state->tiers[tier_index]; - auto& channel = tier.channels[channel_index]; - assert(!channel.job_active); - - channel.job_spectrum_write_index = channel.spectrum_write_index; - auto& current_spectrum = channel.input_spectra[channel.job_spectrum_write_index]; - tier.fft.fwd(current_spectrum.data(), channel.input_time.data(), tier.fft_size); - std::fill(channel.accumulator.begin(), channel.accumulator.end(), LinearFFTState::Complex{}); - channel.job_work_index = 0; - channel.job_ticks_remaining = tier.runs_inline ? 1 : tier.block_size; - channel.job_block_start = block_start; - channel.job_active = true; - - channel.spectrum_write_index++; - if (channel.spectrum_write_index == tier.num_partitions) - channel.spectrum_write_index = 0; - - std::fill(channel.input_time.begin(), channel.input_time.begin() + tier.block_size, 0.0f); - - if (tier.runs_inline) - this->_advance_fft_job(tier_index, channel_index); -} - -void nam::Linear::_finish_fft_block(const int tier_index, const int channel_index) -{ - auto& state = *this->_fft_state; - auto& tier = state.tiers[tier_index]; - auto& channel = tier.channels[channel_index]; - - tier.fft.inv(channel.ifft_time.data(), channel.accumulator.data(), tier.fft_size); + for (auto& channel : state.inputs) + channel.history_index += num_frames; + + // A callback that ran no transform takes its share of the pending + // multiplies: what is left, divided among the callbacks still to come before + // the one that runs the transform, this one included. + // + // With regular callbacks that leaves the transform nothing to catch up on; + // irregular ones are made whole there. A callback of block_size frames or + // more always runs a transform, and so does all of the work there. + if (!transformed && state.pending_done < state.pending_units) + { + const int callbacks_left = (state.block_size - state.input_pos + num_frames - 1) / num_frames; + const int remaining = state.pending_units - state.pending_done; + state.do_pending((remaining + callbacks_left - 1) / callbacks_left); + } - const long long output_start = channel.job_block_start + tier.offset; - auto& output_ring = state.output_channels[channel_index].output_ring; - for (int i = 0; i < tier.fft_size - 1; i++) + // The tail's job likewise: what is left, shared among the callbacks still to + // come before the next tail block completes, this one included. + auto& tail = state.tail; + if (state.has_tail_tier && tail.job_active) { - const int ring_index = (int)((output_start + i) % state.output_ring_size); - output_ring[ring_index] += channel.ifft_time[i]; + const int samples_left = std::max(1, tail.block_size - tail.job_clock); + const long long callbacks_left = (samples_left + num_frames - 1) / num_frames; + state.tail_work((tail.remaining_cost + callbacks_left - 1) / callbacks_left); } - channel.job_active = false; } nam::LinearImplementation nam::linear::parse_implementation(const std::string& implementation) @@ -504,7 +931,9 @@ nam::LinearFFTPlan nam::linear::select_fft_plan(const int receptive_field) { for (const auto& entry : _LINEAR_FFT_DISPATCH) if (receptive_field <= entry.max_taps) + { return entry.plan; + } throw std::runtime_error("No Linear FFT dispatch entry for receptive field"); } diff --git a/NAM/linear.h b/NAM/linear.h index 26721aa5..b952e187 100644 --- a/NAM/linear.h +++ b/NAM/linear.h @@ -7,18 +7,30 @@ namespace nam struct LinearFFTState; +/// \brief How the FFT path splits an impulse response. +/// +/// The first direct_taps taps are convolved directly, which is what keeps the +/// latency at zero. The rest is cut into partitions of max_partition_size taps, +/// convolved by FFT. Those partitions are uniform, and the head is one +/// partition long, so the two sizes are equal. Long impulse responses add a +/// tail tier of larger partitions; see tail_partition_size. struct LinearFFTPlan { int direct_taps; int max_partition_size; + /// Taps per partition in the tail tier, or 0 for none. With a tail, the + /// uniform partitions stop at 2 * tail_partition_size taps and the rest of the + /// impulse response is cut into these larger ones, whose transforms run + /// less often and whose multiplies are spread across the samples in between. + int tail_partition_size = 0; }; /// \brief Selects the convolution engine used by Linear models. enum class LinearImplementation { Auto, ///< Choose direct or FFT convolution from the impulse-response length. - Direct, ///< Legacy per-sample direct convolution. - FFT ///< Zero-latency partitioned FFT convolution. + Direct, ///< Per-sample direct convolution over the whole impulse response. + FFT ///< Zero-latency partitioned FFT convolution: uniform partitions, plus a tail tier for long IRs. }; /// \brief Basic linear model @@ -91,10 +103,6 @@ class Linear : public Buffer void _configure_fft_state(); void _process_direct(NAM_SAMPLE** input, NAM_SAMPLE** output, const int num_frames); void _process_fft(NAM_SAMPLE** input, NAM_SAMPLE** output, const int num_frames); - void _advance_fft_job(const int tier, const int channel); - void _advance_fft_jobs(const int channel); - void _start_fft_block(const int tier, const int channel, const long long block_start); - void _finish_fft_block(const int tier, const int channel); }; namespace linear diff --git a/docs/linear.rst b/docs/linear.rst index 9d0bc4e1..b159a31d 100644 --- a/docs/linear.rst +++ b/docs/linear.rst @@ -58,3 +58,81 @@ Both direct and FFT convolution use these rules. Resetting to a new processing sample rate independently resamples each response from its original training coefficients, leaves biases unchanged, and clears all convolution history. Processing uses preallocated state; construction and reset may allocate. + +Convolution engines +------------------- + +The optional configuration field ``implementation`` selects how the +convolution is computed: ``"auto"`` (the default), ``"direct"`` or ``"fft"``. +Both engines have zero latency and produce the same result up to floating-point +rounding. ``"auto"`` chooses from the impulse-response length at the processing +sample rate, so resetting to a new sample rate can change the engine: + +.. list-table:: + :header-rows: 1 + + * - Taps + - Engine + - Partition + - Tail partition + * - up to 1,024 + - direct + - + - + * - up to 2,048 + - FFT + - 256 + - + * - up to 8,192 + - FFT + - 512 + - + * - up to 48,000 + - FFT + - 1,024 + - + * - up to 240,000 + - FFT + - 1,024 + - 8,192 + * - more + - FFT + - 1,024 + - 16,384 + +**Direct** convolution computes every output sample as a dot product over the +whole impulse response. Its cost per sample is proportional to the length and +the same in every callback. + +**FFT** convolution splits the impulse response into three parts: + +* **Direct head.** The first partition's worth of taps is convolved directly, + sample by sample. This is what keeps the latency at zero. +* **Uniform partitions.** The taps after the head are cut into partitions of + the same size ``B``, each convolved with a ``2B``-point real FFT of the + input, overlap-added as the output is played. A transform runs once every + ``B`` samples. When a block completes, only its forward transform, the first + partition's multiplies and the inverse transform run in that callback; the + other partitions multiply spectra of blocks that have already arrived, and + that work is shared out across the callbacks in between. +* **Tail tier.** Beyond 48,000 taps, the uniform partitions stop at twice the + tail partition size ``T``, and the rest of the impulse response is cut into + partitions of ``T`` taps. A tail block's output is first needed ``T`` samples + after the block completes, and all of its work is spread across that gap, + including its transforms: each ``2T``-point transform is computed as several + ``2B``-point transforms plus a combining pass, so no callback runs a large + transform. Work is shared out by estimated cost among the callbacks that + remain before the result is due; anything left when it is due is done then. + +The FFT engine's output does not depend on how the input is divided into +callbacks. It keeps only the direct head's input history, plus a few +maximum-size callbacks. The direct engine keeps the whole impulse response's +input history and copies it back to the start of its buffer every 32 +maximum-size callbacks. + +Neither engine allocates while processing callbacks no longer than the +maximum buffer size given to ``Reset``. A longer callback makes the input +history grow, which allocates. + +``tools/BENCHMARK_LINEAR.md`` records how the table was chosen and how to +measure it with ``tools/bench_linear``. diff --git a/tools/BENCHMARK_LINEAR.md b/tools/BENCHMARK_LINEAR.md index e1ae6ff5..6fcb95f5 100644 --- a/tools/BENCHMARK_LINEAR.md +++ b/tools/BENCHMARK_LINEAR.md @@ -18,35 +18,55 @@ through the entire requested filter—including a one-minute filter—and compar ## Dispatch tuning -The dispatch table was tuned on an Apple M1 at 48 kHz using the same `-O3` optimization level as the Release plugin. -The main constraint was the 666.67 microsecond deadline of a 32-sample callback. Candidate plans varied direct-head -sizes from 64 through 256 samples and maximum FFT partitions from 1,024 through 32,768 samples. - -The selected FFT plans produced these representative 10-second results (the default dispatcher uses direct -convolution for the 1,024-tap case): - -| Taps | Direct head | Maximum partition | Mean (us) | p99 (us) | Max (us) | Overruns | -|---:|---:|---:|---:|---:|---:|---:| -| 1,024 | 128 | 256 | 2.37 | 10.62 | 55.67 | 0 | -| 2,048 | 128 | 512 | 2.90 | 14.54 | 63.38 | 0 | -| 4,096 | 128 | 1,024 | 3.65 | 23.79 | 58.33 | 0 | -| 8,192 | 128 | 2,048 | 4.63 | 49.12 | 81.79 | 0 | -| 48,000 | 64 | 4,096 | 6.45 | 48.83 | 123.42 | 0 | -| 240,000 | 64 | 8,192 | 8.21 | 91.12 | 218.33 | 0 | -| 1,200,000 | 64 | 8,192 | 14.41 | 99.79 | 297.58 | 0 | -| 2,880,000 | 64 | 8,192 | 24.22 | 112.00 | 324.62 | 0 | - -The old 1,024-sample uniform implementation measured about 2.7--3.1 ms at p99 for the 1,208,121-tap atmospheric -model and overran 32- and 64-sample callback deadlines. The non-uniform plan reduces that periodic burst by more than -an order of magnitude. - -The table favors bounded callback time over the absolute minimum mean: - -- A 64-sample direct head had lower p99 times for long filters; a 128-sample head reduced overhead for 2K--8K filters. -- A 16,384-sample maximum partition slightly reduced mean time for multi-second filters but roughly doubled p99 and - produced deadline outliers. A 4,096 maximum kept transforms smaller but nearly doubled one-minute steady-state cost. -- Direct convolution through 1,024 taps had a flatter callback profile than FFT convolution at essentially the same - mean cost, so `Auto` selects it for that range. +The FFT path partitions uniformly. The first partition's worth of taps is convolved directly, which keeps the latency +at zero, and every partition behind it is the same size, so every transform is the same size and none of them is ever +the large one. Partitions after the first multiply the spectra of blocks that have already arrived, so that work is +spread across the callbacks that run no transform: only the forward transform, the first partition's multiplies and +the inverse transform land in the callback where a block completes. + +| Taps | Implementation | Direct head | Partition | +|---:|---|---:|---:| +| up to 1,024 | direct | | | +| up to 2,048 | FFT | 256 | 256 | +| up to 8,192 | FFT | 512 | 512 | +| up to 48,000 | FFT | 1,024 | 1,024 | +| up to 240,000 | FFT | 1,024 | 1,024, then 8,192 from 16,384 taps | +| more | FFT | 1,024 | 1,024, then 16,384 from 32,768 taps | + +Past a second of impulse response, uniform partitions would cost too many multiplies per sample, so a tail tier of +larger partitions takes over at twice its partition size. A tail block's result is first needed one tail block after it +completes, and all its work is spread across that gap. That includes its transforms: each is done as several transforms +of the uniform tier's size plus a combining pass, so no callback runs a large transform. + +The FFT path keeps only the direct head's history: a few maximum-size callbacks beyond the head, moved back to the +start of its buffer when it fills. The direct implementation keeps the whole impulse response's worth of history, and +copies it back to the start of its buffer every 32 maximum-size callbacks. + +The table was chosen on the 99th-percentile callback rather than the mean, with +[NAMBench](https://github.com/rikkus/NAMBench)'s `nam_ir_benchmark` on an Apple M2 and a Raspberry Pi 500 (Cortex-A76) +at 16- to 256-sample callbacks: + +- Direct convolution through 1,024 taps. Forced to FFT, the uniform plan has the lower mean from 513 taps, but at 16- + and 32-sample callbacks its transform callback costs more than direct convolution's flat profile until well past + 1,024 taps. +- A 256-tap partition up to 2,048 taps and 512 up to 8,192 keep the transform callback short while leaving few enough + partitions that their spread multiplies stay cheap. +- Beyond 48,000 taps, the tail tier: without it, the uniform tier's multiplies per sample grow with the impulse + response's length. + +These are `bench_linear` results, FFT forced, 5 seconds each, on a Raspberry Pi 500 pinned to one core at 2.4 GHz. +"Uniform only" is this plan without its tail tier, for comparison: + +| Taps | Callback | Uniform only mean / p99 / max (us) | This plan mean / p99 / max (us) | +|---:|---:|---|---| +| 240,000 | 32 | 25.74 / 46.63 / 50.20 | 13.30 / 51.70 / 74.63 | +| 1,200,000 | 32 | 118.05 / 145.94 / 165.19 | 20.23 / 60.30 / 84.22 | +| 2,880,000 | 16 | 156.86 / 190.78 / 248.83 | 15.30 / 56.11 / 97.00 | +| 2,880,000 | 32 | 295.66 / 367.61 / 457.45 | 27.52 / 64.00 / 88.70 | +| 2,880,000 | 256 | 2,348.98 / 3,303.18 / 3,379.68 | 211.22 / 370.96 / 390.61 | + +On Apple silicon, run `bench_linear` with nothing else busy: it does not ask for a high-priority thread, so macOS may +schedule it on an efficiency core, which roughly doubles every figure in a run. These numbers are hardware-specific. When changing the FFT backend, data layout, or dispatch table, rerun warm and cold-cache tests on every supported architecture and optimize for the worst callback distribution, not only mean CPU. diff --git a/tools/run_tests.cpp b/tools/run_tests.cpp index ee827818..e8425ff4 100644 --- a/tools/run_tests.cpp +++ b/tools/run_tests.cpp @@ -112,6 +112,8 @@ int main() test_linear::test_fft_matches_direct_irregular_chunks(); test_linear::test_auto_selection(); test_linear::test_fft_dispatch_table(); + test_linear::test_fft_output_independent_of_callback_size(); + test_linear::test_fft_tail_tier_impulse_response(); test_linear::test_fft_impulse_response_across_dispatch_sizes(); test_linear::test_parse_implementation(); test_linear::test_direct_process_realtime_safe(); diff --git a/tools/test/test_linear.cpp b/tools/test/test_linear.cpp index 50da1043..84ecf4b3 100644 --- a/tools/test/test_linear.cpp +++ b/tools/test/test_linear.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -147,8 +148,8 @@ void test_auto_selection() assert(cutoff_model.GetRequestedImplementation() == nam::LinearImplementation::Auto); assert(cutoff_model.GetActiveImplementation() == nam::LinearImplementation::Direct); - const auto fft_weights = make_weights(2048, false); - nam::Linear fft_model(1, 1, 2048, false, fft_weights, 48000.0); + const auto fft_weights = make_weights(1025, false); + nam::Linear fft_model(1, 1, 1025, false, fft_weights, 48000.0); assert(fft_model.GetRequestedImplementation() == nam::LinearImplementation::Auto); assert(fft_model.GetActiveImplementation() == nam::LinearImplementation::FFT); } @@ -157,11 +158,122 @@ void test_fft_dispatch_table() { assert(nam::linear::select_implementation(1024) == nam::LinearImplementation::Direct); assert(nam::linear::select_implementation(1025) == nam::LinearImplementation::FFT); - assert(nam::linear::select_fft_plan(1024).direct_taps == 128); - assert(nam::linear::select_fft_plan(8192).max_partition_size == 2048); - assert(nam::linear::select_fft_plan(48000).max_partition_size == 4096); - assert(nam::linear::select_fft_plan(240000).max_partition_size == 8192); - assert(nam::linear::select_fft_plan(2880000).max_partition_size == 8192); + // Uniform partitioning: the direct head is always exactly one partition. + for (const int receptive_field : {1, 1024, 1025, 2048, 2049, 8192, 8193, 48000, 2880000}) + { + const auto plan = nam::linear::select_fft_plan(receptive_field); + assert(plan.direct_taps == plan.max_partition_size); + } + assert(nam::linear::select_fft_plan(1024).max_partition_size == 256); + assert(nam::linear::select_fft_plan(2048).max_partition_size == 256); + assert(nam::linear::select_fft_plan(2049).max_partition_size == 512); + assert(nam::linear::select_fft_plan(8192).max_partition_size == 512); + assert(nam::linear::select_fft_plan(8193).max_partition_size == 1024); + assert(nam::linear::select_fft_plan(2880000).max_partition_size == 1024); + // A tail tier only past a second of impulse response. + assert(nam::linear::select_fft_plan(48000).tail_partition_size == 0); + assert(nam::linear::select_fft_plan(48001).tail_partition_size == 8192); + assert(nam::linear::select_fft_plan(240000).tail_partition_size == 8192); + assert(nam::linear::select_fft_plan(240001).tail_partition_size == 16384); + assert(nam::linear::select_fft_plan(2880000).tail_partition_size == 16384); +} + +// The tail tier, past 48000 taps, splits and spreads its transforms across the +// samples between its blocks. Impulses at a block boundary and away from one, +// in callbacks of several sizes including ones longer than a tail block, must +// each reproduce the impulse response, and two of them must add. +void test_fft_tail_tier_impulse_response() +{ + for (const int taps : {60000, 250000}) + { + const auto weights = make_weights(taps, false); + const int first = 0, second = 20000 + 12345; + const int frames = second + taps + 100; + std::vector input(frames, 0.0); + input[first] = 1.0; + input[second] = -0.5; + for (const std::vector& pattern : std::vector>{{16}, {37}, {256}, {20000}, {1, 300, 7}}) + { + nam::Linear model(1, 1, taps, false, weights, 48000.0, nam::LinearImplementation::FFT); + const auto output = process_model(model, input, pattern); + double max_abs_error = 0.0; + for (int i = 0; i < frames; ++i) + { + double expected = 0.0; + if (i - first < taps) + expected += weights[i - first]; + if (i >= second && i - second < taps) + expected -= 0.5 * weights[i - second]; + max_abs_error = std::max(max_abs_error, std::abs((double)output[i] - expected)); + } + assert(max_abs_error < 5.0e-5); + } + } +} + +// The FFT path's output must not depend on how the input is cut into callbacks: +// every pattern has to reproduce the 64-frame output exactly, not just within a +// tolerance. Multiplies for partitions after the first are spread across the +// callbacks between transforms, and callbacks of at least one partition reach +// every transform with none of that done, so they pin the spread work to the +// result of doing it all at once. +void test_fft_output_independent_of_callback_size() +{ + std::vector> patterns{{1}, {23}, {32}, {48}, {512}, {1024}, {20000}, {1, 64, 7, 512, 33}}; + std::vector random; + uint32_t x = 0x5EED; + for (int i = 0; i < 200; i++) + { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + random.push_back(1 + (int)(x % 700)); + } + patterns.push_back(random); + + for (const auto shape : {std::pair{1, 1}, {1, 2}, {2, 1}}) + for (const int taps : {1000, 2049, 4096, 8192, 60000}) + { + const int inputs = shape.first, outputs = shape.second; + const int kernels = inputs == outputs ? 1 : std::max(inputs, outputs); + std::vector weights; + for (int k = 0; k < kernels; ++k) + { + auto kernel = make_weights(taps, false); + for (auto& value : kernel) + value *= k + 1.0f; + weights.insert(weights.end(), kernel.begin(), kernel.end()); + } + const int frames = 3 * taps + 3000; + std::vector> input(inputs, make_input(frames)); + for (int ch = 1; ch < inputs; ++ch) + for (auto& value : input[ch]) + value *= -0.5; + + const auto run = [&](const std::vector& pattern) { + nam::Linear model(inputs, outputs, taps, false, weights, 48000.0, nam::LinearImplementation::FFT); + model.SetPrewarmOnReset(false); + model.Reset(48000.0, 1024); + std::vector> output(outputs, std::vector(frames)); + std::vector in_ptrs(inputs), out_ptrs(outputs); + int offset = 0; + for (size_t call = 0; offset < frames; ++call) + { + const int count = std::min(pattern[call % pattern.size()], frames - offset); + for (int ch = 0; ch < inputs; ++ch) + in_ptrs[ch] = input[ch].data() + offset; + for (int ch = 0; ch < outputs; ++ch) + out_ptrs[ch] = output[ch].data() + offset; + model.process(in_ptrs.data(), out_ptrs.data(), count); + offset += count; + } + return output; + }; + + const auto expected = run({64}); + for (const auto& pattern : patterns) + assert(run(pattern) == expected); + } } void test_fft_impulse_response_across_dispatch_sizes()