forked from mindspore-lab/mindnlp
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add PadTransform (mindspore-lab#323)
- Loading branch information
Showing
8 changed files
with
152 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
# Copyright 2023 Huawei Technologies Co., Ltd | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================ | ||
"""AddToken transform""" | ||
import numpy as np | ||
from mindspore.dataset.transforms.transforms import PyTensorOperation | ||
from mindspore.dataset.text.transforms import Implementation | ||
|
||
|
||
class PadTransform(PyTensorOperation): | ||
""" | ||
Pad tensor to a fixed length with given padding value. | ||
Args: | ||
max_length (int): Maximum length to pad to. | ||
pad_value (int): Value to pad the tensor with. | ||
return_length (bool): Whether return auxiliary sequence length. | ||
Raises: | ||
TypeError: If `token` is not of type str. | ||
Supported Platforms: | ||
``CPU`` | ||
Examples: | ||
""" | ||
|
||
# @check_decode | ||
def __init__(self, max_length: int, pad_value:int, return_length:bool = False): | ||
super().__init__() | ||
self.max_length = max_length | ||
self.pad_value = pad_value | ||
self.return_length = return_length | ||
self.implementation = Implementation.PY | ||
|
||
def __call__(self, text_input): | ||
""" | ||
Call method for input conversion for eager mode with C++ implementation. | ||
""" | ||
if not isinstance(text_input, np.ndarray): | ||
raise TypeError( | ||
f"Input should be a text line in 1-D ndarray contains string, got {type(text_input)}.") | ||
return super().__call__(text_input) | ||
|
||
def execute_py(self, text_input): | ||
""" | ||
Execute method. | ||
""" | ||
return self._execute_py(text_input) | ||
|
||
def _execute_py(self, text_input): | ||
""" | ||
Execute method. | ||
""" | ||
text_input = text_input[:self.max_length] | ||
text_length = len(text_input) | ||
|
||
pad_value = np.array([self.pad_value] * (self.max_length - text_length), text_input.dtype) | ||
text_output = np.concatenate([text_input, pad_value], 0) | ||
|
||
if self.return_length: | ||
length = np.array(text_length) | ||
return text_output, length | ||
|
||
return text_output |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Copyright 2023 Huawei Technologies Co., Ltd | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================ | ||
"""Test the AddToken""" | ||
|
||
from mindspore.dataset import NumpySlicesDataset | ||
from mindnlp.transforms import PadTransform, Truncate | ||
from mindnlp.utils import less_min_pynative_first | ||
|
||
def test_pad_transform(): | ||
"""test PadTransform""" | ||
dataset = NumpySlicesDataset(data={"text": [[1, 2, 3, 4, 5]]}) | ||
|
||
pad_transform_op = PadTransform(10, 0) | ||
dataset = dataset.map(operations=pad_transform_op) | ||
|
||
data_after = next(dataset.create_tuple_iterator(output_numpy=True))[0] | ||
assert data_after.tolist() == [1, 2, 3, 4, 5, 0, 0, 0, 0, 0] | ||
|
||
def test_pad_transform_with_seq_length(): | ||
"""test PadTransform with seq_length""" | ||
dataset = NumpySlicesDataset(data={"text": [[1, 2, 3, 4, 5]]}) | ||
|
||
pad_transform_op = PadTransform(10, 0, True) | ||
if less_min_pynative_first: | ||
dataset = dataset.map(pad_transform_op, 'text', ['text', 'len'], ['text', 'len']) | ||
else: | ||
dataset = dataset.map(pad_transform_op, 'text', ['text', 'len']) | ||
|
||
data_after = next(dataset.create_tuple_iterator(output_numpy=True)) | ||
data = data_after[0] | ||
seq_len = data_after[1] | ||
|
||
assert data.tolist() == [1, 2, 3, 4, 5, 0, 0, 0, 0, 0] | ||
assert seq_len == 5 | ||
|
||
def test_pad_transform_with_seq_length_multi_transform(): | ||
"""test PadTransform with seq_length in multi-transforms.""" | ||
dataset = NumpySlicesDataset(data={"text": [[1, 2, 3, 4, 5]]}) | ||
|
||
pad_transform_op = PadTransform(10, 0, True) | ||
truncate_token = Truncate(3) | ||
|
||
if less_min_pynative_first: | ||
dataset = dataset.map([truncate_token, pad_transform_op], 'text', ['text', 'len'], ['text', 'len']) | ||
else: | ||
dataset = dataset.map([truncate_token, pad_transform_op], 'text', ['text', 'len']) | ||
|
||
data_after = next(dataset.create_tuple_iterator(output_numpy=True)) | ||
data = data_after[0] | ||
seq_len = data_after[1] | ||
|
||
assert data.tolist() == [1, 2, 3, 0, 0, 0, 0, 0, 0, 0] | ||
assert seq_len == 3 |