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

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

#include <math.h>
#include "Softmax.h"
#include "Softmax.cuh"
25
#include "../XName.h"
xiaotong committed
26
#include "../XUtility.h"
27 28
#include "../core/reduce/ReduceSum.h"
#include "../core/reduce/ReduceMax.h"
29
#include "../core/shape/IsSameShaped.h"
xiaotong committed
30 31 32 33 34 35 36 37 38

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

/*
softmax y = e^x / \sum_{i} e^{x_i}
>> x - input vector
>> y - result
>> leadDim - leading dimension (along which we perform reduction)
*/
39
void _Softmax(const XTensor * x, XTensor * y, int leadDim)
xiaotong committed
40
{
41 42 43
    if(leadDim < 0)
        leadDim = x->order - 1;

xiaotong committed
44 45 46 47
    if(!x->isSparse && !y->isSparse && x->dataType == y->dataType){
        int * dimSize = new int[x->order - 1];
        for(int i = 0; i < x->order; i++){
            if(i < leadDim)
48
                dimSize[i] = x->dimSize[i];
xiaotong committed
49
            else if(i > leadDim)
50
                dimSize[i - 1] = x->dimSize[i];
xiaotong committed
51 52 53 54 55 56
        }

        XMem * mem = x->mem;
        XTensor * max = NULL;
        XTensor * sum = NULL;

57 58
        max = NewTensorBufV2(x->order - 1, dimSize, x->dataType, x->denseRatio, x->devID, mem);
        sum = NewTensorBufV2(x->order - 1, dimSize, x->dataType, x->denseRatio, x->devID, mem);
xiaotong committed
59

60 61
        _ReduceMax(x, max, leadDim);
        _ReduceSum(x, sum, leadDim, max, 1.0F, true);
xiaotong committed
62 63 64

        if(x->devID >= 0){
#ifdef USE_CUDA
65
            _CudaSoftmaxSumMax(x, y, leadDim, sum, max);
xiaotong committed
66 67 68 69 70 71 72
#else
            ShowNTErrors("Please specify USE_CUDA and recompile the code!");
#endif
        }
        else{
            CheckNTErrors((x->dataType == DEFAULT_DTYPE), "TODO!");

73
            int dimensionSize = y->dimSize[leadDim];
xiaotong committed
74 75 76 77
            int stride = 1;
            int blockSize = 1;
            int blockNum = 1;

78 79
            for(int i = leadDim + 1; i < y->order; i++)
                stride *= y->dimSize[i];
xiaotong committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
            blockSize = stride * dimensionSize;
            blockNum = y->unitNum / blockSize;

            for(int k = 0; k < blockNum; k++){
                int m = stride;
                int n = dimensionSize;
                int blockOffset = k * blockSize;
                int blockOffsetMax = k * blockSize / dimensionSize;

                DTYPE * ip = (DTYPE*)x->data + blockOffset;
                DTYPE * op = (DTYPE*)y->data + blockOffset;
                DTYPE * mp = (DTYPE*)max->data + blockOffsetMax;
                DTYPE * sp = (DTYPE*)sum->data + blockOffsetMax;

                for(int j = 0; j < m; j++){
                    DTYPE sumValue = sp[j];
                    if(sumValue == 0){
                        for(int i = 0; i < n; i++)
                            op[i * m + j] = 0;
                    }
                    else{
                        for(int i = 0; i < n; i++){
                            DTYPE r = (DTYPE)exp(ip[i * m + j] - mp[j])/sp[j];
103 104 105 106
                            if (r > (DTYPE)1.0F)
                                r = (DTYPE)1.0F;
                            else if (r < 0)
                                r = 0;
xiaotong committed
107 108 109 110 111 112 113
                            op[i * m + j] = r;
                        }
                    }
                }
            }
        }

114 115 116
        DelTensorBuf(sum);
        DelTensorBuf(max);

xiaotong committed
117 118 119 120 121 122 123 124
        delete[] dimSize;
    }
    else
        ShowNTErrors("TODO!");
    
}

