Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 22 additions & 37 deletions NAM/convnet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -156,21 +156,11 @@ void nam::convnet::_Head::process_(const Eigen::MatrixXf& input, Eigen::MatrixXf
const long i_end) const
{
const long length = i_end - i_start;
const long out_channels = this->_weight.rows();

// Resize output to (out_channels x length)
output.resize(out_channels, length);

// Extract input slice: (in_channels x length)
Eigen::MatrixXf input_slice = input.middleCols(i_start, length);

// Compute output = weight * input_slice: (out_channels x in_channels) * (in_channels x length) = (out_channels x
// length)
output.noalias() = this->_weight * input_slice;

// Add bias to each column: output.colwise() += bias
// output is (out_channels x length), bias is (out_channels x 1), so colwise() += works
output.colwise() += this->_bias;
// Write into the pre-sized left columns instead of resizing and copying a slice (issue #350).
auto output_block = output.leftCols(length);
output_block.noalias() = this->_weight * input.middleCols(i_start, length);
output_block.colwise() += this->_bias;
}

nam::convnet::ConvNet::ConvNet(const int in_channels, const int out_channels, const int channels,
Expand Down Expand Up @@ -214,35 +204,21 @@ void nam::convnet::ConvNet::process(NAM_SAMPLE** input, NAM_SAMPLE** output, con
// and sum outputs to each output channel (simple implementation)
// This can be extended later for more sophisticated cross-channel processing

// Convert input buffers to matrix for first layer (stack input channels)
Eigen::MatrixXf input_matrix(in_channels, num_frames);
// Fill the reusable input matrix for the first layer (stack input channels).
const long i_start = this->_input_buffer_offset;
for (int ch = 0; ch < in_channels; ch++)
{
for (int i = 0; i < num_frames; i++)
input_matrix(ch, i) = this->_input_buffers[ch][i_start + i];
this->_input_matrix(ch, i) = this->_input_buffers[ch][i_start + i];
}

// Process through ConvNetBlock layers
// Each block now uses Conv1D's internal buffers via Process() and GetOutput()
// Chain blocks through their pre-sized buffers: Conv1D::Process only reads
// leftCols(num_frames), so none of these hand-offs need a copy (issue #350).
const Eigen::MatrixXf* block_input = &this->_input_matrix;
for (size_t i = 0; i < this->_blocks.size(); i++)
{
// Get input for this block
Eigen::MatrixXf block_input;
if (i == 0)
{
// First block uses the input matrix
block_input = input_matrix;
}
else
{
// Subsequent blocks use output from previous block
auto prev_output = this->_blocks[i - 1].GetOutput(num_frames);
block_input = prev_output; // Copy to matrix
}

// Process block (handles Conv1D, batchnorm, and activation internally)
this->_blocks[i].Process(block_input, num_frames);
this->_blocks[i].Process(*block_input, num_frames);
block_input = &this->_blocks[i].GetOutputBuffer();
}

// Process head for all output channels at once
Expand All @@ -262,8 +238,7 @@ void nam::convnet::ConvNet::process(NAM_SAMPLE** input, NAM_SAMPLE** output, con
// Copy to the correct location in _block_vals
this->_block_vals[0].block(0, buffer_offset, last_output.rows(), num_frames) = last_output;

// Process head - outputs all channels at once
// Head will resize _head_output internally
// Process head - outputs all channels at once into the pre-sized buffer
this->_head.process_(this->_block_vals[0], this->_head_output, buffer_offset, buffer_i_end);

// Copy to output arrays for each channel
Expand All @@ -287,6 +262,10 @@ void nam::convnet::ConvNet::SetMaxBufferSize(const int maxBufferSize)
{
nam::Buffer::SetMaxBufferSize(maxBufferSize);

// Allocate the reusable hot-path buffers here, off the audio thread (issue #350).
this->_input_matrix.resize(NumInputChannels(), maxBufferSize);
this->_head_output.resize(NumOutputChannels(), maxBufferSize);

// Reset all ConvNetBlock instances with the new buffer size
for (auto& block : _blocks)
{
Expand All @@ -298,6 +277,12 @@ void nam::convnet::ConvNet::_update_buffers_(NAM_SAMPLE** input, const int num_f
{
this->Buffer::_update_buffers_(input, num_frames);

// Defensive growth if a host processes more frames than declared at Reset().
if (this->_input_matrix.rows() != NumInputChannels() || this->_input_matrix.cols() < num_frames)
this->_input_matrix.resize(NumInputChannels(), num_frames);
if (this->_head_output.rows() != NumOutputChannels() || this->_head_output.cols() < num_frames)
this->_head_output.resize(NumOutputChannels(), num_frames);

// All channels use the same buffer size
const long buffer_size = (long)this->_input_buffers[0].size();

Expand Down
7 changes: 6 additions & 1 deletion NAM/convnet.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ class ConvNetBlock
/// \return Block reference to the output
Eigen::Block<Eigen::MatrixXf> GetOutput(const int num_frames);

/// \brief Get the whole output buffer without copying (issue #350)
/// \return Const reference to the output buffer owned by this block
const Eigen::MatrixXf& GetOutputBuffer() const { return this->_output; };

/// \brief Get the number of output channels
/// \return Number of output channels
long get_out_channels() const;
Expand Down Expand Up @@ -156,7 +160,8 @@ class ConvNet : public Buffer
protected:
std::vector<ConvNetBlock> _blocks;
std::vector<Eigen::MatrixXf> _block_vals;
Eigen::MatrixXf _head_output; // (out_channels, num_frames)
Eigen::MatrixXf _input_matrix; // (in_channels, maxBufferSize), reused by the first block (issue #350)
Eigen::MatrixXf _head_output; // (out_channels, maxBufferSize)
_Head _head;
void _verify_weights(const int channels, const std::vector<int>& dilations, const bool batchnorm,
const size_t actual_weights);
Expand Down
9 changes: 9 additions & 0 deletions tools/run_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "test/test_conv1d.cpp"
#include "test/test_conv_1x1.cpp"
#include "test/test_convnet.cpp"
#include "test/test_convnet_realtime_safe.cpp"
#include "test/test_dsp.cpp"
#include "test/test_film.cpp"
#include "test/test_film_realtime_safe.cpp"
Expand Down Expand Up @@ -256,6 +257,14 @@ int main()
test_convnet::test_convnet_prewarm();
test_convnet::test_convnet_multiple_calls();

// ConvNet real-time safety tests (issue #350)
test_convnet_realtime_safe::test_convnet_process_single_block_realtime_safe();
test_convnet_realtime_safe::test_convnet_process_multiple_blocks_realtime_safe();
test_convnet_realtime_safe::test_convnet_process_batchnorm_realtime_safe();
test_convnet_realtime_safe::test_convnet_process_multichannel_realtime_safe();
test_convnet_realtime_safe::test_convnet_process_varying_frames_realtime_safe();
test_convnet_realtime_safe::test_convnet_process_consecutive_calls_realtime_safe();

// LSTM tests
test_lstm::test_lstm_basic();
test_lstm::test_lstm_multiple_layers();
Expand Down
161 changes: 161 additions & 0 deletions tools/test/test_convnet_realtime_safe.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Test to verify ConvNet::process is real-time safe (no allocations/frees).
//
// Regression test for upstream issue #350 ("ConvNet::process() allocates and
// frees on every call"). The ConvNet counterpart of the LSTM fix for #218.
// Every hand-off between layers must use pre-sized buffers because process()
// runs on the audio thread.

#include <Eigen/Dense>
#include <cassert>
#include <cmath>
#include <string>
#include <vector>

#include "NAM/convnet.h"
#include "allocation_tracking.h"

namespace test_convnet_realtime_safe
{
using namespace allocation_tracking;

static const auto kActivation = nam::activations::ActivationConfig::simple(nam::activations::ActivationType::ReLU);

// Self-consistent weight vector for a ConvNet with the given shape.
// Layout: per block, Conv1D weights (kernel=2, row-major), optional Conv1D
// bias, optional batchnorm (mean, var, weight, bias, eps); then head weights
// (out_channels x channels, row-major) and head biases.
static std::vector<float> make_weights(const int in_channels, const int out_channels, const int channels,
const std::vector<int>& dilations, const bool batchnorm)
{
std::vector<float> weights;
for (size_t i = 0; i < dilations.size(); i++)
{
const int block_in = (i == 0) ? in_channels : channels;
const int num_conv_weights = 2 * block_in * channels + (batchnorm ? 0 : channels);
for (int j = 0; j < num_conv_weights; j++)
weights.push_back(0.1f); // small weights for numerical stability
if (batchnorm)
{
for (int j = 0; j < 4 * channels; j++)
weights.push_back((j < channels || j >= 3 * channels) ? 0.0f : 1.0f); // mean, var, weight, bias
weights.push_back(1e-5f); // eps
}
}
for (int j = 0; j < out_channels * channels; j++)
weights.push_back(0.1f); // head weight
for (int j = 0; j < out_channels; j++)
weights.push_back(0.0f); // head bias
return weights;
}

static void check_no_allocations(const int in_channels, const int out_channels, const int channels,
const std::vector<int>& dilations, const bool batchnorm, const int max_buffer_size,
const int num_frames, const char* test_name)
{
std::vector<float> weights = make_weights(in_channels, out_channels, channels, dilations, batchnorm);
nam::convnet::ConvNet convnet(in_channels, out_channels, channels, dilations, batchnorm, kActivation, weights,
48000.0);

// Reset + prewarm move all one-time allocations before tracking starts.
convnet.Reset(48000.0, max_buffer_size);
convnet.prewarm();

std::vector<std::vector<NAM_SAMPLE>> input_bufs(in_channels, std::vector<NAM_SAMPLE>(num_frames, 0.25f));
std::vector<std::vector<NAM_SAMPLE>> output_bufs(out_channels, std::vector<NAM_SAMPLE>(num_frames, 0.0f));
std::vector<NAM_SAMPLE*> input_ptrs(in_channels);
std::vector<NAM_SAMPLE*> output_ptrs(out_channels);
for (int ch = 0; ch < in_channels; ch++)
input_ptrs[ch] = input_bufs[ch].data();
for (int ch = 0; ch < out_channels; ch++)
output_ptrs[ch] = output_bufs[ch].data();

// One extra warm-up block at this frame count, outside tracking.
convnet.process(input_ptrs.data(), output_ptrs.data(), num_frames);

run_allocation_test_no_allocations(
nullptr, [&]() { convnet.process(input_ptrs.data(), output_ptrs.data(), num_frames); }, nullptr, test_name);

for (int ch = 0; ch < out_channels; ch++)
for (int i = 0; i < num_frames; i++)
assert(std::isfinite(output_bufs[ch][i]));
}

// One block: the input matrix was allocated per call before the fix.
void test_convnet_process_single_block_realtime_safe()
{
check_no_allocations(/*in*/ 1, /*out*/ 1, /*channels*/ 2, {1}, /*batchnorm*/ false, /*max*/ 64, /*frames*/ 64,
"ConvNet process (1 block)");
}

// Several blocks: the inter-block copies were allocated per call.
void test_convnet_process_multiple_blocks_realtime_safe()
{
check_no_allocations(/*in*/ 1, /*out*/ 1, /*channels*/ 2, {1, 2, 4}, /*batchnorm*/ false, /*max*/ 128,
/*frames*/ 128, "ConvNet process (3 blocks)");
}

// Batchnorm path must remain allocation-free too.
void test_convnet_process_batchnorm_realtime_safe()
{
check_no_allocations(/*in*/ 1, /*out*/ 1, /*channels*/ 2, {1, 2}, /*batchnorm*/ true, /*max*/ 64, /*frames*/ 64,
"ConvNet process (batchnorm)");
}

// Multi-channel input/output.
void test_convnet_process_multichannel_realtime_safe()
{
check_no_allocations(/*in*/ 2, /*out*/ 2, /*channels*/ 2, {1, 2}, /*batchnorm*/ false, /*max*/ 64, /*frames*/ 32,
"ConvNet process (2in/2out)");
}

// Hosts may pass fewer frames than the maximum: the head must not reallocate.
void test_convnet_process_varying_frames_realtime_safe()
{
const int max_buffer_size = 512;
std::vector<float> weights = make_weights(1, 1, 2, {1, 2}, false);
nam::convnet::ConvNet convnet(1, 1, 2, {1, 2}, false, kActivation, weights, 48000.0);
convnet.Reset(48000.0, max_buffer_size);
convnet.prewarm();

for (const int num_frames : {512, 256, 64, 1})
{
std::vector<NAM_SAMPLE> input(num_frames, 0.25f), output(num_frames, 0.0f);
NAM_SAMPLE* input_ptrs[] = {input.data()};
NAM_SAMPLE* output_ptrs[] = {output.data()};
// Warm up this frame count before tracking.
convnet.process(input_ptrs, output_ptrs, num_frames);
run_allocation_test_no_allocations(
nullptr, [&]() { convnet.process(input_ptrs, output_ptrs, num_frames); }, nullptr,
"ConvNet process (varying frames)");
for (int i = 0; i < num_frames; i++)
assert(std::isfinite(output[i]));
}
}

// State persists across calls; consecutive calls must remain allocation-free.
void test_convnet_process_consecutive_calls_realtime_safe()
{
const int num_frames = 48;
std::vector<float> weights = make_weights(1, 1, 2, {1, 2}, false);
nam::convnet::ConvNet convnet(1, 1, 2, {1, 2}, false, kActivation, weights, 48000.0);
convnet.Reset(48000.0, num_frames);
convnet.prewarm();

std::vector<NAM_SAMPLE> input(num_frames, 0.25f), output(num_frames, 0.0f);
NAM_SAMPLE* input_ptrs[] = {input.data()};
NAM_SAMPLE* output_ptrs[] = {output.data()};
convnet.process(input_ptrs, output_ptrs, num_frames);

run_allocation_test_no_allocations(
nullptr,
[&]() {
for (int call = 0; call < 8; call++)
convnet.process(input_ptrs, output_ptrs, num_frames);
},
nullptr, "ConvNet process (8 consecutive calls)");

for (int i = 0; i < num_frames; i++)
assert(std::isfinite(output[i]));
}

} // namespace test_convnet_realtime_safe