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

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

22 23
#include "../../XTensor.h"
#include "../../XName.h"
24
#include "../../XUtility.h"
liyinqiao committed
25
#include "../shape/IsSameShaped.h"
26 27
#include "Sum.h"
#include "../math/ScaleAndShift.h"
28 29
#include "Multiply.h"
#include "Multiply.cuh"
xuchen committed
30
#include "MultiplyDim.h"
xiaotong committed
31 32

namespace nts { // namespace nts(NiuTrans.Tensor)
liyinqiao committed
33

xiaotong committed
34 35
/*
element-wise product of two tensors
36

xiaotong committed
37 38
c(i) = a(i)*b(i) + \alpha * c(i)
where i is the index of the item
39

40 41 42
>> a - tensor a
>> b - tensor b
>> c - result tensor
xiaotong committed
43
>> alpha - the coefficient
44
>> leadingDim - the dimension along which we perform broadcasting
xiaotong committed
45
*/
46
void _Multiply(const XTensor * a, const XTensor * b, XTensor * c, DTYPE alpha, int leadingDim)
xiaotong committed
47 48
{
    CheckNTErrors((a->unitNum <= c->unitNum && b->unitNum <= c->unitNum),
49 50 51
                  "Unmatched tensors in multiplication!");
    CheckNTErrors((a->order == b->order && a->order == c->order), 
                  "Unmatched tensors!");
xiaotong committed
52

53
    CheckDev(a->devID, b->devID);
xiaotong committed
54 55
#ifdef USE_CUDA
    if (a->devID >= 0 || b->devID >= 0 || c->devID >= 0) {
56
        _CudaMultiply(a, b, c, alpha, leadingDim);
xiaotong committed
57 58 59 60 61 62 63 64 65
        return;
    }
#endif

    int stride = 1;
    int blockSizeA = 1;
    int blockSizeB = 1;
    int blockSizeC = 1;
    int blockNum = 1;
66 67 68
    int dimensionSizeA = a->dimSize[leadingDim];
    int dimensionSizeB = b->dimSize[leadingDim];
    int dimensionSizeC = c->dimSize[leadingDim];
xiaotong committed
69 70

    for (int i = 0; i < a->order; i++) {
71 72 73
        if (i != leadingDim) {
            CheckNTErrors((a->dimSize[i] == b->dimSize[i] &&
                           a->dimSize[i] == c->dimSize[i]),
74
                          "Unmatched tensors!");
xiaotong committed
75
        }
76 77
        if (i > leadingDim)
            stride *= a->dimSize[i];
xiaotong committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    }

    blockSizeA = stride * dimensionSizeA;
    blockSizeB = stride * dimensionSizeB;
    blockSizeC = stride * dimensionSizeC;
    blockNum = a->unitNum / blockSizeA;

    if (!a->isSparse && !b->isSparse) {
        if (a->dataType == DEFAULT_DTYPE && b->dataType == DEFAULT_DTYPE) {
            if (a->unitNum == c->unitNum && b->unitNum == c->unitNum) {
                int size = a->unitNum;
                DTYPE * ap = (DTYPE*)a->data;
                DTYPE * bp = (DTYPE*)b->data;
                DTYPE * cp = (DTYPE*)c->data;
                if (alpha == 0) {
                    for (int i = 0; i < size; i++)
                        cp[i] = ap[i] * bp[i];
                }
                else {
                    for (int i = 0; i < size; i++)
                        cp[i] = ap[i] * bp[i] + alpha * cp[i];
                }
            }
            else {
                for (int k = 0; k < blockNum; k++) {

                    for (int ci = 0, ai = 0, bi = 0; ci < dimensionSizeC; ci++, ai++, bi++) {
                        if (ai >= dimensionSizeA)
                            ai = 0;
                        if (bi >= dimensionSizeB)
                            bi = 0;
                        DTYPE * ap = (DTYPE*)a->data + k * blockSizeA + ai * stride;
                        DTYPE * bp = (DTYPE*)b->data + k * blockSizeB + bi * stride;
                        DTYPE * cp = (DTYPE*)c->data + k * blockSizeC + ci * stride;
                        for (int j = 0; j < stride; j++)
                            cp[j] = ap[j] * bp[j] + cp[j] * alpha;
                    }
                }
            }
        }
        else {
            // TODO!!
            ShowNTErrors("TODO!");
        }
    }
    else {
        // TODO!!
        ShowNTErrors("TODO!");
    }
}

129
/*
130 131 132
element-wise product of two tensors (do it on site)
keep the result in the input tensor a and return nothing

133 134
a(i) = a(i)*b(i) + \alpha * a(i)
where i is the index of the item
135

136 137 138 139 140 141 142 143 144 145
>> a - tensor a (where keep the result)
>> b - tensor b
>> alpha - the coefficient
>> leadingDim - the dimension along which we perform broadcasting
*/
void _MultiplyMe(XTensor * a, const XTensor * b, DTYPE alpha, int leadingDim)
{
    _Multiply(a, b, a, alpha, leadingDim);
}

liyinqiao committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159
/*
element-wise product of two tensors (do it on site)
keep the result in the input tensor a and return nothing

a(i) = a(i)*b(i) + \alpha * a(i)
where i is the index of the item

>> a - tensor a (where keep the result)
>> b - tensor b
>> alpha - the coefficient
>> leadingDim - the dimension along which we perform broadcasting
*/
void MultiplyMe(XTensor& a, const XTensor& b, DTYPE alpha, int leadingDim)
{
160
    if (b.order == 0){
liyinqiao committed
161
        DTYPE scale = b.Get0D() + alpha;
162

liyinqiao committed
163
        _ScaleAndShift(&a, &a, scale, 0.0F);
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    }
    else {
        int n = GetBroadcastDimIndex(a, b);

        if (n == -1) {
            CheckNTErrors(a.dimSize[leadingDim] == b.dimSize[leadingDim], "TODO!");

            /* call _Multiply function */
            _Multiply(&a, &b, &a, alpha, leadingDim);
        }
        else if (n >= 0 && n < a.order) {
            /* call _MultiplyDim function */
            _MultiplyDim(&a, &b, &a, n, alpha);
        }
        else {
            ShowNTErrors("Something is wrong!");
        }
    }
liyinqiao committed
182 183
}

184
/*
xiaotong committed
185
element-wise product of two tensors (return an XTensor structure)
186 187
make a new tensor c to keep the result and return it

188
c(i) = a(i)*b(i)
189
where i is the index of the item
190

191 192 193 194 195
>> a - tensor a
>> b - tensor b
>> leadingDim - the dimension along which we perform broadcasting
<< return - the product of the tensors
*/
196
XTensor Multiply(const XTensor &a, const XTensor &b, int leadingDim)
197 198
{
    XTensor c(&a);
xiaotong committed
199
    c.SetTMPFlag();
200 201 202 203

    if (b.order == 0){
        DTYPE scale = b.Get0D();
        ScaleAndShift(a, c, scale, 0.0F);
xuchen committed
204
    }
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    else {
        DTYPE alpha = 0.0F;
        int n = GetBroadcastDimIndex(a, b);

        if(n == -1){
            CheckNTErrors(a.dimSize[leadingDim] == b.dimSize[leadingDim], "TODO!");

            /* call _Multiply function */
            _Multiply(&a, &b, &c, alpha, leadingDim);

            /* tensor connections */
            if (a.enableGrad && b.enableGrad) {
                XLink::MakeLink(&a, &b, &c, MATH_MULTIPLY);
            }
        }
        else if(n >= 0 && n < a.order){
            /* call _MultiplyDim function */
            _MultiplyDim(&a, &b, &c, n, alpha);

            /* tensor connections */
            if (a.enableGrad && b.enableGrad) {
                XLink::MakeLink(&a, &b, &c, MATH_MULTIPLYDIM);
                XLink::AddParamToHeadInt(&c, n);
            }
        }
        else{
            ShowNTErrors("Something is wrong!");
xuchen committed
232
        }
xuchen committed
233 234
    }

235 236 237
    return c;
}

238 239 240 241 242 243 244 245 246 247 248 249
/*
element-wise product of two tensors

c(i) = a(i)*b(i) + \alpha * c(i)
where i is the index of the item

>> a - tensor a
>> b - tensor b
>> c - result tensor
>> alpha - the coefficient
>> leadingDim - the dimension along which we perform broadcasting
*/
liyinqiao committed
250
void Multiply(const XTensor &a, const XTensor &b, XTensor &c, DTYPE alpha, int leadingDim)
251
{
252
    if (!c.isInit || !IsSameShaped(a, c)) {
253
        InitTensorV2(&c, &a);
254 255
    }

256 257 258 259
    if (b.order == 0){
        DTYPE scale = b.Get0D();
        XTensor * tmp1 = NewTensorBufV2(&a, a.devID, a.mem);
        XTensor * tmp2 = NewTensorBufV2(&c, c.devID, c.mem);
260

261 262 263
        ScaleAndShift(a, *tmp1, scale, 0.0F);
        ScaleAndShift(c, *tmp2, alpha, 0.0F);
        Sum(*tmp2, *tmp1, c);
264

265 266
        DelTensorBuf(tmp1);
        DelTensorBuf(tmp2);
267
    }
268 269
    else {
        int n = GetBroadcastDimIndex(a, b);
270

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        if (n == -1) {
            CheckNTErrors(a.dimSize[leadingDim] == b.dimSize[leadingDim], "TODO!");

            /* call _Multiply function */
            _Multiply(&a, &b, &c, alpha, leadingDim);

            if (a.enableGrad && b.enableGrad) {
                /* tensor connections */
                XLink::MakeLink(&a, &b, &c, MATH_MULTIPLY);
            }
        }
        else if (n >= 0 && n < a.order) {
            /* call _MultiplyDim function */
            _MultiplyDim(&a, &b, &c, n, alpha);

            if (a.enableGrad && b.enableGrad) {
                /* tensor connections */
                XLink::MakeLink(&a, &b, &c, MATH_MULTIPLYDIM);
                XLink::AddParamToHeadInt(&c, n);
            }
        }
        else {
            ShowNTErrors("Something is wrong!");
294 295 296 297
        }
    }
}

xiaotong committed
298
} // namespace nts(NiuTrans.Tensor)