pytorch-image-models
78 строк · 1.8 Кб
1import torch2import torch.nn as nn3
4from timm.layers import create_act_layer, set_layer_config5
6import importlib7import os8
9torch_backend = os.environ.get('TORCH_BACKEND')10if torch_backend is not None:11importlib.import_module(torch_backend)12torch_device = os.environ.get('TORCH_DEVICE', 'cpu')13
14class MLP(nn.Module):15def __init__(self, act_layer="relu", inplace=True):16super(MLP, self).__init__()17self.fc1 = nn.Linear(1000, 100)18self.act = create_act_layer(act_layer, inplace=inplace)19self.fc2 = nn.Linear(100, 10)20
21def forward(self, x):22x = self.fc1(x)23x = self.act(x)24x = self.fc2(x)25return x26
27
28def _run_act_layer_grad(act_type, inplace=True):29x = torch.rand(10, 1000) * 1030m = MLP(act_layer=act_type, inplace=inplace)31
32def _run(x, act_layer=''):33if act_layer:34# replace act layer if set35m.act = create_act_layer(act_layer, inplace=inplace)36out = m(x)37l = (out - 0).pow(2).sum()38return l39
40x = x.to(device=torch_device)41m.to(device=torch_device)42
43out_me = _run(x)44
45with set_layer_config(scriptable=True):46out_jit = _run(x, act_type)47
48assert torch.isclose(out_jit, out_me)49
50with set_layer_config(no_jit=True):51out_basic = _run(x, act_type)52
53assert torch.isclose(out_basic, out_jit)54
55
56def test_swish_grad():57for _ in range(100):58_run_act_layer_grad('swish')59
60
61def test_mish_grad():62for _ in range(100):63_run_act_layer_grad('mish')64
65
66def test_hard_sigmoid_grad():67for _ in range(100):68_run_act_layer_grad('hard_sigmoid', inplace=None)69
70
71def test_hard_swish_grad():72for _ in range(100):73_run_act_layer_grad('hard_swish')74
75
76def test_hard_mish_grad():77for _ in range(100):78_run_act_layer_grad('hard_mish')79