Skip to content

Commit 1178ff0

Browse files
authored
[API compatibility] add paddle.ravel (#74439)
* add paddle.ravel * fix test case * fix typo
1 parent cb81162 commit 1178ff0

File tree

4 files changed

+175
-0
lines changed

4 files changed

+175
-0
lines changed

python/paddle/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,7 @@
328328
masked_scatter_,
329329
moveaxis,
330330
put_along_axis,
331+
ravel,
331332
repeat_interleave,
332333
reshape,
333334
reshape_,
@@ -1094,6 +1095,7 @@
10941095
'std',
10951096
'flatten',
10961097
'flatten_',
1098+
'ravel',
10971099
'asin',
10981100
'multiply',
10991101
'multiply_',

python/paddle/tensor/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@
193193
moveaxis,
194194
put_along_axis,
195195
put_along_axis_,
196+
ravel,
196197
repeat_interleave,
197198
reshape,
198199
reshape_,

python/paddle/tensor/manipulation.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1992,6 +1992,46 @@ def flatten(
19921992
return out
19931993

19941994

1995+
def ravel(input: Tensor) -> Tensor:
1996+
"""
1997+
Return a contiguous flattened tensor. A copy is made only if needed.
1998+
Note:
1999+
The output Tensor will share data with origin Tensor and doesn't have a Tensor copy in ``dygraph`` mode.
2000+
If you want to use the Tensor copy version, please use `Tensor.clone` like ``ravel_clone_x = x.ravel().clone()``.
2001+
For example:
2002+
2003+
.. code-block:: text
2004+
Case 1:
2005+
Given
2006+
X.shape = (3, 100, 100, 4)
2007+
2008+
We get:
2009+
Out.shape = (3 * 100 * 100 * 4)
2010+
Args:
2011+
x (Tensor): A tensor of number of dimensions >= axis. A tensor with data type float16, float32,
2012+
float64, int8, int32, int64, uint8.
2013+
2014+
Returns:
2015+
Tensor: A tensor with the contents of the input tensor, whose input axes are flattened by indicated :attr:`start_axis` and :attr:`stop_axis`, and data type is the same as input :attr:`x`.
2016+
2017+
Examples:
2018+
2019+
.. code-block:: python
2020+
2021+
>>> import paddle
2022+
2023+
>>> image_shape=(2, 3, 4, 4)
2024+
2025+
>>> x = paddle.arange(end=image_shape[0] * image_shape[1] * image_shape[2] * image_shape[3])
2026+
>>> img = paddle.reshape(x, image_shape)
2027+
2028+
>>> out = paddle.ravel(img)
2029+
>>> print(out.shape)
2030+
[96]
2031+
"""
2032+
return flatten(input)
2033+
2034+
19952035
@inplace_apis_in_dygraph_only
19962036
def flatten_(
19972037
x: Tensor, start_axis: int = 0, stop_axis: int = -1, name: str | None = None

test/legacy_test/test_ravel.py

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
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 numpy as np
18+
19+
import paddle
20+
from paddle import base
21+
22+
23+
class TestPaddleRavel(unittest.TestCase):
24+
def setUp(self):
25+
self.input_np = np.array([[1, 2, 3], [4, 5, 6]], dtype="float32")
26+
self.input_shape = self.input_np.shape
27+
self.input_dtype = "float32"
28+
self.op_static = lambda x: paddle.ravel(x)
29+
self.op_dygraph = lambda x: paddle.ravel(x)
30+
self.expected = lambda x: x.flatten()
31+
self.places = [None, paddle.CPUPlace()]
32+
33+
def check_static_result(self, place):
34+
paddle.enable_static()
35+
main_prog = paddle.static.Program()
36+
startup_prog = paddle.static.Program()
37+
with paddle.static.program_guard(main_prog, startup_prog):
38+
input_name = 'input'
39+
input_var = paddle.static.data(
40+
name=input_name, shape=self.input_shape, dtype=self.input_dtype
41+
)
42+
res = self.op_static(input_var)
43+
exe = base.Executor(place)
44+
fetches = exe.run(
45+
main_prog,
46+
feed={input_name: self.input_np},
47+
fetch_list=[res],
48+
)
49+
expect = (
50+
self.expected(self.input_np)
51+
if callable(self.expected)
52+
else self.expected
53+
)
54+
np.testing.assert_allclose(fetches[0], expect, rtol=1e-05)
55+
56+
def test_static(self):
57+
for place in self.places:
58+
self.check_static_result(place=place)
59+
60+
def check_dygraph_result(self, place):
61+
with base.dygraph.guard(place):
62+
input = paddle.to_tensor(self.input_np, stop_gradient=False)
63+
result = self.op_dygraph(input)
64+
expect = (
65+
self.expected(self.input_np)
66+
if callable(self.expected)
67+
else self.expected
68+
)
69+
# check forward
70+
np.testing.assert_allclose(result.numpy(), expect, rtol=1e-05)
71+
72+
# check backward
73+
paddle.autograd.backward([result])
74+
np.testing.assert_allclose(
75+
input.grad.numpy(), np.ones_like(self.input_np), rtol=1e-05
76+
)
77+
78+
def test_dygraph(self):
79+
for place in self.places:
80+
self.check_dygraph_result(place=place)
81+
82+
83+
class TestPaddleRavel_case1(TestPaddleRavel):
84+
def setUp(self):
85+
# check Ravel 1d
86+
self.input_np = np.array([7, 8, 9], dtype="float32")
87+
self.input_shape = self.input_np.shape
88+
self.input_dtype = "float32"
89+
self.op_static = lambda x: paddle.ravel(x)
90+
self.op_dygraph = lambda x: paddle.ravel(x)
91+
self.expected = lambda x: x.flatten()
92+
self.places = [None, paddle.CPUPlace()]
93+
94+
95+
class TestPaddleRavel_case2(TestPaddleRavel):
96+
def setUp(self):
97+
# check Ravel 3d
98+
self.input_np = np.arange(24, dtype="float32").reshape(2, 3, 4)
99+
self.input_shape = self.input_np.shape
100+
self.input_dtype = "float32"
101+
self.op_static = lambda x: paddle.ravel(x)
102+
self.op_dygraph = lambda x: paddle.ravel(x)
103+
self.expected = lambda x: x.flatten()
104+
self.places = [None, paddle.CPUPlace()]
105+
106+
107+
class TestPaddleRavel_case3(TestPaddleRavel):
108+
def setUp(self):
109+
# check Ravel 0d (scalar)
110+
self.input_np = np.array(5.0, dtype="float32")
111+
self.input_shape = self.input_np.shape
112+
self.input_dtype = "float32"
113+
self.op_static = lambda x: paddle.ravel(x)
114+
self.op_dygraph = lambda x: paddle.ravel(x)
115+
self.expected = lambda x: x.flatten()
116+
self.places = [None, paddle.CPUPlace()]
117+
118+
119+
class TestPaddleRavel_case4(TestPaddleRavel):
120+
def setUp(self):
121+
# check Ravel empty array
122+
self.input_np = np.array([], dtype="float32").reshape(0, 3)
123+
self.input_shape = self.input_np.shape
124+
self.input_dtype = "float32"
125+
self.op_static = lambda x: paddle.ravel(x)
126+
self.op_dygraph = lambda x: paddle.ravel(x)
127+
self.expected = lambda x: x.flatten()
128+
self.places = [None, paddle.CPUPlace()]
129+
130+
131+
if __name__ == "__main__":
132+
unittest.main()

0 commit comments

Comments
 (0)