|
| 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 | +import paddle |
| 17 | +import time |
| 18 | +import paddle.nn as nn |
| 19 | +import numpy as np |
| 20 | +import threading |
| 21 | + |
| 22 | + |
| 23 | +class SimpleNet(nn.Layer): |
| 24 | + def __init__(self, in_dim, out_dim): |
| 25 | + super(SimpleNet, self).__init__() |
| 26 | + self.fc = nn.Linear(in_dim, out_dim) |
| 27 | + |
| 28 | + def forward(self, x): |
| 29 | + return self.fc(x) |
| 30 | + |
| 31 | + |
| 32 | +class TestCases(unittest.TestCase): |
| 33 | + @paddle.no_grad() |
| 34 | + def thread_1_main(self): |
| 35 | + time.sleep(8) |
| 36 | + |
| 37 | + def thread_2_main(self): |
| 38 | + in_dim = 10 |
| 39 | + out_dim = 3 |
| 40 | + net = SimpleNet(in_dim, out_dim) |
| 41 | + for _ in range(1000): |
| 42 | + x = paddle.to_tensor(np.random.rand(32, in_dim).astype('float32')) |
| 43 | + self.assertTrue(x.stop_gradient) |
| 44 | + x = net(x) |
| 45 | + self.assertFalse(x.stop_gradient) |
| 46 | + |
| 47 | + def test_main(self): |
| 48 | + threads = [] |
| 49 | + for _ in range(10): |
| 50 | + threads.append(threading.Thread(target=self.thread_1_main)) |
| 51 | + threads.append(threading.Thread(target=self.thread_2_main)) |
| 52 | + for t in threads: |
| 53 | + t.start() |
| 54 | + for t in threads: |
| 55 | + t.join() |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + unittest.main() |
0 commit comments