Table of Contents

Class ConvTasNet<T>

Namespace
AiDotNet.Audio.Enhancement
Assembly
AiDotNet.dll

Conv-TasNet: A fully-convolutional time-domain audio separation network.

public class ConvTasNet<T> : AudioNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, IAudioEnhancer<T>

Type Parameters

T

The numeric type used for calculations.

Inheritance
ConvTasNet<T>
Implements
IFullModel<T, Tensor<T>, Tensor<T>>
IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>
IParameterizable<T, Tensor<T>, Tensor<T>>
ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>
IGradientComputable<T, Tensor<T>, Tensor<T>>
Inherited Members
Extension Methods

Remarks

Conv-TasNet (Convolutional Time-domain Audio Separation Network) is a pioneering neural network architecture that operates directly in the time domain, avoiding the phase reconstruction problems of frequency-domain methods.

The architecture consists of three main components:

  • Encoder: Converts waveform to a learned representation using 1D convolutions
  • Separator: Temporal Convolutional Network (TCN) that estimates source masks
  • Decoder: Reconstructs separated waveforms from masked representations

For Beginners: Conv-TasNet is like having multiple microphones that each focus on one speaker in a noisy room. Give it a recording with multiple people talking, and it separates them into individual clean tracks!

Traditional methods convert audio to frequency domain, process it, then convert back. Conv-TasNet works directly on the waveform, which avoids problems with phase reconstruction and often produces cleaner results.

Common use cases:

  • Separating speakers in meeting recordings
  • Isolating vocals from music
  • Removing background noise
  • Speech enhancement for hearing aids
  • Denoising phone calls

Reference: Luo, Y., & Mesgarani, N. (2019). Conv-TasNet: Surpassing Ideal Time-Frequency Magnitude Masking for Speech Separation.

Constructors

