common_utils.py 3.5 KB
Newer Older
1
import os
2
import tempfile
3
import unittest
4
from typing import Type, Iterable
5
6
from contextlib import contextmanager
from shutil import copytree
7

jamarshon's avatar
jamarshon committed
8
import torch
9
from torch.testing._internal.common_utils import TestCase
10
import torchaudio
11

12
_TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__))
13
BACKENDS = torchaudio._backend._audio_backends
14
15


16
17
18
19
20
def get_asset_path(*paths):
    """Return full path of a test asset"""
    return os.path.join(_TEST_DIR_PATH, 'assets', *paths)


21
22
23
24
25
26
27
def create_temp_assets_dir():
    """
    Creates a temporary directory and moves all files from test/assets there.
    Returns a Tuple[string, TemporaryDirectory] which is the folder path
    and object.
    """
    tmp_dir = tempfile.TemporaryDirectory()
28
    copytree(os.path.join(_TEST_DIR_PATH, "assets"),
29
30
             os.path.join(tmp_dir.name, "assets"))
    return tmp_dir.name, tmp_dir
jamarshon's avatar
jamarshon committed
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


def random_float_tensor(seed, size, a=22695477, c=1, m=2 ** 32):
    """ Generates random tensors given a seed and size
    https://en.wikipedia.org/wiki/Linear_congruential_generator
    X_{n + 1} = (a * X_n + c) % m
    Using Borland C/C++ values

    The tensor will have values between [0,1)
    Inputs:
        seed (int): an int
        size (Tuple[int]): the size of the output tensor
        a (int): the multiplier constant to the generator
        c (int): the additive constant to the generator
        m (int): the modulus constant to the generator
    """
    num_elements = 1
    for s in size:
        num_elements *= s

    arr = [(a * seed + c) % m]
    for i in range(num_elements - 1):
        arr.append((a * arr[i] + c) % m)

    return torch.tensor(arr).float().view(size) / m


58
59
60
61
62
63
64
65
66
67
68
69
@contextmanager
def AudioBackendScope(new_backend):
    previous_backend = torchaudio.get_audio_backend()
    try:
        torchaudio.set_audio_backend(new_backend)
        yield
    finally:
        torchaudio.set_audio_backend(previous_backend)


def filter_backends_with_mp3(backends):
    # Filter out backends that do not support mp3
70
    test_filepath = get_asset_path('steam-train-whistle-daniel_simon.mp3')
71
72
73
74
75
76

    def supports_mp3(backend):
        try:
            with AudioBackendScope(backend):
                torchaudio.load(test_filepath)
            return True
moto's avatar
moto committed
77
        except (RuntimeError, ImportError):
78
79
80
81
82
83
            return False

    return [backend for backend in backends if supports_mp3(backend)]


BACKENDS_MP3 = filter_backends_with_mp3(BACKENDS)
84
85
86
87
88
89
90


class TestBaseMixin:
    dtype = None
    device = None


91
92
93
_SKIP_IF_NO_CUDA = unittest.skipIf(not torch.cuda.is_available(), reason='CUDA not available')


94
95
96
97
98
99
100
101
def define_test_suite(testbase: Type[TestBaseMixin], dtype: str, device: str):
    if dtype not in ['float32', 'float64']:
        raise NotImplementedError(f'Unexpected dtype: {dtype}')
    if device not in ['cpu', 'cuda']:
        raise NotImplementedError(f'Unexpected device: {device}')

    name = f'Test{testbase.__name__}_{device.upper()}_{dtype.capitalize()}'
    attrs = {'dtype': getattr(torch, dtype), 'device': torch.device(device)}
102
    testsuite = type(name, (testbase, TestCase), attrs)
103
104

    if device == 'cuda':
105
        testsuite = _SKIP_IF_NO_CUDA(testsuite)
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    return testsuite


def define_test_suites(
        scope: dict,
        testbases: Iterable[Type[TestBaseMixin]],
        dtypes: Iterable[str] = ('float32', 'float64'),
        devices: Iterable[str] = ('cpu', 'cuda'),
):
    for suite in testbases:
        for device in devices:
            for dtype in dtypes:
                t = define_test_suite(suite, dtype, device)
                scope[t.__name__] = t