-
Notifications
You must be signed in to change notification settings - Fork 5
/
BinActivateFunc.py
48 lines (42 loc) · 1.45 KB
/
BinActivateFunc.py
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
import torch
from torch.autograd import Function
import BinActivateFunc_cpp, BinActivateFunc_cuda
class BinActivateFunc(Function):
@staticmethod
def forward(ctx, input):
ctx.input = input
ctx.backend = BinActivateFunc_cuda if input.is_cuda else BinActivateFunc_cpp
output = ctx.backend.forward(input)
return output
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.clone()
ctx.backend.backward(ctx.input, grad_input)
return grad_input
class BinActivateFunc2(Function):
@staticmethod
def forward(ctx, input):
ctx.input = input
return input.sign()
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.clone()
grad_input[ctx.input > 1] = 0
grad_input[ctx.input < -1] = 0
return grad_input
class BinActivateFunc_bireal(Function):
'''
Proposed in "Bi-Real Net: Enhancing the Performance of 1-bit CNNs With Improved \
Representational Capability and Advanced Training Algorithm" (ECCV2018)
'''
@staticmethod
def forward(ctx, input):
ctx.input = input
ctx.backend = BinActivateFunc_cuda if input.is_cuda else BinActivateFunc_cpp
output = ctx.backend.forward(input)
return output
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output.clone()
ctx.backend.clip_backward(ctx.input, grad_input)
return grad_input