Loss.cpp 18.3 KB
Newer Older
xiaotong committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* 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.
 */

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

#include <math.h>
#include "Loss.h"
24
#include "Loss.cuh"
25
#include "../core/getandset/SetData.h"
xiaotong committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

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

/*
loss function to measure the "number" of errors
*/

/* 
compute the loss 
>> gold - gold standard
>> output - model prediction
>> LFName - name of loss function
>> isLogOutput - is the output in log scale?
>> leadDim - the leading dimension for the output
>> gBeg - where to start in the gold standard (along the leading dimension)
>> gLen - segment length from gBeg (along the leading dimension)
>> oBeg - where to start in the model output (along the leading dimension)
<< return - error in model prediction with respect to gold standard
*/
45
DTYPE _LossCompute(XTensor * gold, XTensor * output, LOSS_FUNCTION_NAME LFName,
xiaotong committed
46 47 48
                  bool isLogOutput, int leadDim, int gBeg, int gLen, int oBeg)
{
    DTYPE error = 0.0F;
49 50
    if (output->devID < 0) {
        CheckNTErrors((gLen >= 0 && gLen <= output->unitNum), "Illegal input length!");
51
        CheckNTErrors((XTensor::IsSameShaped(gold, output)), "The input tensors must be of the same size!");
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        CheckNTErrors((gold->dimSizeRDI[0] == 1 && output->dimSizeRDI[0] == 1), "TODO!");
        CheckNTErrors((gold->order > leadDim && leadDim >= 0), "Illegal leading dimension!");
        CheckNTErrors((gold->dataType == DEFAULT_DTYPE && output->dataType == DEFAULT_DTYPE),
                             "TODO!");

        int leadDimRDI = output->order - leadDim - 1;
        int dimensionSize = output->dimSizeRDI[leadDimRDI];
        int stride = 1;
        int blockSize = 1;
        int blockNum = 1;

        for(int i = 0; i < leadDimRDI; i++)
            stride *= output->dimSizeRDI[i];
        blockSize = stride * dimensionSize;
        blockNum = output->unitNum / blockSize;

        if(isLogOutput)
69
            return _LossComputeForLogScale(gold, output, LFName, leadDim, gBeg, gLen, oBeg);
70 71 72 73 74 75 76 77 78 79 80 81 82 83

        DTYPE * gp = (DTYPE*)gold->data;
        DTYPE * op = (DTYPE*)output->data;

        /* 
        squared error 
        loss = sum_{i} 0.5*(gold_i - output_i)^2
        where gold_i is the gold standard and output_i is the model prediction
        */
        if(LFName == SQUAREDERROR){
            if(gold->isSparse){
                CheckNTErrors((gBeg == 0 && gLen == dimensionSize), "TODO!");
                for(int i = 0; i < blockSize; i++){
                    DTYPE diff = 0 - *(op + oBeg + i);
xiaotong committed
84 85
                    error += (DTYPE)0.5 * diff * diff;
                }
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
                int num = gold->GetNonzeroSize();
                for(int i = 0; i < num; i++){
                    int key = gold->GetKeyInSparse(i);
                    DTYPE value = gold->GetInSparse(i);
                    int offset = key - gBeg;
                    DTYPE diff = value - *(op + oBeg + offset);
                    error += (DTYPE)0.5 * diff * diff;
                    DTYPE diff2 = 0 - *(op + oBeg + offset);
                    error -= (DTYPE)0.5 * diff2 * diff2;
                }
            }
            else{
                for(int k = 0; k < blockNum; k++){
                    int bg = k * blockSize + gBeg * stride;
                    int og = k * blockSize + oBeg * stride;
                    int size = stride * gLen;
                    for(int i = 0; i < size; i++){
                        DTYPE diff = *(gp + bg + i) - *(op + og + i);
                        error += (DTYPE)0.5 * diff * diff;
                    }
                }
xiaotong committed
107 108 109
            }
        }

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        /* 
        cross entropy
        loss = sum_{i} (-gold_i * log(output_i))
        where gold and output are distributions 
        */
        if(LFName == CROSSENTROPY){
            if(gold->isSparse){
                CheckNTErrors((gBeg == 0 && gLen == dimensionSize), "TODO!");
                int num = gold->GetNonzeroSize();
                for(int i = 0; i < num; i++){
                    int key = gold->GetKeyInSparse(i);
                    DTYPE value = gold->GetInSparse(i);
                    int offset = key - gBeg;
                    error += -value * (DTYPE)log((*(op + oBeg + offset)));
                }
xiaotong committed
125
            }
126 127 128 129 130 131 132 133
            else{
                for(int k = 0; k < blockNum; k++){
                    int bg = k * blockSize + gBeg * stride;
                    int og = k * blockSize + oBeg * stride;
                    int size = stride * gLen;
                    for(int i = 0; i < size; i++){
                        error += -(*(gp + bg + i)) * (DTYPE)log(*(op + og + i));
                    }
xiaotong committed
134 135 136
                }
            }
        }
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        
        /*
        one hot error
        loss = sum_{i} e_i 
        where e_i = 0.5*(t_i - y_i)^2 if t_i = 1, 
              e_i = 0 otherwise
        */
        if(LFName == ONEHOTERROR){
            if(gold->isSparse){
                CheckNTErrors((gBeg == 0 && gLen == dimensionSize), "TODO!");
                for(int i = 0; i < blockSize; i++){
                    DTYPE diff = 0 - *(op + oBeg + i);
                    error += (DTYPE)0.5 * diff * diff;
                }
                int num = gold->GetNonzeroSize();
                for(int i = 0; i < num; i++){
                    int key = gold->GetKeyInSparse(i);
                    DTYPE value = gold->GetInSparse(i);
                    int offset = key - gBeg;
xiaotong committed
156

157
                    if(value >= 1.0F)
xiaotong committed
158
                        continue;
159 160 161 162

                    DTYPE diff0 = 0 - *(op + oBeg + offset);
                    error += (DTYPE)0.5 * diff0 * diff0;
                    DTYPE diff = value - *(op + oBeg + offset);
xiaotong committed
163
                    error += (DTYPE)0.5 * diff * diff;
164 165 166 167 168 169 170 171 172 173 174 175 176
                    DTYPE diff2 = 0 - *(op + oBeg + offset);
                    error -= (DTYPE)0.5 * diff2 * diff2;
                }
            }
            else{
                for(int k = 0; k < blockNum; k++){
                    int size = stride * gLen;
                    for(int i = 0; i < size; i++){
                        if(*(gp + gBeg + i) < 1.0F)
                            continue;
                        DTYPE diff = *(gp + gBeg + i) - *(op + oBeg + i);
                        error += (DTYPE)0.5 * diff * diff;
                    }
xiaotong committed
177 178 179 180
                }
            }
        }
    }
181
    else {
xiaotong committed
182
#ifdef USE_CUDA
183
        error = _CudaLossCompute(gold, output, LFName, isLogOutput, leadDim, gBeg, gLen, oBeg);
xiaotong committed
184 185 186
#else
        ShowNTErrors("Please specify USE_CUDA and recompile the code!");
#endif
187
    }
xiaotong committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

    return error;
}

