CopyIndexed.cpp 11.6 KB
Newer Older
xiaotong committed
1
/* NiuTrans.Tensor - an open-source tensor library
2
 * Copyright (C) 2017, Natural Language Processing Lab, Northeastern University.
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 * All rights reserved.
 *
 * 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.
 */
xiaotong committed
17 18

/*
19 20
 * $Created by: XIAO Tong (email: xiaotong@mail.neu.edu.cn) 2018-04-24
 */
xiaotong committed
21 22

#include "CopyIndexed.h"
23
#include "CopyIndexed.cuh"
xiaotong committed
24
#include "CopyBlocks.h"
25
#include "Gather.h"
26
#include "../../XName.h"
liyinqiao committed
27
#include "../utilities/SetAscendingOrder.h"
xiaotong committed
28 29 30 31 32

namespace nts { // namespace nts(NiuTrans.Tensor)

/*
copy indexed sub-tensors
33

xiaotong committed
34 35 36
>> s - the source tensor
>> t - the target tensor
>> dim - the leading dimension to define "sub-tensors"
37 38
         e.g., for a tensor of size (4, 2, 3) and dim = 0, 
         we have 4 sub-tensors of size (2, 3)
xiaotong committed
39 40 41
>> srcIndex - index of the source sub-tensors
>> indexSize - length of srcIndex (and tgtIndex)
>> tgtIndex - index of the target sub-tensors
42
>> copyNum - number of the sub-tensors we copy for each source index, 
xiaotong committed
43 44
             e.g., for srcIndex = [0,1] and copyNum = 2,
             we actually copy the source sub-tensors 0, 1, 1 and 2
xiaotong committed
45
*/
46 47 48
void _CopyIndexed(const XTensor * s, XTensor * t, int dim, 
                  int * srcIndex, int indexSize, int * tgtIndex, 
                  int copyNum)
xiaotong committed
49
{
50 51
    CheckNTErrors(s && t, "Invalid tensors!");
    CheckNTErrors(s->devID == t->devID || (s->devID < 0 && t->devID < 0),
52
                  "the data must be kept on the same device!");
53 54
    CheckNTErrors(dim < s->order && dim < t->order, "A too larget dimension specified!");
    CheckNTErrors(s->unitSize == t->unitSize, "Unmatched tensors!");
xiaotong committed
55 56 57 58 59

    int blockSizeSrc = 1;
    int blockSizeTgt = 1;
    int blockNumSrc = 1;
    int blockNumTgt = 1;
60 61
    int leadDimSizeSrc = s->dimSize[dim];
    int leadDimSizeTgt = t->dimSize[dim];
xiaotong committed
62 63
    int indexOffsetNum = 1;

64 65 66 67 68 69 70 71 72 73
    for (int i = dim + 1; i < s->order; i++) {
        blockSizeSrc *= s->dimSize[i];
    }
    for (int i = dim + 1; i < t->order; i++) {
        blockSizeTgt *= t->dimSize[i];
    }
    for (int i = 0; i <= dim; i++)
    {
        blockNumSrc *= s->dimSize[i];
        blockNumTgt *= t->dimSize[i];
xiaotong committed
74 75
    }

xiaotong committed
76
    CheckNTErrors(blockSizeSrc == blockSizeTgt, "Unmatched tensors!");
77
    indexOffsetNum = blockNumSrc / s->dimSize[dim];
xiaotong committed
78 79 80 81 82

    int realIndexSize = indexOffsetNum * indexSize * copyNum;
    int * realSrcIndex = new int[realIndexSize];
    int * realTgtIndex = new int[realIndexSize];
    for (int i = 0; i < indexOffsetNum; i++) {
83 84 85
        int base = i * indexSize * copyNum;
        int baseSrc = i * leadDimSizeSrc;
        int baseTgt = i * leadDimSizeTgt;
xiaotong committed
86
        for (int j = 0; j < indexSize; j++) {
87 88 89
            int offset = base + j * copyNum;
            int * rsi = realSrcIndex + offset;
            int * rti = realTgtIndex + offset;
xiaotong committed
90
            for (int k = 0; k < copyNum; k++) {
91 92
                rsi[k] = baseSrc + srcIndex[j] + k;
                rti[k] = baseTgt + tgtIndex[j] + k;
xiaotong committed
93 94
                CheckNTErrors(rsi[k] < s->unitNum, "Wrong index!");
                CheckNTErrors(rti[k] < t->unitNum, "Wrong index!");
xiaotong committed
95 96 97 98 99
            }
        }
    }

    for (int i = 0; i < indexSize; i++) {
xiaotong committed
100 101
        CheckNTErrors(srcIndex[i] < blockNumSrc, "Index is out of scope!");
        CheckNTErrors(tgtIndex[i] < blockNumTgt, "Index is out of scope!");
xiaotong committed
102 103
    }

104
    _CopyBlocks(s->data, s->unitSize, blockSizeSrc * s->unitSize, realSrcIndex, realIndexSize, t->data, realTgtIndex, s->mem, s->devID);
xiaotong committed
105 106 107

    delete[] realSrcIndex;
    delete[] realTgtIndex;
108 109 110
}

/*
111 112 113 114 115
copy selected sub-tensors where indeces are kept in tensors

>> s - the source tensor
>> t - the target tensor
>> dim - the leading dimension to define "sub-tensors"
116 117
         e.g., for a tensor of size (4, 2, 3) and dim = 0, 
         we have 4 sub-tensors of size (2, 3)
118 119 120
>> srcIndex - the tensor to save the index of the source sub-tensors
>> tgtIndex - the tensor to save the index of the target sub-tensors
>> copyNum - number of the sub-tensors we copy for each source index, 
xiaotong committed
121 122
             e.g., for srcIndex = [0,1] and copyNum = 2,
             we actually copy the source sub-tensors 0, 1, 1 and 2
123 124 125 126 127 128 129 130 131
*/
void _CopyIndexed(const XTensor * s, XTensor * t, int dim, 
                  const XTensor * srcIndex, const XTensor * tgtIndex, 
                  int copyNum)
{
    int order = s->order;
    int indexSize = srcIndex->unitNum;

    CheckNTErrors(indexSize != 0, "NULL index!")
132 133 134
    CheckNTErrors(s && t, "Invalid tensors!");
    CheckNTErrors(srcIndex && tgtIndex, "Invalid index tensors!");
    CheckNTErrors(s->devID == t->devID || (s->devID < 0 && t->devID < 0),
135
                  "the data must be kept on the same device!");
136
    CheckNTErrors(srcIndex->devID == srcIndex->devID || (s->devID < 0 && t->devID < 0),
137
                  "the index must be kept on the same device!");
138
    CheckNTErrors(s->devID == srcIndex->devID || (s->devID < 0 && t->devID < 0),
139
                  "the data and index must be kept on the same device!");
140 141 142
    CheckNTErrors(dim >= 0 && dim < order, "A too larget dimension specified!");
    CheckNTErrors(s->unitSize == t->unitSize, "Unmatched tensors!");
    CheckNTErrors(srcIndex->unitNum == tgtIndex->unitNum, "Unmatched index tensors!");
143 144 145 146 147 148

    for (int i = 0; i < order; i++) {
        if (i != dim) {
            CheckNTErrors(s->GetDim(i) == t->GetDim(i), "Unmatched dimensions");
        }
        else {
149
            CheckNTErrors(t->GetDim(i) >= indexSize * copyNum, "Unmatched dimensions");
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        }
    }

#ifdef USE_CUDA
    if (s->devID >= 0 && srcIndex->devID >= 0) {
        _CudaCopyIndexed(s, t, dim, srcIndex, tgtIndex, copyNum);
        return;
    }
#endif

    int blockNum = 1;
    int stride = 1;
    int blockSizeSrc = 1;
    int blockSizeTgt = 1;

    for (int i = 0; i < dim; i++)
        blockNum *= s->GetDim(i);
    
    for (int i = dim + 1; i < order; i++)
        stride *= s->GetDim(i);

    blockSizeSrc = stride * s->GetDim(dim);
    blockSizeTgt = stride * t->GetDim(dim);

    DTYPE * sData = (DTYPE*)s->data;
    DTYPE * tData = (DTYPE*)t->data;
    int * sIndex = (int*)srcIndex->data;
    int * tIndex = (int*)tgtIndex->data;

    for (int i = 0; i < indexSize; i++) {
        for (int c = 0; c < copyNum; c++) {
            int si = sIndex[i] + c;
            int ti = tIndex[i] + c;

            for (int j = 0; j < blockNum; j++) {
                DTYPE * sd = sData + j * blockSizeSrc + si * stride;
                DTYPE * td = tData + j * blockSizeTgt + ti * stride;
                for (int k = 0; k < stride; k++)
                    *(td + k) = *(sd + k);
            }
        
        }
    }
}

liyinqiao committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
/* 
copy selected sub-tensors

>> s - the source tensor
>> t - the target tensor
>> dim - the leading dimension to define "sub-tensors"
         e.g., for a tensor of size (3, 2, 4) and dim = 2, 
         we have 4 sub-tensors of size (3, 2)
>> srcIndex - the tensor to save the index of the source sub-tensors
>> copyNum - number of the sub-tensors we copy for each source index, 
             e.g., for srcIndex = [1,4] and copyNum = 2,
             we actually copy the source sub-tensors 1, 2, 4, 5
*/
void _CopyIndexed(const XTensor * s, XTensor * t, int dim,                   
                  const XTensor * srcIndex, int copyNum)
{
    XTensor * tgtIndex = NewTensor(srcIndex);
liyinqiao committed
212
    SetAscendingOrder(*tgtIndex, 0);
liyinqiao committed
213 214 215 216 217

    _CopyIndexed(s, t, dim, srcIndex, tgtIndex, copyNum);
    delete tgtIndex;
}

218 219 220 221 222 223
/*
copy selected sub-tensors where indeces are kept in tensors (return an XTensor structure)
make a new tensor to keep the result and return it

>> s - the source tensor
>> dim - the leading dimension to define "sub-tensors"
224 225
         e.g., for a tensor of size (3, 2, 4) and dim = 2, 
         we have 4 sub-tensors of size (3,2)
226 227 228 229
>> srcIndex - index of the source sub-tensors
>> indexSize - length of srcIndex (and tgtIndex)
>> tgtIndex - index of the target sub-tensors
>> copyNum - number of the sub-tensors we copy for each source index, 
230 231
             e.g., for srcIndex = [1,4] and copyNum = 2,
             we actually copy the source sub-tensors 1, 2, 4, 5
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
<< return - the result of copying indexed sub-tensors
*/
XTensor CopyIndexed(const XTensor & s, int dim, 
                    const XTensor & srcIndex, const XTensor & tgtIndex,
                    int copyNum)
{
    CheckNTErrors(dim >= 0 && dim < s.order, "A too larget dimension specified!");

    int order = s.order;
    int * dimSize = new int[order];
    int indexSize = srcIndex.unitNum;

    for (int i = 0; i < s.order; i++) {
        if (i == dim)
            dimSize[i] = indexSize * copyNum;
        else
            dimSize[i] = s.dimSize[i];
    }
    
    float dr = (!s.isSparse) ? 1.0F : s.denseRatio;
    XTensor t(order, dimSize, s.dataType, dr, s.devID, s.mem);
    t.SetTMPFlag();

    /* call _CopyIndexed function */
    _CopyIndexed(&s, &t, dim, &srcIndex, &tgtIndex, copyNum);

258 259 260 261
    TensorList list(3);
    list.Add((XTensor*)&s);
    list.Add((XTensor*)&srcIndex);
    list.Add((XTensor*)&tgtIndex);
262 263

    /* tensor connection */
xuchen committed
264 265 266 267 268 269
    if (s.enableGrad) {
        XLink::MakeLink(&list, &t, MOVEMENT_COPYINDEXED);
        XLink::AddParamToHeadInt(&t, dim);
        XLink::AddParamToHeadInt(&t, copyNum);
    }

270 271 272 273 274 275 276 277
    /* destroy variables */
    delete[] dimSize;

    return t;
}

/*
copy indexed sub-tensors (return a XTensor structure)
278 279 280 281
make a new tensor to keep the result and return it

>> s - the source tensor
>> dim - the leading dimension to define "sub-tensors"
282 283
         e.g., for a tensor of size (3, 2, 4) and dim = 2, 
         we have 4 sub-tensors of size (3,2)
284 285 286 287
>> srcIndex - index of the source sub-tensors
>> indexSize - length of srcIndex (and tgtIndex)
>> tgtIndex - index of the target sub-tensors
>> copyNum - number of the sub-tensors we copy for each source index, 
288 289
             e.g., for srcIndex = [1,4] and copyNum = 2,
             we actually copy the source sub-tensors 1, 2, 4, 5
290 291 292 293
<< return - the result of copying indexed sub-tensors
*/
XTensor CopyIndexed(const XTensor &s, int dim, int * srcIndex, int indexSize, int * tgtIndex, int copyNum)
{
294
    CheckNTErrors(dim >= 0 && dim < s.order, "A too larget dimension specified!");
295 296 297 298 299 300 301 302 303 304 305

    int order = s.order;
    int * dimSize = new int[order];

    for (int i = 0; i < s.order; i++) {
        if (i == dim)
            dimSize[i] = indexSize * copyNum;
        else
            dimSize[i] = s.dimSize[i];
    }
    
306 307
    float dr = (!s.isSparse) ? 1.0F : s.denseRatio;
    XTensor t(order, dimSize, s.dataType, dr, s.devID, s.mem);
308
    t.SetTMPFlag();
309 310 311 312

    /* call _CopyIndexed function */
    _CopyIndexed(&s, &t, dim, srcIndex, indexSize, tgtIndex, copyNum);

xiaotong committed
313 314
    /* NOTE: we must allocate a new array to save index,
             because the source index may be released. */
315 316 317 318 319 320
    int * saveSrcIndex = new int[indexSize];
    memcpy(saveSrcIndex, srcIndex, indexSize * sizeof(int));

    int * saveTgtIndex = new int[indexSize];
    memcpy(saveTgtIndex, tgtIndex, indexSize * sizeof(int));

321
    /* tensor connection */
xuchen committed
322 323 324 325 326 327 328 329 330
    if (s.enableGrad) {
        XLink::MakeLink(&s, NULL, &t, MOVEMENT_COPYINDEXED);
        XLink::AddParamToHeadInt(&t, dim);
        XLink::AddParamToHeadPointer(&t, saveSrcIndex);
        XLink::AddParamToHeadInt(&t, indexSize);
        XLink::AddParamToHeadPointer(&t, saveTgtIndex);
        XLink::AddParamToHeadInt(&t, copyNum);
    }

331 332
    /* destroy variables */
    delete[] dimSize;
333

334
    return t;
xiaotong committed
335 336 337
}

} // namespace nts(NiuTrans.Tensor)