/*
xiaotong committed
125
softmax y = e^x / \sum_{i} e^{x_i} (return an XTensor structure) 
126 127 128 129 130 131 132 133
make a new tensor to keep the result and return it

>> x - input vector
>> leadDim - leading dimension (along which we perform reduction)
<< return - y
*/
XTensor Softmax(const XTensor &x, int leadDim)
{
134 135 136 137
    int ld = leadDim;
    if (ld < 0)
        ld = x.order - 1;

138
    XTensor y(&x);
139
    y.SetTMPFlag();
140 141

    /* call _Softmax function */
142
    _Softmax(&x, &y, ld);
143 144

    /* tensor connection */
145 146 147 148
    if (x.enableGrad) {
        XLink::MakeLink(&x, NULL, &y, FUNC_SOFTMAX);
        XLink::AddParamToHeadInt(&y, ld);
    }
149 150 151 152

    return y;
}

153
void Softmax(const XTensor &x, XTensor &y, int leadDim)
154 155 156 157 158
{
    int ld = leadDim;
    if (ld < 0)
        ld = x.order - 1;

159 160
    if (!y.isInit || !IsSameShaped(y, x)) {
        InitTensorV2(&y, &x);
161 162 163 164 165
    }

    /* call _Softmax function */
    _Softmax(&x, &y, ld);

166
    if (x.enableGrad) {
167 168 169 170 171 172
        /* tensor connection */
        XLink::MakeLink(&x, NULL, &y, FUNC_SOFTMAX);
        XLink::AddParamToHeadInt(&y, ld);
    }
}

173
/*
xiaotong committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
backward computation for dense tensors

dE/dx = dE/dy * dy/dx

    softmax: y_i = e^{x_i} / \sum_{k} e^{x_k}

       dy_i/dx_j = y_i * (\delta(i,j) - y_j)

for cross-entropy error function,

         dE/dy_i = -gold_i / y_i
then
         dE/dx_j = -gold_j + y_j

See more details in LogSoftmaxBackward(...)

>> gold - gold standard to measure error (or loss)
>> y - output of the function
>> x - input of the function
>> dedy - dE/dy
>> dedx - dE/dx
>> lossName - type of loss function, e.g., cross entropy
>> leadDim - leading dimension (along which we perform reduction)
*/
198
void _SoftmaxBackward(XTensor * gold, XTensor * y, XTensor * x, 
199 200
                      XTensor * dedy, XTensor * dedx, 
                      XTensor * padding, int leadDim,
201
                      LOSS_FUNCTION_NAME lossName)
