Spaces:
Sleeping
Sleeping
File size: 1,559 Bytes
d7e58f0 |
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 |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
import torch.nn as nn
class Loss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input, target):
input = input.view(-1)
target = target.view(-1)
return torch.mean(input - target)
class TestCrissCrossAttention:
def test_cc_attention(self):
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
from mmcv.ops import CrissCrossAttention
loss_func = Loss()
input = np.fromfile(
'tests/data/for_ccattention/ccattention_input.bin',
dtype=np.float32)
output = np.fromfile(
'tests/data/for_ccattention/ccattention_output.bin',
dtype=np.float32)
input = input.reshape((1, 32, 45, 45))
output = output.reshape((1, 32, 45, 45))
label = torch.ones((1, 32, 45, 45))
input = torch.FloatTensor(input)
output = torch.FloatTensor(output)
input.requires_grad = True
shape = input.shape
channel = shape[1]
cca = CrissCrossAttention(channel)
cca.to(device)
input = input.to(device)
label = label.to(device)
cca.train()
test_output = cca(input)
test_loss = loss_func(test_output, label)
test_loss.backward()
test_output = test_output.detach().cpu().numpy()
output = output.numpy()
assert np.allclose(test_output, output)
assert test_output.shape == shape
|