forked from PaddlePaddle/Paddle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_tensor_requires_grad.py
More file actions
476 lines (377 loc) · 16.9 KB
/
test_tensor_requires_grad.py
File metadata and controls
476 lines (377 loc) · 16.9 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import numpy as np
import paddle
class TestTensorRequiresGrad(unittest.TestCase):
def setUp(self):
"""Set up test fixtures before each test method."""
paddle.disable_static()
np.random.seed(1919)
def tearDown(self):
"""Clean up after each test method."""
paddle.disable_static()
def test_basic_requires_grad_property(self):
"""Test basic requires_grad property functionality"""
# Test default behavior - new tensors have stop_gradient=True by default
x = paddle.randn([2, 3])
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
# Test setting requires_grad to True
x.requires_grad = True
self.assertTrue(x.requires_grad)
self.assertFalse(x.stop_gradient)
# Test setting requires_grad to False
x.requires_grad = False
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
def test_requires_grad_consistency_with_stop_gradient(self):
"""Test that requires_grad is always the opposite of stop_gradient"""
x = paddle.randn([3, 4])
# Test multiple state changes
states = [True, False, True, False]
for requires_grad_state in states:
x.requires_grad = requires_grad_state
self.assertEqual(x.requires_grad, requires_grad_state)
self.assertEqual(x.stop_gradient, not requires_grad_state)
# Also test setting stop_gradient directly
x.stop_gradient = requires_grad_state
self.assertEqual(x.requires_grad, not requires_grad_state)
self.assertEqual(x.stop_gradient, requires_grad_state)
def test_requires_grad_type_checking(self):
"""Test type checking for requires_grad setter"""
x = paddle.randn([2, 2])
# Valid boolean values should work
x.requires_grad = True
x.requires_grad = False
# Invalid types should raise TypeError
invalid_values = ["true", 1, 0, None, [], {}]
for invalid_value in invalid_values:
with self.assertRaises(TypeError) as cm:
x.requires_grad = invalid_value
self.assertIn("requires_grad must be bool", str(cm.exception))
def test_requires_grad_with_parameter(self):
"""Test requires_grad behavior with Parameter tensors"""
# Create a parameter - Parameters have stop_gradient=False by default (trainable)
param = paddle.create_parameter([3, 4], dtype='float32')
self.assertTrue(
param.requires_grad
) # Parameters require grad by default
self.assertFalse(
param.stop_gradient
) # Parameters are trainable by default
# Test changing requires_grad on parameter
param.requires_grad = False
self.assertFalse(param.requires_grad)
self.assertTrue(param.stop_gradient)
def test_requires_grad_in_gradient_computation(self):
"""Test requires_grad behavior in actual gradient computation"""
x = paddle.randn([2, 3])
y = paddle.randn([2, 3])
# Set both tensors to require grad
x.requires_grad = True
y.requires_grad = True
z = x * y + x.sum()
z.backward()
self.assertIsNotNone(x.grad)
self.assertIsNotNone(y.grad)
# Clear gradients and test with requires_grad=False
x.grad._clear_data()
y.grad._clear_data()
x.requires_grad = False
y.requires_grad = True
z = x * y + x.sum()
z.backward()
self.assertIsNone(x.grad) # x doesn't require grad
self.assertIsNotNone(y.grad) # y requires grad
def test_requires_grad_with_different_tensor_types(self):
"""Test requires_grad with different tensor creation methods"""
# Test with different tensor creation functions
tensor_creators = [
lambda: paddle.randn([2, 3]),
lambda: paddle.zeros([2, 3]),
lambda: paddle.ones([2, 3]),
lambda: paddle.to_tensor([[1, 2, 3], [4, 5, 6]], dtype='float32'),
lambda: paddle.arange(6, dtype='float32').reshape([2, 3]),
]
for creator in tensor_creators:
x = creator()
# All newly created tensors should have requires_grad=False by default
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
# Test modification
x.requires_grad = True
self.assertTrue(x.requires_grad)
self.assertFalse(x.stop_gradient)
def test_requires_grad_with_tensor_operations(self):
"""Test requires_grad preservation through tensor operations"""
x = paddle.randn([3, 3])
y = paddle.randn([3, 3])
x.requires_grad = True
y.requires_grad = False
# Operations should preserve requires_grad appropriately
z1 = x + y # Should require grad (x requires grad)
z2 = x * 2.0 # Should require grad (x requires grad)
z3 = y.sin() # Should not require grad (y doesn't require grad)
self.assertTrue(z1.requires_grad)
self.assertTrue(z2.requires_grad)
self.assertFalse(z3.requires_grad)
def test_requires_grad_with_detach(self):
"""Test requires_grad behavior with detach operation"""
x = paddle.randn([2, 3])
x.requires_grad = True
y = x.detach()
# Detached tensor should not require grad
self.assertTrue(x.requires_grad)
self.assertFalse(y.requires_grad)
self.assertTrue(y.stop_gradient)
def test_requires_grad_static_mode(self):
"""Test requires_grad behavior in static mode"""
paddle.enable_static()
try:
with paddle.static.program_guard(paddle.static.Program()):
x = paddle.static.data(name='x', shape=[2, 3], dtype='float32')
# In static mode, variables also have stop_gradient=True by default
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
# Test setting requires_grad in static mode
x.requires_grad = True
self.assertTrue(x.requires_grad)
self.assertFalse(x.stop_gradient)
finally:
paddle.disable_static()
def test_requires_grad_edge_cases(self):
"""Test edge cases for requires_grad"""
# Test with scalar tensor
scalar = paddle.to_tensor(3.14)
self.assertFalse(scalar.requires_grad) # False
scalar.requires_grad = True
self.assertTrue(scalar.requires_grad)
# Test with empty tensor
empty = paddle.empty([0, 3])
self.assertFalse(empty.requires_grad) # False
empty.requires_grad = True
self.assertTrue(empty.requires_grad)
# Test with different dtypes
dtypes = [paddle.float32, paddle.float64, paddle.int32, paddle.int64]
for dtype in dtypes:
x = paddle.ones([2, 2], dtype=dtype)
# All tensors should have requires_grad=False by default
self.assertFalse(x.requires_grad)
# Float tensors should support requires_grad
if dtype in [paddle.float32, paddle.float64]:
x.requires_grad = True
self.assertTrue(x.requires_grad)
class TestTensorRequiresGrad_(unittest.TestCase):
def setUp(self):
"""Set up test fixtures before each test method."""
paddle.disable_static()
np.random.seed(1919)
def tearDown(self):
"""Clean up after each test method."""
paddle.disable_static()
def test_basic_requires_grad_property(self):
"""Test basic requires_grad property functionality"""
# Test default behavior - new tensors have stop_gradient=True by default
x = paddle.randn([2, 3])
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
# Test setting requires_grad to True
x.requires_grad_(True)
self.assertTrue(x.requires_grad)
self.assertFalse(x.stop_gradient)
# Test setting requires_grad to False
x.requires_grad_(False)
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
def test_requires_grad_consistency_with_stop_gradient(self):
"""Test that requires_grad is always the opposite of stop_gradient"""
x = paddle.randn([3, 4])
# Test multiple state changes
states = [True, False, True, False]
for requires_grad_state in states:
x.requires_grad_(requires_grad_state)
self.assertEqual(x.requires_grad, requires_grad_state)
self.assertEqual(x.stop_gradient, not requires_grad_state)
# Also test setting stop_gradient directly
x.stop_gradient = requires_grad_state
self.assertEqual(x.requires_grad, not requires_grad_state)
self.assertEqual(x.stop_gradient, requires_grad_state)
def test_requires_grad_type_checking(self):
"""Test type checking for requires_grad setter"""
x = paddle.randn([2, 2])
# Valid boolean values should work
x.requires_grad_(True)
x.requires_grad_(False)
# Invalid types should raise TypeError
invalid_values = ["true", 1, 0, None, [], {}]
for invalid_value in invalid_values:
with self.assertRaises(TypeError) as cm:
x.requires_grad_(invalid_value)
self.assertIn("requires_grad must be bool", str(cm.exception))
def test_requires_grad_with_parameter(self):
"""Test requires_grad behavior with Parameter tensors"""
# Create a parameter - Parameters have stop_gradient=False by default (trainable)
param = paddle.create_parameter([3, 4], dtype='float32')
self.assertTrue(
param.requires_grad
) # Parameters require grad by default
self.assertFalse(
param.stop_gradient
) # Parameters are trainable by default
# Test changing requires_grad on parameter
param.requires_grad_(False)
self.assertFalse(param.requires_grad)
self.assertTrue(param.stop_gradient)
def test_requires_grad_in_gradient_computation(self):
"""Test requires_grad behavior in actual gradient computation"""
x = paddle.randn([2, 3])
y = paddle.randn([2, 3])
# Set both tensors to require grad
x.requires_grad_(True)
y.requires_grad_(True)
z = x * y + x.sum()
z.backward()
self.assertIsNotNone(x.grad)
self.assertIsNotNone(y.grad)
# Clear gradients and test with requires_grad=False
x.grad._clear_data()
y.grad._clear_data()
x.requires_grad_(False)
y.requires_grad_(True)
z = x * y + x.sum()
z.backward()
self.assertIsNone(x.grad) # x doesn't require grad
self.assertIsNotNone(y.grad) # y requires grad
def test_requires_grad_with_different_tensor_types(self):
"""Test requires_grad with different tensor creation methods"""
# Test with different tensor creation functions
tensor_creators = [
lambda: paddle.randn([2, 3]),
lambda: paddle.zeros([2, 3]),
lambda: paddle.ones([2, 3]),
lambda: paddle.to_tensor([[1, 2, 3], [4, 5, 6]], dtype='float32'),
lambda: paddle.arange(6, dtype='float32').reshape([2, 3]),
]
for creator in tensor_creators:
x = creator()
# All newly created tensors should have requires_grad=False by default
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
# Test modification
x.requires_grad_(True)
self.assertTrue(x.requires_grad)
self.assertFalse(x.stop_gradient)
def test_requires_grad_with_tensor_operations(self):
"""Test requires_grad preservation through tensor operations"""
x = paddle.randn([3, 3])
y = paddle.randn([3, 3])
x.requires_grad_(True)
y.requires_grad_(False)
# Operations should preserve requires_grad appropriately
z1 = x + y # Should require grad (x requires grad)
z2 = x * 2.0 # Should require grad (x requires grad)
z3 = y.sin() # Should not require grad (y doesn't require grad)
self.assertTrue(z1.requires_grad)
self.assertTrue(z2.requires_grad)
self.assertFalse(z3.requires_grad)
def test_requires_grad_with_detach(self):
"""Test requires_grad behavior with detach operation"""
x = paddle.randn([2, 3])
x.requires_grad_(True)
y = x.detach()
# Detached tensor should not require grad
self.assertTrue(x.requires_grad)
self.assertFalse(y.requires_grad)
self.assertTrue(y.stop_gradient)
def test_requires_grad_old_static_mode(self):
"""Test requires_grad behavior in static mode"""
paddle.enable_static()
with paddle.pir_utils.OldIrGuard():
x = paddle.static.data(name='x', shape=[2, 3], dtype='float32')
# In static mode, variables also have stop_gradient=True by default
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
# Test setting requires_grad in static mode
x.requires_grad_(True)
self.assertTrue(x.requires_grad)
self.assertFalse(x.stop_gradient)
def test_requires_grad_static_mode(self):
"""Test requires_grad behavior in static mode"""
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program()):
x = paddle.static.data(name='x', shape=[2, 3], dtype='float32')
# In static mode, variables also have stop_gradient=True by default
self.assertFalse(x.requires_grad)
self.assertTrue(x.stop_gradient)
# Test setting requires_grad in static mode
x.requires_grad_(True)
self.assertTrue(x.requires_grad)
self.assertFalse(x.stop_gradient)
def test_requires_grad_edge_cases(self):
"""Test edge cases for requires_grad"""
# Test with scalar tensor
scalar = paddle.to_tensor(3.14)
self.assertFalse(scalar.requires_grad) # False
scalar.requires_grad_(True)
self.assertTrue(scalar.requires_grad)
# Test with empty tensor
empty = paddle.empty([0, 3])
self.assertFalse(empty.requires_grad) # False
empty.requires_grad_(True)
self.assertTrue(empty.requires_grad)
# Test with different dtypes
dtypes = [paddle.float32, paddle.float64, paddle.int32, paddle.int64]
for dtype in dtypes:
x = paddle.ones([2, 2], dtype=dtype)
# All tensors should have requires_grad=False by default
self.assertFalse(x.requires_grad)
# Float tensors should support requires_grad
if dtype in [paddle.float32, paddle.float64]:
x.requires_grad_(True)
self.assertTrue(x.requires_grad)
class TestAPI(unittest.TestCase):
def setUp(self):
paddle.enable_static()
def assert_api(self, api_func, require_grad):
main_program = paddle.static.Program()
with paddle.static.program_guard(main_program):
x = api_func()
self.assertEqual(x.stop_gradient, require_grad)
# test for setter
x.requires_grad_(require_grad)
self.assertEqual(x.stop_gradient, not require_grad)
def test_full(self):
api = lambda: paddle.full(shape=[2, 3], fill_value=1.0)
self.assert_api(api, True)
def test_data(self):
api = lambda: paddle.static.data('x', [4, 4], dtype='float32')
self.assert_api(api, True)
# TODO(Aurelius84): Add more test cases after API is migrated.
class TestParameters(unittest.TestCase):
def setUp(self):
paddle.enable_static()
def test_create_param(self):
main_program = paddle.static.Program()
with paddle.static.program_guard(main_program):
w = paddle.create_parameter(shape=[784, 200], dtype='float32')
self.assertEqual(w.stop_gradient, False)
self.assertEqual(w.persistable, True)
# test for setter
w.requires_grad_(False)
w.persistable = False
self.assertEqual(w.stop_gradient, True)
self.assertEqual(w.persistable, False)
if __name__ == '__main__':
unittest.main()