How can torchaudio.transform.Resample be called without __call__ function inside?

妖精的绣舞 提交于 2021-01-27 18:59:09

问题


if sample_rate != sr:
        waveform = torchaudio.transforms.Resample(sample_rate, sr)(waveform)
        sample_rate = sr

I was wondering how this Resamle works in there. So took a look at the docs of torchaudio. I thought there would be __call__ function. Because Resample is used as a function. I mean that Resample()(waveform). But inside, there are only __init__ and forward function. I think the forward function is the working function but I don't know why it is named 'forward' not __call__. What am I missing?

class Resample(torch.nn.Module):
    r"""Resample a signal from one frequency to another. A resampling method can be given.

    Args:
        orig_freq (float, optional): The original frequency of the signal. (Default: ``16000``)
        new_freq (float, optional): The desired frequency. (Default: ``16000``)
        resampling_method (str, optional): The resampling method. (Default: ``'sinc_interpolation'``)
    """

    def __init__(self,
                 orig_freq: int = 16000,
                 new_freq: int = 16000,
                 resampling_method: str = 'sinc_interpolation') -> None:
        super(Resample, self).__init__()
        self.orig_freq = orig_freq
        self.new_freq = new_freq
        self.resampling_method = resampling_method

    def forward(self, waveform: Tensor) -> Tensor:
        r"""
        Args:
            waveform (Tensor): Tensor of audio of dimension (..., time).

        Returns:
            Tensor: Output signal of dimension (..., time).
        """
        if self.resampling_method == 'sinc_interpolation':

            # pack batch
            shape = waveform.size()
            waveform = waveform.view(-1, shape[-1])

            waveform = kaldi.resample_waveform(waveform, self.orig_freq, self.new_freq)

            # unpack batch
            waveform = waveform.view(shape[:-1] + waveform.shape[-1:])

            return waveform

        raise ValueError('Invalid resampling method: %s' % (self.resampling_method))

--edit--

I looked around torch.nn.module. There is no def __call__. But only __call__ : Callable[..., Any] = _call_impl Would it be the way?


回答1:


Here's simple similar demonstrates of how forward function works in PyTorch.

Check this:

from typing import Callable, Any

class parent:
    def _unimplemented_forward(self, *input):
        raise NotImplementedError

    def _call_impl(self, *args):
        # original nn.Module _call_impl function contains lot more code
        # to handle exceptions, to handle hooks and for other purposes
        self.forward(*args)
    
    forward : Callable[..., Any]  = _unimplemented_forward
    __call__ : Callable[..., Any] = _call_impl

class child(parent):
    def forward(self, *args):
        print('forward function')


class child_2(parent):
    pass

Runtime:

>>> c1 = child_1()
>>> c1()
forward function
>>> c2 = child_2()
>>> c2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".\callable.py", line 8, in _call_impl
    self.forward(*args)
  File ".\callable.py", line 5, in _unimplemented_forward
    raise NotImplementedError
NotImplementedError


来源:https://stackoverflow.com/questions/63480624/how-can-torchaudio-transform-resample-be-called-without-call-function-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!