Skip to content

Commit c5e8259

Browse files
Support model.to with device=tensor.place (#75867)
* support model.to with device=tensor.place * simplify code
1 parent 9999342 commit c5e8259

File tree

2 files changed

+40
-8
lines changed

2 files changed

+40
-8
lines changed

python/paddle/nn/layer/layers.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2698,18 +2698,12 @@ def _to_impl(
26982698
device = paddle.device._convert_to_place(device)
26992699
elif isinstance(
27002700
device,
2701-
(
2702-
core.CPUPlace,
2703-
core.CUDAPlace,
2704-
core.CUDAPinnedPlace,
2705-
core.XPUPlace,
2706-
),
2701+
core.Place,
27072702
):
27082703
pass
27092704
else:
27102705
raise ValueError(
2711-
"device value error, must be str, paddle.CPUPlace(), paddle.CUDAPlace(), paddle.CUDAPinnedPlace() or paddle.XPUPlace(), but the type of device is "
2712-
+ type(device).__name__
2706+
f"device should be type of str, paddle.CPUPlace, paddle.CUDAPlace, paddle.CUDAPinnedPlace, paddle.XPUPlace, or paddle.base.libpaddle.Place, but got {type(device).__name__}"
27132707
)
27142708

27152709
if blocking is None:

test/legacy_test/test_layer_to.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Copyright (c) 2025 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 paddle
18+
19+
20+
class TensorToTest(unittest.TestCase):
21+
def test_layer_to_place(self):
22+
model = paddle.vision.models.resnet18()
23+
place = paddle.randn([]).cpu().place
24+
_ = model.to(place)
25+
26+
def test_layer_to_place_error(self):
27+
model = paddle.vision.models.resnet18()
28+
29+
place = 1
30+
with self.assertRaisesRegex(
31+
ValueError,
32+
"device should be type of str, paddle.CPUPlace, paddle.CUDAPlace, paddle.CUDAPinnedPlace, paddle.XPUPlace, or paddle.base.libpaddle.Place, but got int",
33+
):
34+
_ = model.to(place)
35+
36+
37+
if __name__ == '__main__':
38+
unittest.main()

0 commit comments

Comments
 (0)