-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtest_jac.py
More file actions
323 lines (248 loc) · 9.98 KB
/
test_jac.py
File metadata and controls
323 lines (248 loc) · 9.98 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import torch
from pytest import mark, raises
from tests.utils.dict_assertions import assert_tensor_dicts_are_close
from tests.utils.tensors import eye_, ones_, tensor_, zeros_
from torchjd.autojac._transform import Jac, OrderedSet, RequirementError
@mark.parametrize("chunk_size", [1, 3, None])
def test_single_input(chunk_size: int | None):
"""
Tests that the Jac transform works correctly for an example of multiple differentiation. Here,
the function considered is: `y = [a1 * x, a2 * x]`. We want to compute the jacobians of `y` with
respect to `a1` and `a2`.
"""
x = tensor_(5.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y = torch.stack([a1 * x, a2 * x])
input = {y: eye_(2)}
jac = Jac(outputs=OrderedSet([y]), inputs=OrderedSet([a1, a2]), chunk_size=chunk_size)
jacobians = jac(input)
expected_jacobians = {
a1: torch.stack([x, zeros_([])]),
a2: torch.stack([zeros_([]), x]),
}
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
@mark.parametrize("chunk_size", [1, 3, None])
def test_empty_inputs_1(chunk_size: int | None):
"""
Tests that the Jac transform works correctly when the `inputs` parameter is an empty `Iterable`.
"""
y1 = tensor_(1.0, requires_grad=True)
y2 = tensor_(1.0, requires_grad=True)
y = torch.stack([y1, y2])
input = {y: eye_(2)}
jac = Jac(outputs=OrderedSet([y]), inputs=OrderedSet([]), chunk_size=chunk_size)
jacobians = jac(input)
expected_jacobians = {}
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
@mark.parametrize("chunk_size", [1, 3, None])
def test_empty_inputs_2(chunk_size: int | None):
"""
Tests that the Jac transform works correctly when the `inputs` parameter is an empty `Iterable`.
"""
x = tensor_(5.0)
a1 = tensor_(1.0, requires_grad=True)
a2 = tensor_(1.0, requires_grad=True)
y1 = a1 * x
y2 = a2 * x
y = torch.stack([y1, y2])
input = {y: eye_(2)}
jac = Jac(outputs=OrderedSet([y]), inputs=OrderedSet([]), chunk_size=chunk_size)
jacobians = jac(input)
expected_jacobians = {}
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
@mark.parametrize("chunk_size", [1, 3, None])
def test_empty_outputs(chunk_size: int | None):
"""
Tests that the Jac transform works correctly when the `outputs` parameter is an empty
`Iterable`.
"""
a1 = tensor_(1.0, requires_grad=True)
a2 = tensor_([1.0, 2.0], requires_grad=True)
input = {}
jac = Jac(outputs=OrderedSet([]), inputs=OrderedSet([a1, a2]), chunk_size=chunk_size)
jacobians = jac(input)
expected_jacobians = {
a1: torch.empty_like(a1).unsqueeze(0)[:0], # Jacobian with no row
a2: torch.empty_like(a2).unsqueeze(0)[:0], # Jacobian with no row
}
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
def test_retain_graph():
"""Tests that the `Jac` transform behaves as expected with the `retain_graph` flag."""
x = tensor_(5.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y1 = a1 * x
y2 = a2 * x
y = torch.stack([y1, y2])
input = {y: eye_(2)}
jac_retain_graph = Jac(
outputs=OrderedSet([y]), inputs=OrderedSet([a1, a2]), chunk_size=None, retain_graph=True
)
jac_discard_graph = Jac(
outputs=OrderedSet([y]), inputs=OrderedSet([a1, a2]), chunk_size=None, retain_graph=False
)
jac_retain_graph(input)
jac_retain_graph(input)
jac_discard_graph(input)
with raises(RuntimeError):
jac_retain_graph(input)
with raises(RuntimeError):
jac_discard_graph(input)
def test_two_levels():
"""
Tests that the Jac transform works correctly for an example of chained differentiation. Here,
the function considered is: `z = a * x1 * x2`, which is computed in 2 parts: `y = a * x1` and
`z = y * x2`. We want to compute the derivative of `z` with respect to the parameter `a`, by
using chain rule. This derivative should be equal to `x1 * x2`.
"""
x1 = tensor_(5.0)
x2 = tensor_(6.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y1 = a1 * x1
y2 = a2 * x1
y = torch.stack([y1, y2])
z = y * x2
input = {z: eye_(2)}
outer_jac = Jac(
outputs=OrderedSet([y]), inputs=OrderedSet([a1, a2]), chunk_size=None, retain_graph=True
)
inner_jac = Jac(
outputs=OrderedSet([z]), inputs=OrderedSet([y]), chunk_size=None, retain_graph=True
)
composed_jac = outer_jac << inner_jac
jac = Jac(outputs=OrderedSet([z]), inputs=OrderedSet([a1, a2]), chunk_size=None)
jacobians = composed_jac(input)
expected_jacobians = jac(input)
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
@mark.parametrize("chunk_size", [1, 3, None])
def test_multiple_outputs_1(chunk_size: int | None):
"""
Tests that the Jac transform works correctly when the `outputs` contains 3 vectors.
The input (jac_outputs) is not the same for all outputs, so that this test also checks that the
scaling is performed correctly.
"""
x = tensor_(5.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y1 = torch.stack([a1 * x, a2 * x])
y2 = torch.stack([a2**2, a1**2])
y3 = torch.stack([a2**3, a1**3])
identity_2x2 = eye_(2)
zeros_2x2 = zeros_(2, 2)
jac_output1 = torch.cat([identity_2x2 * 7, zeros_2x2, zeros_2x2])
jac_output2 = torch.cat([zeros_2x2, identity_2x2, zeros_2x2])
jac_output3 = torch.cat([zeros_2x2, zeros_2x2, identity_2x2])
input = {y1: jac_output1, y2: jac_output2, y3: jac_output3}
jac = Jac(outputs=OrderedSet([y1, y2, y3]), inputs=OrderedSet([a1, a2]), chunk_size=chunk_size)
jacobians = jac(input)
zero_scalar = tensor_(0.0)
expected_jacobians = {
a1: torch.stack([x * 7, zero_scalar, zero_scalar, 2 * a1, zero_scalar, 3 * a1**2]),
a2: torch.stack([zero_scalar, x * 7, 2 * a2, zero_scalar, 3 * a2**2, zero_scalar]),
}
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
@mark.parametrize("chunk_size", [1, 3, None])
def test_multiple_outputs_2(chunk_size: int | None):
"""
Same as test_multiple_outputs_1 but with different jac_outputs, so the returned jacobians are of
different shapes.
"""
x = tensor_(5.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y1 = torch.stack([a1 * x, a2 * x])
y2 = torch.stack([a2**2, a1**2])
y3 = torch.stack([a2**3, a1**3])
ones_2 = ones_(2)
zeros_2 = zeros_(2)
jac_output1 = torch.stack([ones_2 * 7, zeros_2, zeros_2])
jac_output2 = torch.stack([zeros_2, ones_2, zeros_2])
jac_output3 = torch.stack([zeros_2, zeros_2, ones_2])
input = {y1: jac_output1, y2: jac_output2, y3: jac_output3}
jac = Jac(outputs=OrderedSet([y1, y2, y3]), inputs=OrderedSet([a1, a2]), chunk_size=chunk_size)
jacobians = jac(input)
expected_jacobians = {
a1: torch.stack([x * 7, 2 * a1, 3 * a1**2]),
a2: torch.stack([x * 7, 2 * a2, 3 * a2**2]),
}
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
def test_composition_of_jacs_is_jac():
"""
Tests that the composition of 2 Jac transforms is equivalent to computing the Jac directly in
a single transform.
"""
x1 = tensor_(5.0)
x2 = tensor_(6.0)
a = tensor_(2.0, requires_grad=True)
y1 = a * x1
y2 = a * x2
z1 = y1 + x2
z2 = y2 + x1
input = {z1: tensor_([1.0, 0.0]), z2: tensor_([0.0, 1.0])}
outer_jac = Jac(
outputs=OrderedSet([y1, y2]), inputs=OrderedSet([a]), chunk_size=None, retain_graph=True
)
inner_jac = Jac(
outputs=OrderedSet([z1, z2]),
inputs=OrderedSet([y1, y2]),
chunk_size=None,
retain_graph=True,
)
composed_jac = outer_jac << inner_jac
jac = Jac(outputs=OrderedSet([z1, z2]), inputs=OrderedSet([a]), chunk_size=None)
jacobians = composed_jac(input)
expected_jacobians = jac(input)
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
def test_conjunction_of_jacs_is_jac():
"""
Tests that the conjunction of 2 Jac transforms is equivalent to computing the Jac directly in
a single transform.
"""
x1 = tensor_(5.0)
x2 = tensor_(6.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y1 = a1 * x1
y2 = a2 * x2
y = torch.stack([y1, y2])
input = {y: eye_(len(y))}
jac1 = Jac(outputs=OrderedSet([y]), inputs=OrderedSet([a1]), chunk_size=None, retain_graph=True)
jac2 = Jac(outputs=OrderedSet([y]), inputs=OrderedSet([a2]), chunk_size=None, retain_graph=True)
conjunction_of_jacs = jac1 | jac2
jac = Jac(outputs=OrderedSet([y]), inputs=OrderedSet([a1, a2]), chunk_size=None)
jacobians = conjunction_of_jacs(input)
expected_jacobians = jac(input)
assert_tensor_dicts_are_close(jacobians, expected_jacobians)
def test_create_graph():
"""Tests that the Jac transform behaves correctly when `create_graph` is set to `True`."""
x = tensor_(5.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y1 = a1 * a2
y2 = a2 * x
y = torch.stack([y1, y2])
input = {y: eye_(2)}
jac = Jac(
outputs=OrderedSet([y]), inputs=OrderedSet([a1, a2]), chunk_size=None, create_graph=True
)
jacobians = jac(input)
assert jacobians[a1].requires_grad
assert jacobians[a2].requires_grad
def test_check_keys():
"""
Tests that the `check_keys` method works correctly: the input_keys should match the stored
outputs.
"""
x = tensor_(5.0)
a1 = tensor_(2.0, requires_grad=True)
a2 = tensor_(3.0, requires_grad=True)
y = torch.stack([a1 * x, a2 * x])
jac = Jac(outputs=OrderedSet([y]), inputs=OrderedSet([a1, a2]), chunk_size=None)
output_keys = jac.check_keys({y})
assert output_keys == {a1, a2}
with raises(RequirementError):
jac.check_keys({y, x})
with raises(RequirementError):
jac.check_keys(set())