|
| 1 | +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import unittest |
| 16 | + |
| 17 | +import numpy as np |
| 18 | + |
| 19 | +import paddle |
| 20 | + |
| 21 | + |
| 22 | +class TestTensorRequiresGrad(unittest.TestCase): |
| 23 | + def setUp(self): |
| 24 | + """Set up test fixtures before each test method.""" |
| 25 | + paddle.disable_static() |
| 26 | + np.random.seed(1919) |
| 27 | + |
| 28 | + def tearDown(self): |
| 29 | + """Clean up after each test method.""" |
| 30 | + paddle.disable_static() |
| 31 | + |
| 32 | + def test_basic_requires_grad_property(self): |
| 33 | + """Test basic requires_grad property functionality""" |
| 34 | + # Test default behavior - new tensors have stop_gradient=True by default |
| 35 | + x = paddle.randn([2, 3]) |
| 36 | + self.assertFalse(x.requires_grad) |
| 37 | + self.assertTrue(x.stop_gradient) |
| 38 | + |
| 39 | + # Test setting requires_grad to True |
| 40 | + x.requires_grad = True |
| 41 | + self.assertTrue(x.requires_grad) |
| 42 | + self.assertFalse(x.stop_gradient) |
| 43 | + |
| 44 | + # Test setting requires_grad to False |
| 45 | + x.requires_grad = False |
| 46 | + self.assertFalse(x.requires_grad) |
| 47 | + self.assertTrue(x.stop_gradient) |
| 48 | + |
| 49 | + def test_requires_grad_consistency_with_stop_gradient(self): |
| 50 | + """Test that requires_grad is always the opposite of stop_gradient""" |
| 51 | + x = paddle.randn([3, 4]) |
| 52 | + |
| 53 | + # Test multiple state changes |
| 54 | + states = [True, False, True, False] |
| 55 | + for requires_grad_state in states: |
| 56 | + x.requires_grad = requires_grad_state |
| 57 | + self.assertEqual(x.requires_grad, requires_grad_state) |
| 58 | + self.assertEqual(x.stop_gradient, not requires_grad_state) |
| 59 | + |
| 60 | + # Also test setting stop_gradient directly |
| 61 | + x.stop_gradient = requires_grad_state |
| 62 | + self.assertEqual(x.requires_grad, not requires_grad_state) |
| 63 | + self.assertEqual(x.stop_gradient, requires_grad_state) |
| 64 | + |
| 65 | + def test_requires_grad_type_checking(self): |
| 66 | + """Test type checking for requires_grad setter""" |
| 67 | + x = paddle.randn([2, 2]) |
| 68 | + |
| 69 | + # Valid boolean values should work |
| 70 | + x.requires_grad = True |
| 71 | + x.requires_grad = False |
| 72 | + |
| 73 | + # Invalid types should raise TypeError |
| 74 | + invalid_values = ["true", 1, 0, None, [], {}] |
| 75 | + for invalid_value in invalid_values: |
| 76 | + with self.assertRaises(TypeError) as cm: |
| 77 | + x.requires_grad = invalid_value |
| 78 | + self.assertIn("requires_grad must be bool", str(cm.exception)) |
| 79 | + |
| 80 | + def test_requires_grad_with_parameter(self): |
| 81 | + """Test requires_grad behavior with Parameter tensors""" |
| 82 | + # Create a parameter - Parameters have stop_gradient=False by default (trainable) |
| 83 | + param = paddle.create_parameter([3, 4], dtype='float32') |
| 84 | + self.assertTrue( |
| 85 | + param.requires_grad |
| 86 | + ) # Parameters require grad by default |
| 87 | + self.assertFalse( |
| 88 | + param.stop_gradient |
| 89 | + ) # Parameters are trainable by default |
| 90 | + |
| 91 | + # Test changing requires_grad on parameter |
| 92 | + param.requires_grad = False |
| 93 | + self.assertFalse(param.requires_grad) |
| 94 | + self.assertTrue(param.stop_gradient) |
| 95 | + |
| 96 | + def test_requires_grad_in_gradient_computation(self): |
| 97 | + """Test requires_grad behavior in actual gradient computation""" |
| 98 | + x = paddle.randn([2, 3]) |
| 99 | + y = paddle.randn([2, 3]) |
| 100 | + |
| 101 | + # Set both tensors to require grad |
| 102 | + x.requires_grad = True |
| 103 | + y.requires_grad = True |
| 104 | + |
| 105 | + z = x * y + x.sum() |
| 106 | + z.backward() |
| 107 | + |
| 108 | + self.assertIsNotNone(x.grad) |
| 109 | + self.assertIsNotNone(y.grad) |
| 110 | + |
| 111 | + # Clear gradients and test with requires_grad=False |
| 112 | + x.grad._clear_data() |
| 113 | + y.grad._clear_data() |
| 114 | + |
| 115 | + x.requires_grad = False |
| 116 | + y.requires_grad = True |
| 117 | + |
| 118 | + z = x * y + x.sum() |
| 119 | + z.backward() |
| 120 | + |
| 121 | + self.assertIsNone(x.grad) # x doesn't require grad |
| 122 | + self.assertIsNotNone(y.grad) # y requires grad |
| 123 | + |
| 124 | + def test_requires_grad_with_different_tensor_types(self): |
| 125 | + """Test requires_grad with different tensor creation methods""" |
| 126 | + # Test with different tensor creation functions |
| 127 | + tensor_creators = [ |
| 128 | + lambda: paddle.randn([2, 3]), |
| 129 | + lambda: paddle.zeros([2, 3]), |
| 130 | + lambda: paddle.ones([2, 3]), |
| 131 | + lambda: paddle.to_tensor([[1, 2, 3], [4, 5, 6]], dtype='float32'), |
| 132 | + lambda: paddle.arange(6, dtype='float32').reshape([2, 3]), |
| 133 | + ] |
| 134 | + |
| 135 | + for creator in tensor_creators: |
| 136 | + x = creator() |
| 137 | + # All newly created tensors should have requires_grad=False by default |
| 138 | + self.assertFalse(x.requires_grad) |
| 139 | + self.assertTrue(x.stop_gradient) |
| 140 | + |
| 141 | + # Test modification |
| 142 | + x.requires_grad = True |
| 143 | + self.assertTrue(x.requires_grad) |
| 144 | + self.assertFalse(x.stop_gradient) |
| 145 | + |
| 146 | + def test_requires_grad_with_tensor_operations(self): |
| 147 | + """Test requires_grad preservation through tensor operations""" |
| 148 | + x = paddle.randn([3, 3]) |
| 149 | + y = paddle.randn([3, 3]) |
| 150 | + |
| 151 | + x.requires_grad = True |
| 152 | + y.requires_grad = False |
| 153 | + |
| 154 | + # Operations should preserve requires_grad appropriately |
| 155 | + z1 = x + y # Should require grad (x requires grad) |
| 156 | + z2 = x * 2.0 # Should require grad (x requires grad) |
| 157 | + z3 = y.sin() # Should not require grad (y doesn't require grad) |
| 158 | + |
| 159 | + self.assertTrue(z1.requires_grad) |
| 160 | + self.assertTrue(z2.requires_grad) |
| 161 | + self.assertFalse(z3.requires_grad) |
| 162 | + |
| 163 | + def test_requires_grad_with_detach(self): |
| 164 | + """Test requires_grad behavior with detach operation""" |
| 165 | + x = paddle.randn([2, 3]) |
| 166 | + x.requires_grad = True |
| 167 | + |
| 168 | + y = x.detach() |
| 169 | + |
| 170 | + # Detached tensor should not require grad |
| 171 | + self.assertTrue(x.requires_grad) |
| 172 | + self.assertFalse(y.requires_grad) |
| 173 | + self.assertTrue(y.stop_gradient) |
| 174 | + |
| 175 | + def test_requires_grad_static_mode(self): |
| 176 | + """Test requires_grad behavior in static mode""" |
| 177 | + paddle.enable_static() |
| 178 | + |
| 179 | + try: |
| 180 | + with paddle.static.program_guard(paddle.static.Program()): |
| 181 | + x = paddle.static.data(name='x', shape=[2, 3], dtype='float32') |
| 182 | + |
| 183 | + # In static mode, variables also have stop_gradient=True by default |
| 184 | + self.assertFalse(x.requires_grad) |
| 185 | + self.assertTrue(x.stop_gradient) |
| 186 | + |
| 187 | + # Test setting requires_grad in static mode |
| 188 | + x.requires_grad = True |
| 189 | + self.assertTrue(x.requires_grad) |
| 190 | + self.assertFalse(x.stop_gradient) |
| 191 | + |
| 192 | + finally: |
| 193 | + paddle.disable_static() |
| 194 | + |
| 195 | + def test_requires_grad_edge_cases(self): |
| 196 | + """Test edge cases for requires_grad""" |
| 197 | + # Test with scalar tensor |
| 198 | + scalar = paddle.to_tensor(3.14) |
| 199 | + self.assertFalse(scalar.requires_grad) # False |
| 200 | + scalar.requires_grad = True |
| 201 | + self.assertTrue(scalar.requires_grad) |
| 202 | + |
| 203 | + # Test with empty tensor |
| 204 | + empty = paddle.empty([0, 3]) |
| 205 | + self.assertFalse(empty.requires_grad) # False |
| 206 | + empty.requires_grad = True |
| 207 | + self.assertTrue(empty.requires_grad) |
| 208 | + |
| 209 | + # Test with different dtypes |
| 210 | + dtypes = [paddle.float32, paddle.float64, paddle.int32, paddle.int64] |
| 211 | + for dtype in dtypes: |
| 212 | + x = paddle.ones([2, 2], dtype=dtype) |
| 213 | + # All tensors should have requires_grad=False by default |
| 214 | + self.assertFalse(x.requires_grad) |
| 215 | + |
| 216 | + # Float tensors should support requires_grad |
| 217 | + if dtype in [paddle.float32, paddle.float64]: |
| 218 | + x.requires_grad = True |
| 219 | + self.assertTrue(x.requires_grad) |
| 220 | + |
| 221 | + |
| 222 | +if __name__ == '__main__': |
| 223 | + unittest.main() |
0 commit comments