xiaotong committed
202
{
203 204 205 206 207
    CheckNTErrors(dedx->isSparse == false, "The gradient tensor must be dense!");
    CheckNTErrors(gold != NULL || lossName == NOLOSS, "Gold standard is required for computing loss!");

    if(leadDim < 0)
        leadDim = y->order - 1;
xiaotong committed
208 209 210

#ifdef USE_CUDA
    if(y->devID >= 0){
211
        _CudaSoftmaxBackward(gold, y, x, dedy, dedx, padding, leadDim, lossName);
xiaotong committed
212 213 214 215
        return;
    }
#endif

216
    int dimensionSize = y->dimSize[leadDim];
xiaotong committed
217 218 219
    int stride = 1;
    int blockSize = 1;
    int blockNum = 1;
220 221
    for(int i = leadDim + 1; i < y->order; i++)
        stride *= y->dimSize[i];
xiaotong committed
222 223 224 225 226 227 228 229
    blockSize = stride * dimensionSize;
    blockNum = y->unitNum / blockSize;

    if(x->dataType == DEFAULT_DTYPE && y->dataType == DEFAULT_DTYPE)
    {
        DTYPE * gp = gold != NULL ? (DTYPE*)gold->data : NULL;
        DTYPE * op = (DTYPE*)y->data;
        DTYPE * sp = (DTYPE*)dedx->data;
xiaotong committed
230
        DTYPE * yp = NULL;
xiaotong committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

        if(lossName == CROSSENTROPY){
            if(gold->isSparse){
                CheckNTErrors((gold->order == 2), "TODO!");
                int size = dimensionSize * stride;

                /* dE/dx_j = y_j */
                for(int j = 0; j < size; j++){
                    *(sp+j) = *(op+j);
                }

                /* for j \in gold (sparse), dE/dx_j += -gold_j */
                int num = gold->GetNonzeroSize();
                for(int i = 0; i < num; i++){
                    int key = gold->GetKeyInSparse(i);
                    DTYPE value = gold->GetInSparse(i);
                    int offset = key;
                    if(key >= 0 && key < size)
                        *(sp+offset) += -value;
                }
            }
            else{
253
                CheckNTErrors((_IsSameShaped(gold, y)), "The tensors must be of the same size!");
xiaotong committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
                for(int k = 0; k < blockNum; k++){
                    gp = (DTYPE*)gold->data + k * blockSize;
                    op = (DTYPE*)y->data + k * blockSize;
                    sp = (DTYPE*)dedx->data + k * blockSize;
                    int size = stride * dimensionSize;

                    /* dE/dx_j = -gold_j + y_j */
                    for(int j = 0; j < size; j++){
                        *(sp+j) = -(*(gp+j)) + *(op+j);
                    }
                }
            }
        }
        else if(lossName == SQUAREDERROR){
            /* 
            dE/dx_j = -gold_j - y_j
            it is actually the same as that in cross entropy.
            */
            if(gold->isSparse){
                CheckNTErrors((gold->order == 2), "TODO!");
                int size = dimensionSize * stride;

                /* dE/dx_j = y_j */
                for(int j = 0; j < size; j++){
                    *(sp+j) = *(op+j);
                }

                /* for j \in gold (sparse), dE/dx_j += -gold_j */
                int num = gold->GetNonzeroSize();
                for(int i = 0; i < num; i++){
                    int key = gold->GetKeyInSparse(i);
                    DTYPE value = gold->GetInSparse(i);
                    int offset = key;
                    if(key >= 0 && key < size)
                        *(sp+offset) += -value;
                }
            }
            else{
292
                CheckNTErrors((_IsSameShaped(gold, y)), "The tensors must be of the same size!");
xiaotong committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
                for(int k = 0; k < blockNum; k++){
                    gp = (DTYPE*)gold->data + k * blockSize;
                    op = (DTYPE*)y->data + k * blockSize;
                    sp = (DTYPE*)dedx->data + k * blockSize;
                    int size = stride * dimensionSize;

                    /* dE/dx_j = -gold_j + y_j */
                    for(int j = 0; j < size; j++){
                        *(sp+j) = -(*(gp+j)) + *(op+j);
                    }
                }
            }
        }
        else if(lossName == NOLOSS){
            /* 
            for softmax: 
            y_i = e^{x_i} / \sum_{k} e^{x_k}
            we have
            dy_i/dx_j = y_i * (\delta(i,j) - y_j)
            Then
            dE/dx_j = \sum_i dE/dy_i * y_i * (\delta(i,j) - y_j) 
                    = dE/dy_j * y_j - y_j * \beta
                    = y_j * (dE/dy_j - \beta)
            where
            \beta = \sum_i (dE/dy_i * y_i) 
            */

320 321 322 323
            for(int m = 0; m < blockNum; m++){
                yp = (DTYPE*)dedy->data + m * blockSize;
                op = (DTYPE*)y->data + m * blockSize;
                sp = (DTYPE*)dedx->data + m * blockSize;
xiaotong committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
                
                int nCols = stride;
                for(int k = 0; k < stride; k++){
                    /* \beta = \sum_i (dE/dy_i * y_i) */
                    DTYPE beta = 0;
                    for(int i = 0; i < dimensionSize; i++)
                        beta += yp[i * nCols + k] * op[i * nCols + k];

                    /* dE/ds_j = y_j * (dE/dy_j - \beta) */
                    for(int j = 0; j < dimensionSize; j++)
                        sp[j * nCols + k] = op[j * nCols + k] * (yp[j * nCols + k] - beta);
                }
            }
        }
        else
            ShowNTErrors("TODO!");
    }
    else
        ShowNTErrors("TODO!");
}

} // namespace nts(NiuTrans.Tensor)