-
Notifications
You must be signed in to change notification settings - Fork 182
/
consider_constant.py
101 lines (62 loc) · 2.4 KB
/
consider_constant.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import theano
import theano.tensor as T
from theano.tensor.opt import register_canonicalize
# TODO: implement w.r.t.?
class ConsiderConstant(theano.compile.ViewOp):
def grad(self, args, g_outs):
return [g_out.zeros_like(g_out) for g_out in g_outs]
consider_constant = ConsiderConstant()
register_canonicalize(theano.gof.OpRemove(consider_constant), name='remove_consider_constant_')
if __name__=='__main__':
import theano.tensor as T
import numpy as np
x = T.matrix('x')
x_c = consider_constant(x)
g = T.grad((x * T.exp(x)).sum(), x)
f = theano.function([x], g) # should always return 1
g_c = T.grad((x * T.exp(x_c)).sum(), x)
f_c = theano.function([x], g_c) # should always return 0
a = np.random.normal(0, 1, (3,3)).astype("float32")
print f(a)
print f_c(a)
print np.exp(a) * (a + 1)
print np.exp(a)
theano.printing.debugprint(f_c)
#########
# WITHOUT CANONICALIZATION
# DeepCopyOp [@A] '' 1
# |ConsiderConstant [@B] '' 0
# |x [@C]
# Elemwise{exp} [@A] '' 1
# |ConsiderConstant [@B] '' 0
# |x [@C]
# WITH CANONICALIZATION
# DeepCopyOp [@A] 'x' 0
# |x [@B]
# Elemwise{exp} [@A] '' 0
# |x [@B]
# class ConsiderConstant(ViewOp):
# def grad(self, args, g_outs):
# return [tensor.zeros_like(g_out) for g_out in g_outs]
# consider_constant_ = ConsiderConstant()
# # Although the op just returns its input, it should be removed from
# # the graph to make sure all possible optimizations can be applied.
# register_canonicalize(gof.OpRemove(consider_constant_),
# name='remove_consider_constant')
# #I create a function only to have the doc show well.
# def consider_constant(x):
# """ Consider an expression constant when computing gradients.
# The expression itself is unaffected, but when its gradient is
# computed, or the gradient of another expression that this
# expression is a subexpression of, it will not be backpropagated
# through. In other words, the gradient of the expression is
# truncated to 0.
# :param x: A Theano expression whose gradient should be truncated.
# :return: The expression is returned unmodified, but its gradient
# is now truncated to 0.
# Support rectangular matrix and tensor with more than 2 dimensions
# if the later have all dimensions are equals.
# .. versionadded:: 0.6.1
# """
# return consider_constant_(x)
#