pytorch-image-models

Форк
0
/
test_layers.py 
78 строк · 1.8 Кб
1
import torch
2
import torch.nn as nn
3

4
from timm.layers import create_act_layer, set_layer_config
5

6
import importlib
7
import os
8

9
torch_backend = os.environ.get('TORCH_BACKEND')
10
if torch_backend is not None:
11
    importlib.import_module(torch_backend)
12
torch_device = os.environ.get('TORCH_DEVICE', 'cpu')
13

14
class MLP(nn.Module):
15
    def __init__(self, act_layer="relu", inplace=True):
16
        super(MLP, self).__init__()
17
        self.fc1 = nn.Linear(1000, 100)
18
        self.act = create_act_layer(act_layer, inplace=inplace)
19
        self.fc2 = nn.Linear(100, 10)
20

21
    def forward(self, x):
22
        x = self.fc1(x)
23
        x = self.act(x)
24
        x = self.fc2(x)
25
        return x
26

27

28
def _run_act_layer_grad(act_type, inplace=True):
29
    x = torch.rand(10, 1000) * 10
30
    m = MLP(act_layer=act_type, inplace=inplace)
31

32
    def _run(x, act_layer=''):
33
        if act_layer:
34
            # replace act layer if set
35
            m.act = create_act_layer(act_layer, inplace=inplace)
36
        out = m(x)
37
        l = (out - 0).pow(2).sum()
38
        return l
39

40
    x = x.to(device=torch_device)
41
    m.to(device=torch_device)
42

43
    out_me = _run(x)
44

45
    with set_layer_config(scriptable=True):
46
        out_jit = _run(x, act_type)
47

48
    assert torch.isclose(out_jit, out_me)
49

50
    with set_layer_config(no_jit=True):
51
        out_basic = _run(x, act_type)
52

53
    assert torch.isclose(out_basic, out_jit)
54

55

56
def test_swish_grad():
57
    for _ in range(100):
58
        _run_act_layer_grad('swish')
59

60

61
def test_mish_grad():
62
    for _ in range(100):
63
        _run_act_layer_grad('mish')
64

65

66
def test_hard_sigmoid_grad():
67
    for _ in range(100):
68
        _run_act_layer_grad('hard_sigmoid', inplace=None)
69

70

71
def test_hard_swish_grad():
72
    for _ in range(100):
73
        _run_act_layer_grad('hard_swish')
74

75

76
def test_hard_mish_grad():
77
    for _ in range(100):
78
        _run_act_layer_grad('hard_mish')
79

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.