|
| 1 | +# Copyright (c) 2018 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 core |
| 16 | +import numpy as np |
| 17 | + |
| 18 | +__all__ = ['create_lod_tensor', 'create_random_int_lodtensor'] |
| 19 | + |
| 20 | + |
| 21 | +def _validate_lod(lod, tensor_height=-1): |
| 22 | + """Check whether the input length-based lod info is valid. |
| 23 | +
|
| 24 | + There are several things to check: |
| 25 | + 1. lod should be a list of lists. Empty list is fine. |
| 26 | + 2. The length of each sublist (a lod level) should be at least one. |
| 27 | + 3. Each element in each lod level should be an integer greater than 0. |
| 28 | + 4. The sum of one lod level should be equal to the length of the next lod level. |
| 29 | + 5. The sum of the last lod level should be equal to the tensor height. |
| 30 | + Bypass this check if user does not provide tensor_height as input. |
| 31 | +
|
| 32 | + Args: |
| 33 | + lod: the length-based lod info, e.g., [[2, 3], [2, 1, 2, 3, 4]]. |
| 34 | + tensor_height: the outermost dimension of the tensor with which the input |
| 35 | + lod is associated with. |
| 36 | +
|
| 37 | + Returns: |
| 38 | + A boolean indicating whether the input lod is valid or not. |
| 39 | + """ |
| 40 | + assert isinstance(lod, list), "lod should be a list" |
| 41 | + # Empty lod is fine |
| 42 | + if len(lod) == 0: |
| 43 | + return True |
| 44 | + |
| 45 | + lod_sum = [] |
| 46 | + for level in lod: |
| 47 | + assert isinstance(level, list), "each item in lod should be a list" |
| 48 | + # Each level of lod should have at least one length info |
| 49 | + if len(level) < 1: |
| 50 | + return False |
| 51 | + level_sum = 0 |
| 52 | + for lod_len in level: |
| 53 | + # Each length in a level should be > 0 |
| 54 | + if lod_len <= 0: |
| 55 | + return False |
| 56 | + level_sum += lod_len |
| 57 | + lod_sum.append(level_sum) |
| 58 | + |
| 59 | + for idx, val in enumerate(lod_sum[:-1]): |
| 60 | + # Each level's sum should be equal to |
| 61 | + # the number of items in the next level |
| 62 | + if val != len(lod[idx + 1]): |
| 63 | + return False |
| 64 | + |
| 65 | + if tensor_height == -1: |
| 66 | + return True |
| 67 | + else: |
| 68 | + # Last level's sum should be equal to the tensor height |
| 69 | + return lod_sum[-1] == tensor_height |
| 70 | + |
| 71 | + |
| 72 | +def _convert_lod(lod): |
| 73 | + """Convert a length-based lod to a offset-based lod. |
| 74 | +
|
| 75 | + If the length-based lod is [[2, 3], [2, 1, 2, 3, 4]], |
| 76 | + then the offset-based lod is [[0, 2, 5], [0, 2, 3, 5, 8, 12]]. |
| 77 | +
|
| 78 | + Args: |
| 79 | + lod: a length-based lod info. |
| 80 | +
|
| 81 | + Returns: |
| 82 | + A list of lists as the offset-based lod converted to from the input lod. |
| 83 | + """ |
| 84 | + new_lod = [] |
| 85 | + for level in lod: |
| 86 | + cur_len = 0 |
| 87 | + new_level = [cur_len] |
| 88 | + for lod_len in level: |
| 89 | + cur_len += lod_len |
| 90 | + new_level.append(cur_len) |
| 91 | + new_lod.append(new_level) |
| 92 | + return new_lod |
| 93 | + |
| 94 | + |
| 95 | +def create_lod_tensor(data, lod, place): |
| 96 | + """Create a lod tensor from a numpy array or an existing lod tensor. |
| 97 | +
|
| 98 | + Create a lod tensor by doing the following: |
| 99 | + 1. Check that the length-based input lod is valid. |
| 100 | + 2. Convert the length-based lod to a offset-based LoD. |
| 101 | + 3. Copy the data from a numpy array or a existing lod tensor to |
| 102 | + CPU or GPU device (based on input place). |
| 103 | + 4. Set the level of detail (LoD) using the offset-based LoD. |
| 104 | + |
| 105 | + Use example: |
| 106 | + Suppose we want LoDTensor to hold data for sequences of word, where each word is |
| 107 | + represented by an integer. If we want to create a LoDTensor to represent two |
| 108 | + sentences, one of 2 words, and one of 3 words. |
| 109 | +
|
| 110 | + Then 'data' can be a numpy array of integers with shape (5, 1). |
| 111 | + 'lod' will be [[2, 3]], indicating the length(# of words) in each sentence. |
| 112 | + This length-based input lod [[2, 3]] will be converted to offset-based lod [[0, 2, 5]] |
| 113 | + inside the function call. |
| 114 | +
|
| 115 | + Please refer to |
| 116 | + github.com/PaddlePaddle/Paddle/blob/develop/doc/fluid/design/concepts/lod_tensor.md |
| 117 | + for more details regarding LoD. |
| 118 | +
|
| 119 | + Args: |
| 120 | + data: a numpy array or a LoDTensor holding the data to be copied. |
| 121 | + lod: a list of lists indicating the length-based LoD info specified by the user. |
| 122 | + place: CPU or GPU place indicating where the data in the new LoDTensor will be stored. |
| 123 | +
|
| 124 | + Returns: |
| 125 | + A fluid LoDTensor object with tensor data and lod info. |
| 126 | + """ |
| 127 | + if isinstance(data, core.LoDTensor): |
| 128 | + return create_lod_tensor(np.array(data), lod, place) |
| 129 | + elif isinstance(data, np.ndarray): |
| 130 | + assert _validate_lod(lod, |
| 131 | + data.shape[0]), "the provided lod info is invalid" |
| 132 | + tensor = core.LoDTensor() |
| 133 | + tensor.set(data, place) |
| 134 | + tensor.set_lod(_convert_lod(lod)) |
| 135 | + return tensor |
| 136 | + else: |
| 137 | + raise Exception( |
| 138 | + "data should be either a LoDTensor or a Numpy array, but you pass type %s instead" |
| 139 | + % (type(data))) |
| 140 | + |
| 141 | + |
| 142 | +def create_random_int_lodtensor(lod, base_shape, place, low, high): |
| 143 | + """Create a LoDTensor containing random integers. |
| 144 | +
|
| 145 | + This function is frequently used in the book examples. So we revised it based on |
| 146 | + the new create_lod_tensor API and put it here in the lod_tensor module to simplify |
| 147 | + the code. |
| 148 | +
|
| 149 | + The function does the following: |
| 150 | + 1. Calculate the overall shape of the LoDTensor based on the length-based 'lod' input |
| 151 | + and the shape of the basic element in 'base_shape'. |
| 152 | + 2. Create a numpy array of this shape. |
| 153 | + 3. Create the LoDTensor using create_lod_tensor API. |
| 154 | +
|
| 155 | + Suppose we want LoDTensor to hold data for sequences of word, where each word is |
| 156 | + represented by an integer. If we want to create a LoDTensor to represent two |
| 157 | + sentences, one of 2 words, and one of 3 words. Then 'base_shape' is [1], input |
| 158 | + length-based 'lod' is [[2, 3]]. Then the overall shape of the LoDTensor would be |
| 159 | + [5, 1], holding 5 words for two sentences. |
| 160 | +
|
| 161 | + Args: |
| 162 | + data: a numpy array or a LoDTensor holding the data to be copied. |
| 163 | + lod: a list of lists indicating the length-based LoD info specified by the user. |
| 164 | + base_shape: the shape of the basic element to be held by the LoDTensor. |
| 165 | + place: CPU or GPU place indicating where the data in the new LoDTensor will be stored. |
| 166 | + low: the lower bound of the random integers. |
| 167 | + high: the upper bound of the random integers. |
| 168 | +
|
| 169 | + Returns: |
| 170 | + A fluid LoDTensor object with tensor data and lod info. |
| 171 | + """ |
| 172 | + assert isinstance(base_shape, list), "base_shape should be a list" |
| 173 | + converted_lod = _convert_lod(lod) |
| 174 | + # append the total number of basic elements to the front of its shape |
| 175 | + overall_shape = [converted_lod[-1][-1]] + base_shape |
| 176 | + # the range of integer data elements is [low, high] |
| 177 | + data = np.random.random_integers(low, high, overall_shape).astype("int64") |
| 178 | + return create_lod_tensor(data, lod, place) |
0 commit comments