Datasets:

ArXiv:
File size: 2,686 Bytes
884b8f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# marble/core/base_transform.py
import torch
import torch.nn as nn
from abc import ABC, abstractmethod
from typing import Sequence, Union, Dict


class BaseEmbTransform(nn.Module, ABC):
    """
    Abstract base class for post‐processing transformer outputs.
    Safely intercepts ModelOutput objects to extract `.hidden_states`
    while preserving all of PyTorch's hook, no_grad, and JIT behavior.
    """

    def __init__(self):
        super().__init__()

    def __call__(
        self,
        outputs: Union[Sequence[torch.Tensor], object],
        *args,
        **kwargs
    ) -> torch.Tensor:
        """
        Safely override nn.Module.__call__ to:
          1. Extract `hidden_states` if `outputs` has that attribute.
          2. Delegate into the original nn.Module.__call__, which
             will handle hooks, no_grad, tracing, etc., then call forward().

        Args:
            outputs: Either
                - A tuple/list of Tensors, each of shape (B, T, H), or
                - A model‐output object (e.g. BaseModelOutput) with `.hidden_states`.
            *args, **kwargs: Passed through to forward().

        Returns:
            Tensor: Whatever your forward() returns.
        """
        # 1. Normalize to a Sequence[Tensor]
        hidden_states = (
            outputs.hidden_states
            if hasattr(outputs, "hidden_states")
            else outputs
        )
        # 2. Call nn.Module.__call__, which invokes hooks and then forward()
        return super().__call__(hidden_states, *args, **kwargs)

    @abstractmethod
    def forward(
        self,
        hidden_states: Sequence[torch.Tensor],
        *args,
        **kwargs
    ) -> torch.Tensor:
        """
        Core transform logic. You must implement this in subclasses.

        Args:
            hidden_states (Sequence[Tensor]): List/tuple of N tensors,
                each of shape (batch_size, seq_len, hidden_size).

        Returns:
            Tensor: Transformed output; shape is up to the subclass.
        """
        raise NotImplementedError("Subclasses must implement forward()")


class BaseAudioTransform(nn.Module, ABC):
    """
    Base class for dict‐based audio transforms.
    Inherit from nn.Module so that __call__() → forward() is wired up automatically.
    """

    @abstractmethod
    def forward(self, sample: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
        """
        Args:
            sample (dict): must contain at least "waveform": Tensor[C, T].
        Returns:
            sample (dict): with same keys (possibly modified in place).
        """
        raise NotImplementedError("Subclasses must implement forward()")