ConvTasNet(NeuralNetworkArchitecture<T>, int, int, int, int, int, int, int, int, int, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Initializes a new instance of the ConvTasNet<T> class for native training mode.

public ConvTasNet(NeuralNetworkArchitecture<T> architecture, int sampleRate = 8000, int encoderDim = 512, int kernelSize = 16, int bottleneckDim = 128, int hiddenDim = 512, int numBlocks = 8, int numRepeats = 3, int tcnKernelSize = 3, int numSources = 2, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture defining input/output dimensions.

sampleRate int

Sample rate of input audio (default: 8000 Hz for speech).

encoderDim int

Number of encoder basis functions (default: 512).

kernelSize int

Encoder kernel size in samples (default: 16, about 2ms at 8kHz).

bottleneckDim int

Bottleneck dimension in TCN (default: 128).

hiddenDim int

Hidden dimension in TCN blocks (default: 512).

numBlocks int

Number of TCN blocks per repeat (default: 8).

numRepeats int

Number of TCN repeats (default: 3).

tcnKernelSize int

Kernel size for TCN convolutions (default: 3).

numSources int

Number of sources to separate (default: 2).

optimizer IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>

Optimizer for training. If null, a default Adam optimizer is used.

lossFunction ILossFunction<T>

Loss function. If null, SI-SNR loss is used.

ConvTasNet(NeuralNetworkArchitecture<T>, string, int, int, int, int, OnnxModelOptions?)

Initializes a new instance of the ConvTasNet<T> class for ONNX inference mode.

public ConvTasNet(NeuralNetworkArchitecture<T> architecture, string modelPath, int sampleRate = 8000, int encoderDim = 512, int kernelSize = 16, int numSources = 2, OnnxModelOptions? onnxOptions = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture defining input/output dimensions.

modelPath string

Path to the ONNX model file.

sampleRate int

Sample rate of input audio (default: 8000 Hz).

encoderDim int

Encoder dimension (default: 512).

kernelSize int

Encoder kernel size in samples (default: 16).

numSources int

Number of sources to separate (default: 2).

onnxOptions OnnxModelOptions

Optional ONNX model options.

Exceptions

FileNotFoundException

Thrown when the ONNX model file is not found.

Properties

EncoderDimension

Gets the encoder dimension (number of basis functions).

public int EncoderDimension { get; }

Property Value

int

EncoderKernelSize

Gets the encoder kernel size (window length in samples).

public int EncoderKernelSize { get; }

Property Value

int

EnhancementStrength

Gets or sets the enhancement strength (0.0 = no enhancement, 1.0 = maximum).

public double EnhancementStrength { get; set; }

Property Value

double

Remarks

Higher values provide more noise reduction but may introduce artifacts. Start with 0.5-0.7 for natural-sounding results.

LatencySamples

Gets the processing latency in samples.

public int LatencySamples { get; }

Property Value

int

Remarks

Important for real-time applications. Lower latency means faster response but potentially lower quality enhancement.

NumChannels

Gets the number of audio channels supported.

public int NumChannels { get; }

Property Value

int

NumSources

Gets the number of sources the network separates.

public int NumSources { get; }

Property Value

int

Methods

CreateNewInstance()

Creates a new instance of the same type as this neural network.

protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()

Returns

IFullModel<T, Tensor<T>, Tensor<T>>

A new instance of the same neural network type.

Remarks

For Beginners: This creates a blank version of the same type of neural network.

It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.

Deserialize(byte[])

Deserializes the model state from a byte array.

public override void Deserialize(byte[] data)

Parameters

data byte[]

DeserializeNetworkSpecificData(BinaryReader)

Deserializes network-specific data that was not covered by the general deserialization process.

protected override void DeserializeNetworkSpecificData(BinaryReader reader)

Parameters

reader BinaryReader

The BinaryReader to read the data from.

Remarks

This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.

For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.

Enhance(Tensor<T>)

Enhances audio quality by reducing noise and artifacts.

public Tensor<T> Enhance(Tensor<T> audio)

Parameters

audio Tensor<T>

Input audio tensor with shape [channels, samples] or [samples].

Returns

Tensor<T>

Enhanced audio tensor with the same shape as input.

EnhanceWithReference(Tensor<T>, Tensor<T>)

Enhances audio with a reference signal for echo cancellation.

public Tensor<T> EnhanceWithReference(Tensor<T> audio, Tensor<T> reference)

Parameters

audio Tensor<T>

Input audio (microphone signal).

reference Tensor<T>

Reference audio (speaker playback signal).

Returns

Tensor<T>

Enhanced audio with echo removed.

Remarks

For Beginners: This is for video calls!

The problem: Your microphone picks up sound from your speakers, creating an echo for the other person.

Solution: We know what's playing from the speakers (reference), so we can subtract it from what the microphone picks up.

EstimateNoiseProfile(Tensor<T>)

Estimates the noise profile from a segment of audio.

public void EstimateNoiseProfile(Tensor<T> noiseOnlyAudio)

Parameters

noiseOnlyAudio Tensor<T>

Audio containing only noise (no signal).

Remarks

For Beginners: Some enhancers work better if you tell them what the noise sounds like. Record a few seconds of "silence" (just the background noise) and pass it here.

GetModelMetadata()

Gets the metadata for this neural network model.

public override ModelMetadata<T> GetModelMetadata()

Returns

ModelMetadata<T>

A ModelMetaData object containing information about the model.

InitializeLayers()

Initializes the neural network layers.

protected override void InitializeLayers()

PostprocessOutput(Tensor<T>)

Postprocesses model output.

protected override Tensor<T> PostprocessOutput(Tensor<T> modelOutput)

Parameters

modelOutput Tensor<T>

Returns

Tensor<T>

Predict(Tensor<T>)

Predicts separated sources from input audio.

public override Tensor<T> Predict(Tensor<T> input)

Parameters

input Tensor<T>

Input audio tensor [batch, samples] or [samples].

Returns

Tensor<T>

Separated sources tensor [batch, sources, samples] or [sources, samples].

PreprocessAudio(Tensor<T>)

Preprocesses raw audio waveform for model input.

protected override Tensor<T> PreprocessAudio(Tensor<T> rawAudio)

Parameters

rawAudio Tensor<T>

Returns

Tensor<T>

ProcessChunk(Tensor<T>)

Processes audio in real-time streaming mode.

public Tensor<T> ProcessChunk(Tensor<T> audioChunk)

Parameters

audioChunk Tensor<T>

A small chunk of audio for real-time processing.

Returns

Tensor<T>

Enhanced audio chunk (may have latency).

Remarks

For real-time applications like video calls. The enhancer maintains internal state between calls for continuity.

ResetState()

Resets the internal state of the different layers, clearing any remembered information.

public override void ResetState()

Remarks

This method resets the internal state (hidden state and cell state) of all layers in the network. This is useful when starting to process a new, unrelated sequence or when the network's memory should be cleared before making new predictions.

For Beginners: This clears the neural network's memory to start fresh.

Think of this like:

  • Wiping the slate clean before starting a new task
  • Erasing the neural network's "memory" so past inputs don't influence new predictions
  • Starting fresh when processing a completely new sequence

For example, if you've been using an neural network to analyze one document and now want to analyze a completely different document, you would reset the state first to avoid having the first document influence the analysis of the second one.

Serialize()

Serializes the model state to a byte array.

public override byte[] Serialize()

Returns

byte[]

SerializeNetworkSpecificData(BinaryWriter)

Serializes network-specific data that is not covered by the general serialization process.

protected override void SerializeNetworkSpecificData(BinaryWriter writer)

Parameters

writer BinaryWriter

The BinaryWriter to write the data to.

Remarks

This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.

For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.

Train(Tensor<T>, Tensor<T>)

Trains the model on a batch of mixture-source pairs.

public override void Train(Tensor<T> input, Tensor<T> expected)

Parameters

input Tensor<T>

Mixture tensor [batch, samples].

expected Tensor<T>

Target sources [batch, sources, samples].

UpdateParameters(Vector<T>)

Updates the network's parameters with new values.

public override void UpdateParameters(Vector<T> gradients)

Parameters

gradients Vector<T>

Remarks

For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.

This is typically used by optimization algorithms that calculate better parameter values based on training data.