mmcv/tests/test_ops/test_cc_attention.py
zhuyuanhao c0f5492ee9
add ext ops, support parrots (#310)
* add ext ops, support parrots

* fix lint

* fix lint

* update op from mmdetection

* support non-pytorch env

* fix import bug

* test not import mmcv.op

* rename mmcv.op to mmcv.ops

* fix compile warning

* 1. fix syncbn warning in pytorch 1.5
2. support only cpu compile
3. add point_sample from mmdet

* fix text bug

* update docstrings

* fix line endings

* minor updates

* remove non_local from ops

* bug fix for nonlocal2d

* rename ops_ext to _ext and _ext to _flow_warp_ext

* update the doc

* try clang-format github action

* fix github action

* add ops to api.rst

* fix cpp format

* fix clang format issues

* remove .clang-format

Co-authored-by: Kai Chen <chenkaidev@gmail.com>
2020-06-28 23:15:47 +08:00

57 lines
1.5 KiB
Python

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(object):
def test_cc_attention(self):
if not torch.cuda.is_available():
return
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.cuda()
input = input.cuda()
label = label.cuda()
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