/* 
the log version of loss computation

>> gold - gold standard
>> output - model prediction
>> LFName - name of loss function
>> leadDim - the leading dimension for the output
>> gBeg - where to start in the gold standard (along the leading dimension)
>> gLen - segment length from gBeg (along the leading dimension)
>> oBeg - where to start in the model output (along the leading dimension)
<< return - error in model prediction with respect to gold standard
*/
204
DTYPE _LossComputeForLogScale(XTensor * gold, XTensor * output, 
xiaotong committed
205 206 207
                             LOSS_FUNCTION_NAME LFName,
                             int leadDim, int gBeg, int gLen, int oBeg)
{
208
    CheckNTErrors(gLen >= 0 && gLen <= output->unitNum, "Illegal input length!");
209
    CheckNTErrors(XTensor::IsSameShaped(gold, output), "The input tensors must be of the same size!");
210 211 212
    CheckNTErrors(gold->dimSizeRDI[0] == 1 && output->dimSizeRDI[0] == 1, "TODO!");
    CheckNTErrors(gold->order > leadDim && leadDim >= 0, "Illegal leading dimension!");
    CheckNTErrors(gold->dataType == DEFAULT_DTYPE && output->dataType == DEFAULT_DTYPE, "TODO!");
xiaotong committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 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 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 292 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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

    int leadDimRDI = output->order - leadDim - 1;
    int dimensionSize = output->dimSizeRDI[leadDimRDI];
    int stride = 1;
    int blockSize = 1;
    int blockNum = 1;

    for(int i = 0; i < leadDimRDI; i++)
        stride *= output->dimSizeRDI[i];
    blockSize = stride * dimensionSize;
    blockNum = output->unitNum / blockSize;

    DTYPE * gp = (DTYPE*)gold->data;
    DTYPE * op = (DTYPE*)output->data;
    DTYPE error = 0.0F;

    /* 
    squared error 
    loss = sum_{i} 0.5*(gold_i - exp(output_i))^2
    where gold_i is the gold standard and output_i is the model prediction
    */
    if(LFName == SQUAREDERROR){
        if(gold->isSparse){
            CheckNTErrors((gBeg == 0 && gLen == dimensionSize), "TODO!");
            for(int i = 0; i < gLen; i++){
                DTYPE diff = 0 - (DTYPE)exp(*(op + oBeg + i));
                error += (DTYPE)0.5 * diff * diff;
            }
            int num = gold->GetNonzeroSize();
            for(int i = 0; i < num; i++){
                int key = gold->GetKeyInSparse(i);
                DTYPE value = gold->GetInSparse(i);
                int offset = key - gBeg;
                DTYPE diff = value - (DTYPE)exp(*(op + oBeg + offset));
                error += (DTYPE)0.5 * diff * diff;
                DTYPE diff2 = 0 - (DTYPE)exp(*(op + oBeg + offset));
                error -= (DTYPE)0.5 * diff2 * diff2;
            }
        }
        else{
            for(int k = 0; k < blockNum; k++){
                int bg = k * blockSize + gBeg * stride;
                int og = k * blockSize + oBeg * stride;
                int size = stride * gLen;
                for(int i = 0; i < size; i++){
                    DTYPE diff = *(gp + bg + i) - (DTYPE)exp(*(op + og + i));
                    error += (DTYPE)0.5 * diff * diff;
                }
            }
        }
    }

    /* 
    cross entropy
    loss = sum_{i} (-t_i * y_i), where t and y are distributions 
    */
    if(LFName == CROSSENTROPY){
        if(gold->isSparse){
            CheckNTErrors((gBeg == 0 && gLen == dimensionSize), "TODO!");
            int num = gold->GetNonzeroSize();
            for(int i = 0; i < num; i++){
                int key = gold->GetKeyInSparse(i);
                DTYPE value = gold->GetInSparse(i);
                int offset = key - gBeg;
                error += -value * (*(op + oBeg + offset));
            }
        }
        else{
            for(int k = 0; k < blockNum; k++){
                int bg = k * blockSize + gBeg * stride;
                int og = k * blockSize + oBeg * stride;
                int size = stride * gLen;
                for(int i = 0; i < size; i++){
                    error += -(*(gp + bg + i)) * (*(op + og + i));
                }
            }
        }
    }

    /*
    one hot error
    loss = sum_{i} e_i 
    where e_i = 0.5*(t_i - exp(y_i))^2 if t_i = 1, 
          e_i = 0 otherwise
    */
    if(LFName == ONEHOTERROR){
        if(gold->isSparse){
            CheckNTErrors((gBeg == 0 && gLen == dimensionSize), "TODO!");
            int num = gold->GetNonzeroSize();
            for(int i = 0; i < num; i++){
                int key = gold->GetKeyInSparse(i);
                DTYPE value = gold->GetInSparse(i);
                int offset = key - gBeg;
                if(value >= 1.0F)
                    continue;

                DTYPE diff0 = 0 - (DTYPE)exp(*(op + oBeg + offset));
                error += (DTYPE)0.5 * diff0 * diff0;
                DTYPE diff = value - (DTYPE)exp(*(op + oBeg + offset));
                error += (DTYPE)0.5 * diff * diff;
                DTYPE diff2 = 0 - (DTYPE)exp(*(op + oBeg + offset));
                error -= (DTYPE)0.5 * diff2 * diff2;
            }
        }
        else{
            for(int k = 0; k < blockNum; k++){
                int bg = k * blockSize + gBeg * stride;
                int og = k * blockSize + oBeg * stride;
                int size = stride * gLen;
                for(int i = 0; i < size; i++){
                    if(*(gp + gBeg + i) >= 1.0F)
                        continue;

                    DTYPE diff = *(gp + bg + i) - (DTYPE)exp(*(op + og + i));
                    error += (DTYPE)0.5 * diff * diff;
                }
            }
        }
    }

    return error;
}

