From 60bcafd960a9cef4ae0d765bfc11841971a58fb1 Mon Sep 17 00:00:00 2001 From: Katsuya Iida Date: Sun, 29 May 2022 18:28:55 +0900 Subject: [PATCH 1/5] Add torchaudio.transforms.Spectrogram and torchaudio.transforms.InverseSpectrogram --- src/TorchSharp/TorchAudio/Compose.cs | 50 +++++ src/TorchSharp/TorchAudio/Functional.cs | 142 ++++++++++++++ src/TorchSharp/TorchAudio/Transforms.cs | 235 ++++++++++++++++++++++++ test/TorchSharpTest/TestTorchAudio.cs | 113 ++++++++++++ 4 files changed, 540 insertions(+) create mode 100644 src/TorchSharp/TorchAudio/Compose.cs create mode 100644 src/TorchSharp/TorchAudio/Functional.cs create mode 100644 src/TorchSharp/TorchAudio/Transforms.cs create mode 100644 test/TorchSharpTest/TestTorchAudio.cs 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..6aec0d887 --- /dev/null +++ b/src/TorchSharp/TorchAudio/Functional.cs @@ -0,0 +1,142 @@ +// 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) + { + if (pad > 0) { + // TODO add "with torch.no_grad():" back when JIT supports it + 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) { + return spec_f.abs(); + } + return spec_f.abs().pow(power.Value); + } else { + return 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. + /// + 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."); + } + + 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 waveform; + } + } + } +} \ No newline at end of file diff --git a/src/TorchSharp/TorchAudio/Transforms.cs b/src/TorchSharp/TorchAudio/Transforms.cs new file mode 100644 index 000000000..09ccedc64 --- /dev/null +++ b/src/TorchSharp/TorchAudio/Transforms.cs @@ -0,0 +1,235 @@ +// 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 interface ITransform + { + Tensor forward(Tensor input); + } + + 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 + { + 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); + } + + 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); + } + } +} From ede277618cad897b9e34b8e53862c4032b218a4c Mon Sep 17 00:00:00 2001 From: Katsuya Iida Date: Sun, 29 May 2022 18:35:31 +0900 Subject: [PATCH 2/5] Add comments --- src/TorchSharp/TorchAudio/Functional.cs | 2 +- src/TorchSharp/TorchAudio/Transforms.cs | 30 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/TorchSharp/TorchAudio/Functional.cs b/src/TorchSharp/TorchAudio/Functional.cs index 6aec0d887..a152b1550 100644 --- a/src/TorchSharp/TorchAudio/Functional.cs +++ b/src/TorchSharp/TorchAudio/Functional.cs @@ -95,7 +95,7 @@ public static torch.Tensor spectrogram(torch.Tensor waveform, long pad, torch.Te /// 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()) { diff --git a/src/TorchSharp/TorchAudio/Transforms.cs b/src/TorchSharp/TorchAudio/Transforms.cs index 09ccedc64..0cad9b336 100644 --- a/src/TorchSharp/TorchAudio/Transforms.cs +++ b/src/TorchSharp/TorchAudio/Transforms.cs @@ -177,6 +177,22 @@ public Tensor forward(Tensor input, long? length = null) 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, @@ -206,6 +222,20 @@ public static ITransform Spectrogram( 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, From 8ecaa12647ba4fe393259cb154f02fe352f2142c Mon Sep 17 00:00:00 2001 From: Katsuya Iida Date: Wed, 1 Jun 2022 20:45:26 +0900 Subject: [PATCH 3/5] ITransform should be in its own file. --- src/TorchSharp/TorchAudio/ITransform.cs | 14 ++++++++++++++ src/TorchSharp/TorchAudio/Transforms.cs | 5 ----- 2 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 src/TorchSharp/TorchAudio/ITransform.cs 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 index 0cad9b336..67ef29bb9 100644 --- a/src/TorchSharp/TorchAudio/Transforms.cs +++ b/src/TorchSharp/TorchAudio/Transforms.cs @@ -20,11 +20,6 @@ namespace TorchSharp { public static partial class torchaudio { - public interface ITransform - { - Tensor forward(Tensor input); - } - public delegate torch.Tensor WindowFunction(long win_length); internal class Spectrogram : ITransform From aa2557a2ea1933440f94507be4ce187c6bd11256 Mon Sep 17 00:00:00 2001 From: Katsuya Iida Date: Sun, 5 Jun 2022 09:42:41 +0900 Subject: [PATCH 4/5] Using DisposeScope to collect temporary tensors. --- src/TorchSharp/TorchAudio/Functional.cs | 142 +++++++++++++----------- 1 file changed, 75 insertions(+), 67 deletions(-) diff --git a/src/TorchSharp/TorchAudio/Functional.cs b/src/TorchSharp/TorchAudio/Functional.cs index a152b1550..a4169bb15 100644 --- a/src/TorchSharp/TorchAudio/Functional.cs +++ b/src/TorchSharp/TorchAudio/Functional.cs @@ -40,44 +40,49 @@ public static partial class functional /// 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) { - if (pad > 0) { - // TODO add "with torch.no_grad():" back when JIT supports it - waveform = torch.nn.functional.pad(waveform, new long[] { pad, pad }, PaddingModes.Constant); - } + using (var d = torch.NewDisposeScope()) { - // 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) { - return spec_f.abs(); + if (pad > 0) { + // TODO add "with torch.no_grad():" back when JIT supports it + 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 spec_f.abs().pow(power.Value); - } else { - return spec_f; + + return d.MoveToOuter(spec_f); } } @@ -102,40 +107,43 @@ public static torch.Tensor inverse_spectrogram(torch.Tensor spectrogram, long? l throw new ArgumentException("Expected `spectrogram` to be complex dtype."); } - if (normalized) { - spectrogram = spectrogram * window.pow(2.0).sum().sqrt(); - } + using (var d = torch.NewDisposeScope()) { - // 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)]; - } + 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]); - // 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); + // 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 + ); - return waveform; + 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); + } } } } From a5eed55c38ad67b1e43ed6e43889b86fed1ed111 Mon Sep 17 00:00:00 2001 From: Katsuya Iida Date: Sun, 5 Jun 2022 11:03:50 +0900 Subject: [PATCH 5/5] Added torch.no_grad() to remove TODO. --- src/TorchSharp/TorchAudio/Functional.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/TorchSharp/TorchAudio/Functional.cs b/src/TorchSharp/TorchAudio/Functional.cs index a4169bb15..d08edccfd 100644 --- a/src/TorchSharp/TorchAudio/Functional.cs +++ b/src/TorchSharp/TorchAudio/Functional.cs @@ -43,8 +43,12 @@ public static torch.Tensor spectrogram(torch.Tensor waveform, long pad, torch.Te using (var d = torch.NewDisposeScope()) { if (pad > 0) { - // TODO add "with torch.no_grad():" back when JIT supports it - waveform = torch.nn.functional.pad(waveform, new long[] { pad, pad }, PaddingModes.Constant); + // 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