diff --git a/python/paddle/fluid/dygraph/layers.py b/python/paddle/fluid/dygraph/layers.py index 088fed03c3595..6392b0d1151b7 100644 --- a/python/paddle/fluid/dygraph/layers.py +++ b/python/paddle/fluid/dygraph/layers.py @@ -1582,7 +1582,8 @@ def _apply(self, func, device, dtype, blocking, include_sublayers=True): blocking) for key, buf in self._buffers.items(): - self._buffers[key] = func(buf, device, dtype, blocking) + if buf is not None: + self._buffers[key] = func(buf, device, dtype, blocking) self._dtype = dtype diff --git a/python/paddle/fluid/tests/unittests/test_base_layer.py b/python/paddle/fluid/tests/unittests/test_base_layer.py index 3bdd03b321276..ab5ce77469286 100644 --- a/python/paddle/fluid/tests/unittests/test_base_layer.py +++ b/python/paddle/fluid/tests/unittests/test_base_layer.py @@ -544,16 +544,25 @@ def func_test_to_api_numpy_dtype(self): else: self.assertTrue(isinstance(p, paddle.fluid.framework.ParamBase)) + def func_test_to_api_none_buffer(self): + model = paddle.nn.Linear(2, 4) + buffer = None + model.register_buffer("buf_name", buffer, persistable=True) + model.to(dtype='float64') + self.assertEqual(model._buffers['buf_name'], None) + def test_main(self): with _test_eager_guard(): self.funcsetUp() self.func_test_to_api() self.func_test_to_api_paddle_dtype() self.func_test_to_api_numpy_dtype() + self.func_test_to_api_none_buffer() self.funcsetUp() self.func_test_to_api() self.func_test_to_api_paddle_dtype() self.func_test_to_api_numpy_dtype() + self.func_test_to_api_none_buffer() if __name__ == '__main__':