/* 
backward compuation for a single element 
dE/dy
where E is the error(loss) function that measure the errors in y
with respect to gold standard, and y this the model output
>> t - gold standard
>> y - model output
>> LFName - name of loss function
<< return dE/dy
*/
346
DTYPE _LossBackwardPoint(DTYPE t, DTYPE y, LOSS_FUNCTION_NAME LFName)
xiaotong committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
{
    /* 
    squared error 
    loss = sum_{i} 0.5*(t_i - y_i)^2, where t_i is the gold standard and y_i is the model output
    dloss/dy_i = y_i - t_i
    */
    if(LFName == SQUAREDERROR){
        return y - t;
    }

    /* 
    cross entropy
    loss = sum_{i} (-t_i * log(y_i)), where t and y are distributions 
    dloss/dy_i = -t_i / y_i
    */
    if(LFName == CROSSENTROPY){
        return -t/y;
    }

    return 1;
}

/* 
backward compuation for (dense) vectors 
dE/dy
where E is the error(loss) function that measure the errors in y
with respect to gold standard, and y this the model output
>> dedy - dE/dy (for return)
>> t - gold standard (in vector/matrix)
>> y - model output (in vector/matrix)
>> LFName - name of loss function
>> leadDim - the leading dimension for the output
>> tBeg - where to start in the gold standard (along the leading dimension)
>> tLen - segment length from tBeg (along the leading dimension)
>> yBeg - where to start in the model output (along the leading dimension)
*/
383
void _LossBackward(XTensor * dedy, XTensor * t, XTensor * y, 
xiaotong committed
384 385 386
                  LOSS_FUNCTION_NAME LFName, 
                  int leadDim, int tBeg, int tLen, int yBeg)
{
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    if(t == NULL){
        if(dedy->dataType == X_FLOAT)
            _SetDataFixedFloat(dedy, 1.0F);
        else if(dedy->dataType == X_DOUBLE)
            _SetDataFixedDouble(dedy, 1.0);
        else if(dedy->dataType == X_INT)
            _SetDataFixedInt(dedy, 1);
        else{
            ShowNTErrors("TODO");
        }
        return;
    }

    if(t->order < 0)
        return;
    
403
    if (y->devID < 0) {
404
        CheckNTErrors(tLen <= y->unitNum, "Illegal input length!");
405 406 407 408
        CheckNTErrors(XTensor::IsSameShaped(t, y)&& XTensor::IsSameShaped(dedy, y),
                     "The input tensors must be of the same size!");
        CheckNTErrors((dedy->devID == t->devID) && (dedy->devID == y->devID),
                     "Tensor must be on the same device!");
409 410
        CheckNTErrors(t->order > leadDim, "Illegal leading dimension!");
        CheckNTErrors(t->dataType == DEFAULT_DTYPE && y->dataType == DEFAULT_DTYPE, "TODO!");
411 412 413 414 415 416 417 418

        int leadDimRDI = leadDim >= 0 ? y->order - leadDim - 1 : -1;
        if(leadDimRDI < 0){
            leadDimRDI = y->order - 1;
            tBeg = 0;
            yBeg = 0;
            tLen = y->dimSizeRDI[leadDimRDI];
        }
xiaotong committed
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        int dimensionSize = y->dimSizeRDI[leadDimRDI];
        int stride = 1;
        int blockSize = 1;
        int blockNum = 1;

        for(int i = 0; i < leadDimRDI; i++)
            stride *= y->dimSizeRDI[i];
        blockSize = stride * dimensionSize;
        blockNum = y->unitNum / blockSize;

        DTYPE * tp = (DTYPE*)t->data;
        DTYPE * yp = (DTYPE*)y->data;
        DTYPE * dedyp = (DTYPE*)dedy->data;

        CheckNTErrors((t->dataType == DEFAULT_DTYPE && 
                       y->dataType == DEFAULT_DTYPE && 
                       dedy->dataType == DEFAULT_DTYPE),
                       "Input vectors are not in default type!");

        /* 
        squared error 
        loss = sum_{i} 0.5*(t_i - y_i)^2, where t_i is the gold standard and y_i is the model output
        dloss/dy_i = y_i - t_i
        */
        if(LFName == SQUAREDERROR){
            if(t->isSparse){
                CheckNTErrors((tBeg == 0 && tLen == dimensionSize), "TODO!");
                int num = t->GetNonzeroSize();
                for(int i = 0; i < num; i++){
                    int key = t->GetKeyInSparse(i);
                    DTYPE value = t->GetInSparse(i);
                    if(key >= tBeg && key < tBeg + tLen)
                        *(dedyp + yBeg + key - tBeg) = -value;
                }
                for(int i = 0; i < tLen; i++){
                    *(dedyp + yBeg + i) += *(yp + yBeg + i);
                }
xiaotong committed
457
            }
458 459 460 461 462 463 464 465
            else{
                for(int k = 0; k < blockNum; k++){
                    int bg = k * blockSize + tBeg * stride;
                    int yg = k * blockSize + yBeg * stride;
                    int size = stride * tLen;
                    for(int i = 0; i < size; i++){
                        *(dedyp + bg + i) = *(yp + yBeg + i) - *(tp + yg + i);
                    }
xiaotong committed
466 467 468 469
                }
            }
        }

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        /* 
        cross entropy
        loss = sum_{i} (-t_i * log(y_i)), where t and y are distributions 
        dloss/dy_i = -t_i / y_i
        */
        if(LFName == CROSSENTROPY){
            if(t->isSparse){
                memset(dedyp + yBeg, 0, sizeof(DTYPE) * tLen);
                int num = t->GetNonzeroSize();
                for(int i = 0; i < num; i++){
                    int key = t->GetKeyInSparse(i);
                    DTYPE value = t->GetInSparse(i);
                    if(key >= tBeg && key < tBeg + tLen)
                        *(dedyp + yBeg + key - tBeg) = -value/(DTYPE)*(yp + yBeg + key - tBeg);
                }
xiaotong committed
485
            }
486 487 488 489 490 491 492 493 494
            else{
                for (int i = 0; i < blockNum; i++) {
                    for (int j = 0; j < stride; j++) {
                        for (int k = 0; k < tLen; k++) {
                            *(dedyp + i * stride * dimensionSize + j + stride * (yBeg + k)) = -(DTYPE)*(tp + i * stride * dimensionSize
                                + j + stride * (tBeg + k)) / (DTYPE)*(yp +  i * stride * dimensionSize + j + stride * (yBeg + k));
                        }
                    }
                }
xiaotong committed
495 496 497
            }
        }
    }
498
    else {
xiaotong committed
499
#ifdef USE_CUDA
500
        _CudaLossBackward(dedy, t, y, LFName, leadDim, tBeg, tLen, yBeg);
xiaotong committed
501 502 503
#else
        ShowNTErrors("Please specify USE_CUDA and recompile the code!");
#endif
504
    }
xiaotong committed
505 506 507
}

} // namespace nts(NiuTrans.Tensor)