diff --git a/src/TorchSharp/TorchAudio/Compose.cs b/src/TorchSharp/TorchAudio/Compose.cs new file mode 100644 index 000000000..5b63ce06d --- /dev/null +++ b/src/TorchSharp/TorchAudio/Compose.cs @@ -0,0 +1,50 @@ +// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. + +using System; +using static TorchSharp.torch; + +namespace TorchSharp +{ + public static partial class torchaudio + { + internal class ComposedTransforms : IDisposable, ITransform + { + public ComposedTransforms(ITransform[] transforms) + { + this.transforms = transforms; + } + + public void Dispose() + { + foreach (var t in transforms) { + if (t is IDisposable) { + ((IDisposable)t).Dispose(); + } + } + } + + public Tensor forward(Tensor input) + { + foreach (var t in transforms) { + input = t.forward(input); + } + return input; + } + + private ITransform[] transforms; + } + + public static partial class transforms + { + /// + /// Composes several transforms together. + /// + /// A list of transforms to compose serially. + /// + static public ITransform Compose(params ITransform[] transforms) + { + return new ComposedTransforms(transforms); + } + } + } +} \ No newline at end of file diff --git a/src/TorchSharp/TorchAudio/Functional.cs b/src/TorchSharp/TorchAudio/Functional.cs new file mode 100644 index 000000000..d08edccfd --- /dev/null +++ b/src/TorchSharp/TorchAudio/Functional.cs @@ -0,0 +1,154 @@ +// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. +using System; +using System.Linq; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +using static TorchSharp.torch; + +// A number of implementation details in this file have been translated from the Python version or torchvision, +// largely located in the files found in this folder: +// +// https://github.com/pytorch/audio/blob/39c2c0a77e11b82ce152d60df3a92f6854d5f52b/torchaudio/functional/functional.py +// +// The origin has the following copyright notice and license: +// +// https://github.com/pytorch/audio/blob/main/LICENSE +// + +namespace TorchSharp +{ + public static partial class torchaudio + { + public static partial class functional + { + /// + /// Compute spectrograms from audio signals. + /// + /// The audio signal tensor + /// Padding on the sides + /// The window function + /// The size of Fourier transform + /// The hop length + /// The window length + /// Exponent for the magnitude spectrogram + /// Whether the output is normalized, or not. + /// Whether the t-th frame is centered around t * hop_window, or not. + /// The padding mode used when center is true. + /// Whether the output is onesided or not. + /// Deprecated and not used. + /// Spectrograms of audio signals + public static torch.Tensor spectrogram(torch.Tensor waveform, long pad, torch.Tensor window, long n_fft, long hop_length, long win_length, double? power, bool normalized, bool center = true, PaddingModes pad_mode = PaddingModes.Reflect, bool onesided = true, bool? return_complex = null) + { + using (var d = torch.NewDisposeScope()) { + + if (pad > 0) { + // The original torchaudio doesn't have `torch.no_grad()' here to + // avoid issues with JIT. + // https://github.com/pytorch/audio/commit/a420cced7e60fcf9ba6efcff3a2e8bee3ac67d05#diff-ab14255549624af556aa0d1dfaf83241a95e05c3dd6a668cd2607655839f7a09 + using (torch.no_grad()) { + waveform = torch.nn.functional.pad(waveform, new long[] { pad, pad }, PaddingModes.Constant); + } + } + + // pack batch + var shape = waveform.size(); + waveform = waveform.reshape(-1, shape[shape.Length - 1]); + + // default values are consistent with librosa.core.spectrum._spectrogram + var spec_f = torch.stft( + input: waveform, + n_fft: n_fft, + hop_length: hop_length, + win_length: win_length, + window: window, + center: center, + pad_mode: pad_mode, + normalized: false, + onesided: onesided, + return_complex: true); + + // unpack batch + var spec_shape = new long[shape.Length + spec_f.dim() - 2]; + Array.Copy(shape, spec_shape, shape.Length - 1); + Array.Copy(spec_f.shape, 1, spec_shape, shape.Length - 1, spec_f.dim() - 1); + spec_f = spec_f.reshape(spec_shape); + + if (normalized) { + spec_f /= window.pow(2.0).sum().sqrt(); + } + + if (power.HasValue) { + if (power.Value == 1.0) { + spec_f = spec_f.abs(); + } else { + spec_f = spec_f.abs().pow(power.Value); + } + } + + return d.MoveToOuter(spec_f); + } + } + + /// + /// Compute inverse of spectrogram. + /// + /// The spectrogram tensor + /// The length of the output tensor + /// Padding on the sides + /// The window function + /// The size of Fourier transform + /// The hop length + /// The window length + /// Whether the output is normalized, or not. + /// Whether the t-th frame is centered around t * hop_window, or not. + /// The padding mode used when center is true. + /// Whether the output is onesided or not. + /// Inverse of spectrogram + public static torch.Tensor inverse_spectrogram(torch.Tensor spectrogram, long? length, long pad, torch.Tensor window, long n_fft, long hop_length, long win_length, bool normalized, bool center = true, PaddingModes pad_mode = PaddingModes.Reflect, bool onesided = true) + { + if (!spectrogram.is_complex()) { + throw new ArgumentException("Expected `spectrogram` to be complex dtype."); + } + + using (var d = torch.NewDisposeScope()) { + + if (normalized) { + spectrogram = spectrogram * window.pow(2.0).sum().sqrt(); + } + + // pack batch + var shape = spectrogram.size(); + spectrogram = spectrogram.reshape(-1, shape[shape.Length - 2], shape[shape.Length - 1]); + + // default values are consistent with librosa.core.spectrum._spectrogram + var waveform = torch.istft( + input: spectrogram, + n_fft: n_fft, + hop_length: hop_length, + win_length: win_length, + window: window, + center: center, + normalized: false, + onesided: onesided, + length: length.HasValue ? length.Value + 2 * pad : -1, + return_complex: false + ); + + if (length.HasValue && pad > 0) { + // remove padding from front and back + waveform = waveform[TensorIndex.Colon, TensorIndex.Slice(pad, -pad)]; + } + + // unpack batch + var waveform_shape = new long[shape.Length - 1]; + Array.Copy(shape, waveform_shape, shape.Length - 2); + waveform_shape[waveform_shape.Length - 1] = waveform.shape[waveform.dim() - 1]; + waveform = waveform.reshape(waveform_shape); + + return d.MoveToOuter(waveform); + } + } + } + } +} \ No newline at end of file diff --git a/src/TorchSharp/TorchAudio/ITransform.cs b/src/TorchSharp/TorchAudio/ITransform.cs new file mode 100644 index 000000000..49e4214da --- /dev/null +++ b/src/TorchSharp/TorchAudio/ITransform.cs @@ -0,0 +1,14 @@ +// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. + +using static TorchSharp.torch; + +namespace TorchSharp +{ + public partial class torchaudio + { + public interface ITransform + { + Tensor forward(Tensor input); + } + } +} diff --git a/src/TorchSharp/TorchAudio/Transforms.cs b/src/TorchSharp/TorchAudio/Transforms.cs new file mode 100644 index 000000000..67ef29bb9 --- /dev/null +++ b/src/TorchSharp/TorchAudio/Transforms.cs @@ -0,0 +1,260 @@ +// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. +using System; +using System.Linq; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +using static TorchSharp.torch; + +// A number of implementation details in this file have been translated from the Python version or torchvision, +// largely located in the files found in this folder: +// +// https://github.com/pytorch/audio/blob/bb77cbebb620a46fdc0dc7e6dae2253eef3f37e2/torchaudio/transforms/_transforms.py +// +// The origin has the following copyright notice and license: +// +// https://github.com/pytorch/audio/blob/main/LICENSE +// + +namespace TorchSharp +{ + public static partial class torchaudio + { + public delegate torch.Tensor WindowFunction(long win_length); + + internal class Spectrogram : ITransform + { + private readonly long n_fft; + private readonly long win_length; + private readonly long hop_length; + private readonly long pad; + private readonly Tensor window; + private readonly double? power; + private readonly bool normalized; + private readonly bool center; + private readonly PaddingModes pad_mode; + private readonly bool onesided; + + public Spectrogram( + long n_fft = 400, + long? win_length = null, + long? hop_length = null, + long pad = 0, + WindowFunction window_fn = null, + Tensor window = null, + double? power = 2.0, + bool normalized = false, + bool center = true, + PaddingModes pad_mode = PaddingModes.Reflect, + bool onesided = true, + bool? return_complex = null) + { + this.n_fft = n_fft; + if (win_length.HasValue) { + this.win_length = win_length.Value; + } else { + this.win_length = n_fft; + } + if (hop_length.HasValue) { + this.hop_length = hop_length.Value; + } else { + this.hop_length = this.win_length / 2; + } + this.pad = pad; + if (window is not null) { + this.window = window; + } else if (window_fn != null) { + this.window = window_fn(this.win_length); + } else { + this.window = torch.hann_window(this.win_length); + } + this.power = power; + this.normalized = normalized; + this.center = center; + this.pad_mode = pad_mode; + this.onesided = onesided; + if (return_complex.HasValue) { + Console.WriteLine( + "`return_complex` argument is now deprecated and is not effective." + + "`torchaudio.transforms.Spectrogram(power=null)` always returns a tensor with " + + "complex dtype. Please remove the argument in the function call." + ); + } + } + + public Tensor forward(Tensor input) + { + return torchaudio.functional.spectrogram( + waveform: input, + pad: pad, + window: window, + n_fft: n_fft, + hop_length: hop_length, + win_length: win_length, + power: power, + normalized: normalized, + center: center, + pad_mode: pad_mode, + onesided: onesided); + } + } + + internal class InverseSpectrogram : ITransform + { + private readonly long n_fft; + private readonly long win_length; + private readonly long hop_length; + private readonly long pad; + private readonly Tensor window; + private readonly bool normalized; + private readonly bool center; + private readonly PaddingModes pad_mode; + private readonly bool onesided; + + public InverseSpectrogram( + long n_fft = 400, + long? win_length = null, + long? hop_length = null, + long pad = 0, + WindowFunction window_fn = null, + Tensor window = null, + bool normalized = false, + bool center = true, + PaddingModes pad_mode = PaddingModes.Reflect, + bool onesided = true) + { + this.n_fft = n_fft; + if (win_length.HasValue) { + this.win_length = win_length.Value; + } else { + this.win_length = n_fft; + } + if (hop_length.HasValue) { + this.hop_length = hop_length.Value; + } else { + this.hop_length = this.win_length / 2; + } + this.pad = pad; + if (window is not null) { + this.window = window; + } else if (window_fn != null) { + this.window = window_fn(this.win_length); + } else { + this.window = torch.hann_window(this.win_length); + } + this.normalized = normalized; + this.center = center; + this.pad_mode = pad_mode; + this.onesided = onesided; + } + + public Tensor forward(Tensor input) + { + return forward(input, null); + } + + public Tensor forward(Tensor input, long? length = null) + { + return torchaudio.functional.inverse_spectrogram( + spectrogram: input, + length: length, + pad: pad, + window: window, + n_fft: n_fft, + hop_length: hop_length, + win_length: win_length, + normalized: normalized, + center: center, + pad_mode: pad_mode, + onesided: onesided); + } + } + + public static partial class transforms + { + /// + /// Compute spectrograms from audio signals. + /// + /// The size of Fourier transform + /// The hop length + /// The window length + /// Padding on the sides + /// The callback to create a window function + /// The window function + /// Exponent for the magnitude spectrogram + /// Whether the output is normalized, or not. + /// Whether the t-th frame is centered around t * hop_window, or not. + /// The padding mode used when center is true. + /// Whether the output is onesided or not. + /// Deprecated and not used. + /// ITransform to compute spectrograms of audio signals + public static ITransform Spectrogram( + long n_fft = 400, + long? win_length = null, + long? hop_length = null, + long pad = 0, + WindowFunction window_fn = null, + Tensor window = null, + double? power = 2.0, + bool normalized = false, + bool center = true, + PaddingModes pad_mode = PaddingModes.Reflect, + bool onesided = true, + bool? return_complex = null) + { + return new Spectrogram( + n_fft: n_fft, + hop_length: hop_length, + win_length: win_length, + pad: pad, + window_fn: window_fn, + window: window, + power: power, + normalized: normalized, + center: center, + pad_mode: pad_mode, + onesided: onesided, + return_complex: return_complex); + } + + /// + /// Compute inverse of spectrogram. + /// + /// The size of Fourier transform + /// The hop length + /// The window length + /// Padding on the sides + /// The callback to create a window function + /// The window function + /// Whether the output is normalized, or not. + /// Whether the t-th frame is centered around t * hop_window, or not. + /// The padding mode used when center is true. + /// Whether the output is onesided or not. + /// ITransform to compute inverse of spectrogram + public static ITransform InverseSpectrogram( + long n_fft = 400, + long? win_length = null, + long? hop_length = null, + long pad = 0, + WindowFunction window_fn = null, + Tensor window = null, + bool normalized = false, + bool center = true, + PaddingModes pad_mode = PaddingModes.Reflect, + bool onesided = true) + { + return new InverseSpectrogram( + n_fft: n_fft, + hop_length: hop_length, + win_length: win_length, + pad: pad, + window_fn: window_fn, + window: window, + normalized: normalized, + center: center, + pad_mode: pad_mode, + onesided: onesided); + } + } + } +} \ No newline at end of file diff --git a/test/TorchSharpTest/TestTorchAudio.cs b/test/TorchSharpTest/TestTorchAudio.cs new file mode 100644 index 000000000..53a931ace --- /dev/null +++ b/test/TorchSharpTest/TestTorchAudio.cs @@ -0,0 +1,113 @@ +using System; +using Xunit; + +namespace TorchSharp +{ + public class TestTorchAudio + { + private torch.Tensor make_waveform() + { + var fc = 220; + var fm = 440; + var beta = 1; + var t = torch.linspace(0, 5, 16000 * 5); + var waveform = 1.0 * torch.sin(2 * Math.PI * t * fc + beta * torch.sin(2 * Math.PI * fm * t)); + return waveform; + } + + [Fact] + public void FunctionalSpectrogram() + { + var waveform = make_waveform(); + + var spectrogram = torchaudio.functional.spectrogram( + waveform: waveform, + pad: 3, + window: torch.hann_window(400), + n_fft: 512, + hop_length: 160, + win_length: 400, + power: 2.0f, + normalized: true); + + Assert.Equal(new long[] { 257, 501 }, spectrogram.shape); + var mean_square = torch.mean(torch.square(spectrogram)).item(); + Assert.InRange(mean_square - 50.7892f, -1e-2f, 1e-2f); + } + + [Fact] + public void FunctionalInverseSpectrogram() + { + var waveform = make_waveform(); + + var spectrogram = torchaudio.functional.spectrogram( + waveform: waveform, + pad: 3, + window: torch.hann_window(400), + n_fft: 512, + hop_length: 160, + win_length: 400, + power: null, + normalized: false); + + var inversed_waveform = torchaudio.functional.inverse_spectrogram( + spectrogram: spectrogram, + length: null, + pad: 3, + window: torch.hann_window(400), + n_fft: 512, + hop_length: 160, + win_length: 400, + normalized: false); + + var mse = torch.mean(torch.square(waveform - inversed_waveform)).item(); + Assert.InRange(mse, 0, 0.1f); + } + + [Fact] + public void TransformsSpectrogram() + { + var transform = torchaudio.transforms.Spectrogram(); + var waveform = make_waveform(); + var spectrogram = transform.forward(waveform); + var expected = torchaudio.functional.spectrogram( + waveform: waveform, + pad: 0, + window: torch.hann_window(400), + n_fft: 400, + hop_length: 200, + win_length: 400, + power: 2.0, + normalized: false); + var mse = torch.mean(torch.square(spectrogram - expected)).item(); + Assert.InRange(mse, 0f, 1e-10f); + } + + [Fact] + public void TransformsInverseSpectrogram() + { + var transform = torchaudio.transforms.InverseSpectrogram(); + var spectrogram = torchaudio.functional.spectrogram( + waveform: make_waveform(), + pad: 0, + window: torch.hann_window(400), + n_fft: 400, + hop_length: 200, + win_length: 400, + power: null, + normalized: false); + var waveform = transform.forward(spectrogram); + var expected = torchaudio.functional.inverse_spectrogram( + spectrogram: spectrogram, + length: null, + pad: 0, + window: torch.hann_window(400), + n_fft: 400, + hop_length: 200, + win_length: 400, + normalized: false); + var mse = torch.mean(torch.square(waveform - expected)).item(); + Assert.InRange(mse, 0f, 1e-10f); + } + } +}