XTensor.cpp 53.4 KB
Newer Older
xiaotong committed
1
/* NiuTrans.Tensor - an open-source tensor library
liyinqiao committed
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 22 23 24 25 26 27 28 29 30 31 32 33 34
 * 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.
 */

/*
 * 
 * implementation of tensors used in this work. It it is the basis of XMatrix 
 * and XVector
 *
 *
 * $Created by: XIAO Tong (xiaotong@mail.neu.edu.cn) 2017-07-31
 * $Update by: LI Yinqiao (li.yin.qiao.2012@hotmail.com) 2017-11-18 bug fixes
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <time.h>
#include "XTensor.h"
liyinqiao committed
35
#include "XCall.h"
xiaotong committed
36 37 38 39 40 41
#include "XGlobal.h"
#include "XUtility.h"
#include "XDevice.h"
#include "XMem.h"
#include "XHeap.h"
#include "XBLAS.h"
liyinqiao committed
42
#include "XName.h"
43
#include "core/shape/MergeBlockLists.h"
44 45 46
#include "core/movement/CopyValues.h"
#include "core/arithmetic/Sum.h"
#include "core/arithmetic/Multiply.h"
47 48
#include "core/arithmetic/Sub.h"
#include "core/arithmetic/Div.h"
49
#include "core/math/ScaleAndShift.h"
liyinqiao committed
50 51 52
#include "core/getandset/SetData.h"
#include "function/Identity.h"
#include "core/CHeader.h"
xiaotong committed
53 54 55 56 57 58 59 60

#ifdef USE_CUDA

// the CUDA stuff
#include <cuda_runtime.h>
#include <cublas_v2.h>
#include <cuda.h>
#include <curand.h>
61 62
#include "core/utilities/FlushToMem.cuh"
#include "core/utilities/SetAscendingOrder.cuh"
xiaotong committed
63 64 65 66 67 68

#endif

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

69 70
int tensorIDGlobal = 0;
MUTEX_HANDLE tensorMutex;
71
XTensor NULLTensor;
72 73 74 75 76 77 78 79

/* generate a tensor id */
int MakeTensorID()
{
    if(tensorIDGlobal == 0)
        MUTEX_INIT(tensorMutex);

    MUTEX_LOCK(tensorMutex);
liyinqiao committed
80
    int id = tensorIDGlobal++;
81 82 83 84 85
    MUTEX_UNLOCK(tensorMutex);

    return id;
}

liyinqiao committed
86
/* constructor */
xiaotong committed
87 88
XTensor::XTensor()
{
89
    Init();
xiaotong committed
90

91
    id = MakeTensorID();
liyinqiao committed
92
    reserved = 0;
xiaotong committed
93 94 95
}

/* constructor */
liyinqiao committed
96
XTensor::XTensor(const XTensor* reference)
xiaotong committed
97
{
98
    Init();
99
    id = MakeTensorID();
xiaotong committed
100

liyinqiao committed
101
    InitTensorV2(this, reference);
xiaotong committed
102 103 104 105 106
}

/* 
constructor 
>> myOrder - order of the tensor
107
>> myDevID - device id
xiaotong committed
108 109
>> myMem - memory pool used to allocating the data array
*/
liyinqiao committed
110
XTensor::XTensor(const int myOrder, int myDevID, XMem* myMem)
xiaotong committed
111
{
liyinqiao committed
112
    CheckNTErrors((myOrder >= 0), "Illegal tensor order!");
xiaotong committed
113

114 115
    Init();

116
    id = MakeTensorID();
xiaotong committed
117 118 119 120 121 122 123 124
    order = myOrder;
    mem = myMem;
    devID = myMem == NULL ? myDevID : myMem->devID;
}

/* 
constructor 
>> myOrder - order of the tensor
liyinqiao committed
125
>> myDimSize - size of each dimension
xiaotong committed
126
>> myDataType - unit size (e.g., int, float, and double)
liyinqiao committed
127
>> myDenseRatio - how often an element has a non-zero value
128
>> myDevID - device id
xiaotong committed
129 130 131
>> myMem - memory pool used to allocating the data array
*/
XTensor::XTensor(const int myOrder, const int * myDimSize, const TENSOR_DATA_TYPE myDataType,
132
                 const float myDenseRatio, int myDevID, XMem * myMem)
xiaotong committed
133
{
134 135
    Init();

136
    id = MakeTensorID();
xiaotong committed
137 138
    order = myOrder;
    mem = myMem;
139
    devID = myMem != NULL ? myMem->devID : myDevID;
xiaotong committed
140

141 142
    if(order >= 0)
        Resize(myOrder, myDimSize, myDataType, myDenseRatio);
xiaotong committed
143 144
}

145
/* copy constructor */
liyinqiao committed
146
XTensor::XTensor(const XTensor& reference)
147
{
148
    Init();
149 150 151 152 153 154 155 156 157
    id = MakeTensorID();
    ShallowCopy(reference);
    data = NULL;
    dataHost = NULL;
    
    if(reference.isTmp){
        devID = reference.devID;
        mem = reference.mem;
        data = reference.data;
liyinqiao committed
158 159 160 161
        reserved = reference.reserved;
        const_cast<XTensor&>(reference).reserved = 0;
        signature = reference.signature;
        const_cast<XTensor&>(reference).data = NULL;
162 163 164 165
    }
    else{
        devID = reference.devID;
        mem = reference.mem;
liyinqiao committed
166
        InitTensorV2(this, &reference);
167
        _CopyValues(&reference, this);
168 169
    }

liyinqiao committed
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 195 196 197 198
    if (reference.enableGrad) {
        if (reference.isTmp)
            XLink::Replace(&reference, this);
        else {
            CheckNTErrors(outgo.tailNum == 0, "The node has outgoing edge to other nodes!");
            XLink::CopyIncoming(&reference, this);
        }
    }

    isInit = true;
    isTmp = reference.isTmp;
}

/* copy constructor (with right value reference) */
XTensor::XTensor(const XTensor&& reference)
{
    Init();
    id = MakeTensorID();
    ShallowCopy(reference);
    data = NULL;
    dataHost = NULL;
    
    devID = reference.devID;
    mem = reference.mem;
    data = reference.data;
    signature = reference.signature;
    const_cast<XTensor&>(reference).data = NULL;

    if (reference.enableGrad) {
199 200 201
        XLink::Replace(&reference, this);
    }

202
    isInit = true;
liyinqiao committed
203 204 205
    isTmp = reference.isTmp;
    reserved = reference.reserved;
    const_cast<XTensor&>(reference).reserved = 0;
206 207
}

xiaotong committed
208 209 210
/* de-constructor */
XTensor::~XTensor()
{
211 212 213 214
    /* We make a hard copy of the tensor to keep
       the connectivity of the graph. To kill memory
       leak, we release the data of the new tensor
       when its parent is deleted (see ClearIncoming). */
215
    if(outgo.tailNum > 0){
216 217 218
        int dims[MAX_TENSOR_DIM_NUM];
        memcpy(dims, dimSize, order * sizeof(int));
        dims[0] = -dims[0];
liyinqiao committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

        XTensor* newTensor = new XTensor(order, dims, dataType, denseRatio, devID, mem);
        newTensor->SetTMPFlag();
        if (reserved == -1) {
            newTensor->data = NULL;
        }
        else {
            newTensor->data = data;
            data = NULL;
        }

        if (enableGrad)
            XLink::Replace(this, newTensor);
    }

    if (enableGrad) {
        XLink::ClearOutgoing(this);
        XLink::ClearIncoming(this);
237
    }
xiaotong committed
238
    DestroyData();
239 240 241

    if(grad != NULL)
        delete grad;
242 243
}

liyinqiao committed
244 245 246 247 248 249
/* set the name of the tensor */
void XTensor::SetName(const char* myName)
{
    strcpy(name, myName);
}

250 251 252
/* initialize member variables */
void XTensor::Init()
{
liyinqiao committed
253
    name[0] = '\0';
254
    id = -1;
liyinqiao committed
255 256
    mem = NULL;
    signature = 0;
xiaotong committed
257 258
    data = NULL;
    dataHost = NULL;
259 260 261 262 263 264 265 266 267 268 269 270 271 272
    devID = -1;
    order = -1;
    memset(dimSize, 0, sizeof(int) * MAX_TENSOR_DIM_NUM);
    dataType = DEFAULT_DTYPE;
    unitSize = sizeof(float);
    unitNum = 0;
    isSparse = false;
    unitNumNonZero = 0;
    denseRatio = 1.0F;
    isShared = false;
    isDefaultDType = true;
    isInGlobalMem = false;
    memset(isAllValued, 0, sizeof(bool) * MAX_TENSOR_DIM_NUM);
    isInit = false;
liyinqiao committed
273
    isTmp = false;
274
    isGrad = false;
liyinqiao committed
275
    isVar = false;
276
    isGradFinished = false;
liyinqiao committed
277
    enableGrad = X_ENABLE_GRAD;
278
    visitMark = 0;
279
    grad = NULL;
xiaotong committed
280 281 282 283 284 285 286 287 288 289
}

/* delete data arrays */
void XTensor::DestroyData()
{
    if(data != NULL && mem == NULL && !isShared)
        XMemFree(devID, data);
    else if(data != NULL && isInGlobalMem)
        FreeData(this, mem);
    else if(data != NULL)
liyinqiao committed
290 291
        mem->Release(data, GetDataSizeInChar(), signature);
    
xiaotong committed
292 293 294 295 296 297 298
    data = NULL;

    if(dataHost != NULL)
        delete[] (char*)dataHost;
    dataHost = NULL;
}

299
/* 
liyinqiao committed
300
shallow copy of the tensor
301 302 303
Note that we do not copy data array here
>> tensor - the source tensor
*/
liyinqiao committed
304
void XTensor::ShallowCopy(const XTensor& tensor)
305
{
liyinqiao committed
306
    strcpy(name, tensor.name);
307
    order = tensor.order;
liyinqiao committed
308
    enableGrad = tensor.enableGrad;
309 310 311 312 313 314
    memcpy(dimSize, tensor.dimSize, sizeof(int) * MAX_TENSOR_DIM_NUM);
    dataType = tensor.dataType;
    unitSize = tensor.unitSize;
    unitNum = tensor.unitNum;
    isSparse = tensor.isSparse;
    unitNumNonZero = tensor.unitNumNonZero;
liyinqiao committed
315
    denseRatio = tensor.denseRatio;
316 317 318 319 320 321
    isShared = tensor.isShared;
    isDefaultDType = tensor.isDefaultDType;
    isInGlobalMem = tensor.isInGlobalMem;
    memcpy(isAllValued, tensor.isAllValued, sizeof(bool) * MAX_TENSOR_DIM_NUM);
}

xiaotong committed
322
/* overloading of the equal-sign */
323
XTensor& XTensor::operator= (const XTensor& tensor)
xiaotong committed
324
{
liyinqiao committed
325
    /* we must make a hard copy of the tensor if it is the input
326 327 328 329 330 331
       of another node. */
    if(outgo.tailNum > 0){
        int dims[MAX_TENSOR_DIM_NUM];
        memcpy(dims, dimSize, order * sizeof(int));
        dims[0] = -dims[0];
        
liyinqiao committed
332 333 334 335 336 337 338
        XTensor* newTensor = new XTensor(order, dims, dataType, denseRatio, devID, mem);
        newTensor->SetTMPFlag();
        
        /* release the data if it won't be used in backward */
        if (reserved == -1) {
            DestroyData();
        }
339 340
        newTensor->data = data;
        newTensor->dataHost = dataHost;
liyinqiao committed
341
        newTensor->signature = tensor.signature;
342
        
liyinqiao committed
343 344 345 346 347
        if (enableGrad) {
            XLink::Replace(this, newTensor);
            XLink::ClearOutgoing(this);
            XLink::ClearIncoming(this);
        }
348 349 350 351 352 353
        newTensor->ShallowCopy(this);

        data = NULL;
        dataHost = NULL;
    }

liyinqiao committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    if(false && !tensor.isTmp){
        /* NOTE: this might lead to additional data copy by Mac LLVM compilers */
        /* we make an identity transformation here */
        
        if (enableGrad) {
            if (outgo.tailNum > 0)
                XLink::ClearOutgoing(this);
            XLink::ClearIncoming(this);
        }
        
        if(!_IsSameShaped(this, &tensor))
            Resize(tensor.order, tensor.dimSize, tensor.dataType, tensor.denseRatio);
        
        _Identity(&tensor, this);
        if (enableGrad) {
            XLink::MakeLink(&tensor, NULL, this, FUNC_IDENTITY);
        }
xiaotong committed
371 372
    }
    else{
liyinqiao committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        /* hard copy of the data array */
        int size = unitNum * unitSize;
        if(isInit && !isSparse && !tensor.isSparse &&
           size == tensor.unitNum * tensor.unitSize &&
           ((devID < 0 && tensor.devID < 0) && devID == tensor.devID) &&
            data != NULL)
        {
            XMemCopy(data, devID, tensor.data, tensor.devID, size);
            if(dataHost != NULL && tensor.dataHost != NULL)
                XMemCopy(dataHost, -1, tensor.dataHost, tensor.devID, size);
        }
        else{
            DestroyData();
            if(!isInit){
                devID = tensor.devID;
                mem = tensor.mem;
            }

            Resize(tensor.order, tensor.dimSize, tensor.dataType, tensor.denseRatio);
            _CopyValues(&tensor, this);
        }

        /* copy member variables */
        ShallowCopy(tensor);

        isInit = true;
        isTmp = false;

        CheckNTErrors(outgo.tailNum == 0, "The node has outgoing edge to other nodes!");

        /* create tensor links for the new tensor */
        if (enableGrad) {
            XLink::Copy(&tensor, this);
        }
    }

    return *this;
}

/* overloading of the equal-sign (with right value reference) */
XTensor& XTensor::operator= (const XTensor&& tensor)
{
    /* we must make a hard copy of the tensor if it is the input
       of another node. */
    if(outgo.tailNum > 0){
        int dims[MAX_TENSOR_DIM_NUM];
        memcpy(dims, dimSize, order * sizeof(int));
        dims[0] = -dims[0];
        
        XTensor* newTensor = new XTensor(order, dims, dataType, denseRatio, devID, mem);
        newTensor->SetTMPFlag();

        /* release the data if it won't be used in backward */
        if (reserved == -1) {
            DestroyData();
        }
        newTensor->data = data;
        newTensor->dataHost = dataHost;
        newTensor->signature = tensor.signature;
        
        if (enableGrad) {
            XLink::Replace(this, newTensor);
            XLink::ClearOutgoing(this);
            XLink::ClearIncoming(this);
xiaotong committed
437
        }
liyinqiao committed
438
        newTensor->ShallowCopy(this);
xiaotong committed
439

liyinqiao committed
440 441
        data = NULL;
        dataHost = NULL;
xiaotong committed
442
    }
liyinqiao committed
443 444
    
    DestroyData();
xiaotong committed
445

446
    ShallowCopy(tensor);
liyinqiao committed
447
    
xiaotong committed
448
    isInit = true;
liyinqiao committed
449 450 451 452 453
    devID = tensor.devID;
    mem = tensor.mem;
    data = tensor.data;
    signature = tensor.signature;
    const_cast<XTensor&>(tensor).data = NULL;
454

liyinqiao committed
455 456 457
    if (enableGrad) {
        XLink::Replace(&tensor, this);
    }
xiaotong committed
458

liyinqiao committed
459 460
    reserved = tensor.reserved;
    const_cast<XTensor&>(tensor).reserved = 0;
xiaotong committed
461 462 463
    return *this;
}

464
/* overloading of the plus-sign */
liyinqiao committed
465
XTensor XTensor::operator+ (const XTensor& tensor) const
466 467 468 469
{
    return Sum(*this, tensor);
}

liyinqiao committed
470 471 472 473 474 475
/* overloading of the plus-sign */
XTensor XTensor::operator+ (const DTYPE shift) const
{
    return ScaleAndShift(*this, 1, shift);
}

476
/* overloading of the multiply-sign */
liyinqiao committed
477
XTensor XTensor::operator* (const XTensor& tensor) const
478 479 480 481
{
    return Multiply(*this, tensor);
}

liyinqiao committed
482 483 484 485 486 487
/* overloading of the multiply-sign */
XTensor XTensor::operator* (const DTYPE scale) const
{
    return ScaleAndShift(*this, scale, 0);
}

488
/* overloading of the minus-sign */
liyinqiao committed
489
XTensor XTensor::operator- (const XTensor& tensor) const
490 491 492 493
{
    return Sub(*this, tensor);
}

liyinqiao committed
494 495 496 497 498 499 500 501 502 503 504 505
/* overloading of the minus-sign */
XTensor XTensor::operator- (const DTYPE shift) const
{
    return ScaleAndShift(*this, 1, -shift);
}

/* overloading of the minus-sign */
XTensor XTensor::operator- () const
{
    return Negate(*this);
}

506
/* overloading of the division-sign */
liyinqiao committed
507
XTensor XTensor::operator/ (const XTensor& tensor) const
508 509 510 511
{
    return Div(*this, tensor);
}

liyinqiao committed
512 513 514 515 516 517
/* overloading of the division-sign */
XTensor XTensor::operator/ (const DTYPE scale) const
{
    return ScaleAndShift(*this, (DTYPE)1.0F / scale, 0);
}

518 519 520 521 522
/* 
linear transformation b = a * \scale + \shift
>> scale - the slope
>> shift - the intercept
*/
liyinqiao committed
523
XTensor XTensor::Lin(DTYPE scale, DTYPE shift) const
524 525 526 527
{
    return Linear(*this, scale, shift);
}

xiaotong committed
528
/* 
liyinqiao committed
529 530 531
relocate the data on the target device 
>> myDevId - target device id
>> myMem - memory pool on the target device
xiaotong committed
532
*/
liyinqiao committed
533 534 535 536 537 538 539 540 541
void XTensor::SetDevice(int myDevId, XMem* myMem)
{
    if(myMem == NULL)
        myMem = GMems.GetMem(myDevId);
    FlushToMem(myMem);
    isInGlobalMem = false;
}

bool XTensor::IsReduceShaped(const XTensor* a, const XTensor* b, int dim)
xiaotong committed
542
{
543 544 545
    if(a == NULL || b == NULL)
        return false;

liyinqiao committed
546
    if ((a->order - 1) != b->order)
xiaotong committed
547 548
        return false;

liyinqiao committed
549 550 551 552 553 554 555 556 557
    for (int i = 0; i < b->order; i++) {
        if (i < dim) {
            if (a->dimSize[i] != b->dimSize[i])
                return false;
        }
        else if (i >= dim) {
            if (a->dimSize[i+1] != b->dimSize[i])
                return false;
        }
xiaotong committed
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    }

    if(a->dataType != b->dataType)
        return false;

    if(a->denseRatio != b->denseRatio)
        return false;

    if(a->isSparse != b->isSparse)
        return false;

    return true;
}

/* 
set the size of each dimension 
>> myDimSize - size of each dimension
*/
liyinqiao committed
576
void XTensor::SetDim(int* myDimSize)
xiaotong committed
577 578 579 580 581 582 583 584 585 586
{
    for (int i = 0; i < order; i++) {
        dimSize[i] = myDimSize[i];
    }
}

/* 
get the size of a given dimension 
>> dim - the given dim we are looking at
*/
liyinqiao committed
587
int XTensor::GetDim(const int dim) const
xiaotong committed
588 589
{
    CheckNTErrors(dim < order, "dimenision is out of range!");
liyinqiao committed
590
    CheckNTErrors(dim >= -order, "dimenision is out of range!");
591 592 593
    
    int d = dim;
    if(dim < 0)
liyinqiao committed
594
        d = order + dim;
xiaotong committed
595

596
    return dimSize[d];
xiaotong committed
597 598 599 600 601
}

/* 
reshape the tensor 
>> myOrder - order of the tensor
liyinqiao committed
602
>> myDimSize - size of each dimension
xiaotong committed
603
*/
liyinqiao committed
604
void XTensor::Reshape(const int myOrder, const int* myDimSize)
xiaotong committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
{
    int dims[MAX_TENSOR_DIM_NUM];
    int num = 1;

    for(int i = 0; i < myOrder; i++){
        num *= myDimSize[i];
        dims[i] = abs(myDimSize[i]);
    }

    CheckNTErrors(abs(num) == unitNum, "Wrong size found when we reshape the tensor!");

    order = myOrder;
    memcpy(dimSize, dims, sizeof(int) * order);
}

620
/* 
liyinqiao committed
621
reshape the tensor into a vector
622 623 624 625 626 627 628 629 630
>> num - number of elements
*/
void XTensor::Reshape(const int num)
{
    int dim = num;
    Reshape(1, &dim);
}

/* 
liyinqiao committed
631
reshape the tensor into a matrix
632 633 634 635 636 637 638 639 640
>> rowNum - number of rows
>> colNum - number of columns
*/
void XTensor::Reshape(const int rowNum, const int colNum)
{
    int dims[2] = {rowNum, colNum};
    Reshape(2, dims);
}

liyinqiao committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
/*
reshape the tensor by merging two consecutive dimensions
>> i - dimension i
>> j - i + 1
*/
void XTensor::ReshapeMerged(const int i, const int j)
{
    if (i < 0)
        return;

    int di = i;
    int dj = j < 0 ? i + 1 : j;

    CheckNTErrors(di < order, "Wrong dimension index!");


    int dims[MAX_TENSOR_DIM_NUM];

    for (int k = 0; k < di; k++)
        dims[k] = dimSize[k];
    dims[di] = dimSize[di] * dimSize[dj];
    for (int k = dj + 1; k < order; k++)
        dims[k - 1] = dimSize[k];

    Reshape(order - 1, dims);
}

/* return a tensor that datatype is same as the special tensor */
XTensor XTensor::TypeAs(const XTensor input)
{
    return ConvertDataType(*this, input.dataType);
}

/* return a tensor that datatype is integer */
XTensor XTensor::Int()
{
    return ConvertDataType(*this, X_INT);
}

/* return a tensor that datatype is float */
XTensor XTensor::Float()
{
    return ConvertDataType(*this, X_FLOAT);
}

/* return a tensor that datatype is float16 */
XTensor XTensor::Float16()
{
    return ConvertDataType(*this, X_FLOAT16);
}

/* return a tensor that datatype is double */
XTensor XTensor::Double()
{
    return ConvertDataType(*this, X_DOUBLE);
}

xiaotong committed
698
/* get the number of items in the data array */
699
int XTensor::GetSize() const
xiaotong committed
700 701 702 703 704 705 706
{
    if(isSparse)
        return unitNumNonZero;
    else
        return unitNum;
}

liyinqiao committed
707 708
/* get the size of the memory space used */
int XTensor::GetDataSizeInChar() const
xiaotong committed
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
{
    if(isSparse){
        int num = int(unitNum * denseRatio + 1);
        int tupleSize = sizeof(int)+sizeof(DTYPE);
        int size = sizeof(int) + tupleSize*(num);
        return size;
    }
    else{
        return unitNum * unitSize;
    }
}

/* 
get unit size in terms of "dataType" 
>> myDataType - type of unit
<< return - unit size
*/
liyinqiao committed
726
int XTensor::GetUnitSize(TENSOR_DATA_TYPE myDataType) const
xiaotong committed
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
{
    if(myDataType == X_INT)
        return sizeof(int);
    else if(myDataType == X_FLOAT)
        return sizeof(float);
    else if(myDataType == X_DOUBLE)
        return sizeof(double);
    else if(myDataType == X_INT8)
        return 1;
    else if(myDataType == X_FLOAT16)
        return 2;
    return sizeof(float);
}

/* 
liyinqiao committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
get offset (2D) 
>> row - index of demension 0
>> col - index of demension 1
*/
MTYPE XTensor::GetOffset2D(int row, int col) const
{
    CheckNTErrors(order == 2, "Cannot get a 2d cell for a tensor whose order is not 2!");
    CheckNTErrors(row >= 0 && row < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(col >= 0 && col < dimSize[1], "dimension 1 is out of range!");

    return row * dimSize[1] + col;
}

/* 
get offset (3D) 
>> d0 - index of demension 0
>> d1 - index of demension 1
>> d2 - index of demension 2
*/
MTYPE XTensor::GetOffset3D(int d0, int d1, int d2) const
{
    CheckNTErrors(order == 3, "Cannot get a 3d cell for a tensor whose order is not 3!");
    CheckNTErrors(d0 >= 0 && d0 < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(d1 >= 0 && d1 < dimSize[1], "dimension 1 is out of range!");
    CheckNTErrors(d2 >= 0 && d2 < dimSize[2], "dimension 2 is out of range!");

    return (d0 * dimSize[1] + d1) * dimSize[2] + d2;
}

/* 
xiaotong committed
772
a tensor with all entries of 0 
xiaotong committed
773
*/
xiaotong committed
774
void XTensor::SetZeroAll()
xiaotong committed
775 776 777 778 779 780 781 782
{
    if(data == NULL)
        return;

    if(isSparse){
        if(devID >= 0){
#ifdef USE_CUDA
            int size = sizeof(int) + (sizeof(int)+sizeof(DTYPE)) * unitNumNonZero;
liyinqiao committed
783 784 785 786
            
            int devIDBackup = 0;
            cudaGetDevice(&devIDBackup);
            cudaSetDevice(devID);
xiaotong committed
787
            cudaMemset(data, 0, size);
liyinqiao committed
788
            cudaSetDevice(devIDBackup);
xiaotong committed
789 790 791 792 793 794 795 796 797 798
#endif
        }
        else
            *(int*)data = 0;

        unitNumNonZero = 0; 
    }
    else{
        if(devID >= 0){
#ifdef USE_CUDA
liyinqiao committed
799 800
            int devIDBackup = 0;
            cudaGetDevice(&devIDBackup);
xiaotong committed
801 802
            cudaSetDevice(devID);     
            cudaMemset(data, 0, unitNum * unitSize);
liyinqiao committed
803
            cudaSetDevice(devIDBackup);
xiaotong committed
804 805 806 807 808 809 810 811 812 813
#endif
        }
        else
            memset(data, 0, unitNum * unitSize);
    }
}

/*  set the tensor with an data array 
>> d - input data. it must be on CPU
>> num - number of data items
liyinqiao committed
814
>> beg - where we start the data copy in the data array of the tensor
xiaotong committed
815
*/
liyinqiao committed
816
void XTensor::SetData(const void* d, int num, int beg)
xiaotong committed
817
{
liyinqiao committed
818
    if(data == NULL || d == NULL)
xiaotong committed
819 820 821
        return;

    CheckNTErrors(!isSparse, "TODO");
liyinqiao committed
822 823 824 825
    CheckNTErrors(num <= unitNum - beg, "Illegal size!");

    XMemCopy((char*)data + beg * unitSize, devID, d, -1, num * unitSize);
}
xiaotong committed
826

liyinqiao committed
827 828 829 830 831 832 833
/* generate data items with a uniform distribution in [0, 1] */
void XTensor::Rand(int rNum, int cNum)
{
    _SetDataRand(this, rNum, cNum);
}

/* generate data items with a range by start, end and the step
834 835 836
>> start - the beginning of the array
>> end - the end of the array (it does not includes itself)
>> step - the step we take along the array
liyinqiao committed
837
*/
838
void XTensor::Range(int lower, int upper, int step)
liyinqiao committed
839 840 841 842 843 844 845 846 847
{
    _SetDataRange(this, lower, upper, step);
}

/* generate data items with a fixed value */
template<class T>
void XTensor::SetDataFixed(T num)
{
    _SetDataFixed(this, num);
xiaotong committed
848
}
liyinqiao committed
849 850 851
template void XTensor::SetDataFixed<int>(int);
template void XTensor::SetDataFixed<float>(float);
template void XTensor::SetDataFixed<double>(double);
xiaotong committed
852 853 854 855 856 857 858 859

/* 
set the tensor items by a uniform distribution in range [lower, upper]
>> lower - lower value of the range
>> upper - upper value of the range
*/
void XTensor::SetDataRand(DTYPE lower, DTYPE upper)
{
liyinqiao committed
860
    _SetDataRand(this, lower, upper);
xiaotong committed
861 862 863 864 865 866 867 868 869
}

/* 
set the tensor items by a normal distribution
>> mean - mean or expectation of the distribution
>> standardDeviation - standard deviation of the distribution
*/
void XTensor::SetDataRandn(DTYPE mean, DTYPE standardDeviation)
{
liyinqiao committed
870
    _SetDataRandN(this, mean, standardDeviation);
xiaotong committed
871 872
}

liyinqiao committed
873 874 875 876 877
/* 
set tensor items with an array of offsets 
>> offsets - offset for each data item
>> value - value for the data items
>> num - number of the data items
xiaotong committed
878
*/
liyinqiao committed
879
void XTensor::SetDataBatched(MTYPE* offsets, DTYPE value, int num)
xiaotong committed
880
{
liyinqiao committed
881
    _SetDataWithOffset(this, offsets, value, num);
882 883
}

xiaotong committed
884
/* 
liyinqiao committed
885 886 887 888
set tensor items with an array of values 
>> offsets - offset for each data item
>> values - value for each data item
>> num - number of the data items
xiaotong committed
889
*/
liyinqiao committed
890
void XTensor::SetDataBatchedWithValues(MTYPE* offsets, void* values, int num)
xiaotong committed
891
{
liyinqiao committed
892
    _SetDataWithOffsetAndValue(this, offsets, values, num);
xiaotong committed
893 894 895 896 897
}

/* 
get the value of a cell with the index 
>> index - index of each dimension
liyinqiao committed
898
>> size - size of the index
xiaotong committed
899 900
<< return - cell value
*/
liyinqiao committed
901
DTYPE XTensor::Get(int index[], int size) const
xiaotong committed
902
{
liyinqiao committed
903
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in the default type.");
xiaotong committed
904 905 906

    return ToCPU(devID, GetCell(index, size));
}
liyinqiao committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    
/*
get the value of a cell with its offset
>> offset - offset in the array
<< return - cell value
*/
DTYPE XTensor::Get(int offset) const
{
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in the default type.");
    CheckNTErrors(offset >= 0 && offset < unitNum, "Invalid index!");
    CheckNTErrors(data != NULL, "Cannot use an uninitialized tensor!");
    CheckNTErrors(denseRatio == 1.0F, "Only dense tensors are supported in Get(offset).");

    DTYPE* address = (DTYPE*)data + offset;

    return ToCPU(devID, address);
}
xiaotong committed
924 925 926 927 928 929 930

/* 
get the pointer to a cell
>> index - index of each dimension
>> size - size of index
<< return - pointer to the cell
*/
liyinqiao committed
931
void* XTensor::GetCell(int index[], int size) const
xiaotong committed
932 933 934
{
    CheckNTErrors((size == order), "Illegal index!");

liyinqiao committed
935 936 937 938
    int offset = index[0];
    for(int i = 1; i < size; ++i){
        CheckNTErrors((index[i] < dimSize[i]), "Index is out of range!");
        offset = offset * dimSize[i] + index[i];
xiaotong committed
939 940 941 942
    }
    
    if(isSparse){
        DTYPE value;
liyinqiao committed
943
        void* p;
xiaotong committed
944 945 946 947 948 949 950 951 952 953 954
        if(BinarySearch(offset, value, p))
            return (char*)p + sizeof(int);
        else
            return NULL;
    }
    else{
        return ((char*)data) + offset * unitSize;
    }
}

/*
liyinqiao committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
get the value of a cell in a 0d tensor in default type
<< return - value of cell(i) in float
*/
DTYPE XTensor::Get0D() const
{
    CheckNTErrors((order == 0), "Cannot get a 0d cell for a tensor whose order is not 0!");
    CheckNTErrors((dataType == DEFAULT_DTYPE), "The tensor is not in default type.");

    int dims[1] = {0};
    void* value = GetCell(dims, 0);

    return ToCPU(devID, value);
}

/*
xiaotong committed
970 971 972 973
get the value of a cell in a 1d tensor in default type
>> i - idex
<< return - value of cell(i) in float
*/
liyinqiao committed
974
DTYPE XTensor::Get1D(int i) const
xiaotong committed
975
{
liyinqiao committed
976
    CheckNTErrors((order == 1), "Cannot get a 1d cell for a tensor whose order is not 1!");
xiaotong committed
977 978 979
    CheckNTErrors((i >= 0 && i < dimSize[0]), "dimension 0 is out of range!");
    CheckNTErrors((dataType == DEFAULT_DTYPE), "The tensor is not in default type.");
    
liyinqiao committed
980 981
    int dims[1] = {i};
    void* value = GetCell(dims, 1);
xiaotong committed
982 983 984 985 986 987 988 989 990 991
    
    return ToCPU(devID, value);
}
    
/* 
get the value of a cell in a 2d tensor in default type
>> ni - row index
>> mi - column index
<< return - value of cell(ni, mi) in float
*/
992
DTYPE XTensor::Get2D(int ni, int mi) const
xiaotong committed
993 994 995 996 997 998 999
{
    CheckNTErrors((order == 2), "Cannot get a 2d cell for a tensor whose order is not 2!");
    CheckNTErrors((ni >= 0 && ni < dimSize[0]), "dimension 0 is out of range!");
    CheckNTErrors((mi >= 0 && mi < dimSize[1]), "dimension 1 is out of range!");
    CheckNTErrors((dataType == DEFAULT_DTYPE), "The tensor is not in default type.");

    int dims[2] = {ni, mi};
liyinqiao committed
1000
    void* value = GetCell(dims, 2);
xiaotong committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    
    return ToCPU(devID, value);
}

/* 
get the value of a cell in a 3d tensor 
>> d0 - index of dimension 0
>> d1 - index of dimension 1
>> d2 - index of dimension 2
*/
liyinqiao committed
1011
DTYPE XTensor::Get3D(int d0, int d1, int d2) const
xiaotong committed
1012
{
liyinqiao committed
1013
    CheckNTErrors((order == 3), "Cannot get a 3d cell for a tensor whose order is not 3!");
xiaotong committed
1014 1015 1016 1017 1018 1019
    CheckNTErrors((d0 >= 0 && d0 < dimSize[0]), "dimension 0 is out of range!");
    CheckNTErrors((d1 >= 0 && d1 < dimSize[1]), "dimension 1 is out of range!");
    CheckNTErrors((d2 >= 0 && d2 < dimSize[2]), "dimension 2 is out of range!");
    CheckNTErrors((dataType == DEFAULT_DTYPE), "The tensor is not in default type.");

    int dims[3] = {d0, d1, d2};
liyinqiao committed
1020
    void* value = GetCell(dims, 3);
xiaotong committed
1021 1022 1023
    
    return ToCPU(devID, value);
}
liyinqiao committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    
/*
get the int value of a cell by its offset
>> offset - offset of the item
*/
int XTensor::GetInt(int offset) const
{
    CheckNTErrors(dataType == X_INT, "The tensor is not in the integer type.");
    CheckNTErrors(offset >= 0 && offset < unitNum, "Invalid index!");
    CheckNTErrors(data != NULL, "Cannot use an uninitialized tensor!");
    CheckNTErrors(denseRatio == 1.0F, "Only dense tensors are supported in Get(offset).");
    
    int* address = (int*)data + offset;
    
    return ToCPUInt(devID, address);
}

/*
get the value of a cell in a 0d tensor in int type
<< return - value of cell(i) in int
*/
int XTensor::Get0DInt() const
{
    CheckNTErrors(order == 0, "Cannot get a 0d cell for a tensor whose order is not 0!");
    CheckNTErrors(dataType == X_INT, "The tensor is not in int type.");

    int dims[1] = {0};
    void* value = GetCell(dims, 0);

    return ToCPUInt(devID, value);
}
xiaotong committed
1055

1056 1057 1058 1059 1060
/*
get the value of a cell in a 1d tensor in int type
>> i - index
<< return - value of cell(i) in int
*/
liyinqiao committed
1061
int XTensor::Get1DInt(int i) const
1062
{
liyinqiao committed
1063 1064 1065
    CheckNTErrors(order == 1, "Cannot get a 1d cell for a tensor whose order is not 1!");
    CheckNTErrors(i >= 0 && i < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(dataType == X_INT, "The tensor is not in int type.");
1066
    
liyinqiao committed
1067 1068
    int dims[1] = {i};
    void* value = GetCell(dims, 1);
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    
    return ToCPUInt(devID, value);
}
    
/* 
get the value of a cell in a 2d tensor in int type
>> ni - row index
>> mi - column index
<< return - value of cell(ni, mi) in int
*/
liyinqiao committed
1079
int XTensor::Get2DInt(int ni, int mi) const
1080
{
liyinqiao committed
1081 1082 1083 1084
    CheckNTErrors(order == 2, "Cannot get a 2d cell for a tensor whose order is not 2!");
    CheckNTErrors(ni >= 0 && ni < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(mi >= 0 && mi < dimSize[1], "dimension 1 is out of range!");
    CheckNTErrors(dataType == X_INT, "The tensor is not in default type.");
1085 1086

    int dims[2] = {ni, mi};
liyinqiao committed
1087
    void* value = GetCell(dims, 2);
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    
    return ToCPUInt(devID, value);
}

/* 
get the value of a cell in a 3d tensor in int type
>> d0 - index of dimension 0
>> d1 - index of dimension 1
>> d2 - index of dimension 2
<< return - value of cell(d0, d1, d2) in int
*/
liyinqiao committed
1099
int XTensor::Get3DInt(int d0, int d1, int d2) const
1100
{
liyinqiao committed
1101 1102 1103 1104 1105
    CheckNTErrors(order == 3, "Cannot get a 3d cell for a tensor whose order is not 3!");
    CheckNTErrors(d0 >= 0 && d0 < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(d1 >= 0 && d1 < dimSize[1], "dimension 1 is out of range!");
    CheckNTErrors(d2 >= 0 && d2 < dimSize[2], "dimension 2 is out of range!");
    CheckNTErrors(dataType == X_INT, "The tensor is not in default type.");
1106 1107

    int dims[3] = {d0, d1, d2};
liyinqiao committed
1108
    void* value = GetCell(dims, 3);
1109 1110 1111 1112
    
    return ToCPUInt(devID, value);
}

xiaotong committed
1113 1114 1115 1116 1117
/* 
get the value of a cell in the sparse tensor 
>> i - i-th tuple in the tuple list of the sparse tensor
<< return - value of the tuple
*/
liyinqiao committed
1118
DTYPE XTensor::GetInSparse(int i) const
xiaotong committed
1119
{
liyinqiao committed
1120 1121
    CheckNTErrors(i >= 0 && i < unitNum, "Index is out of range!");
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");
xiaotong committed
1122

liyinqiao committed
1123 1124
    char* d = (char*)data + sizeof(int);
    DTYPE* value = (DTYPE*)(d + (sizeof(int) + sizeof(DTYPE)) * i + sizeof(int));
xiaotong committed
1125 1126 1127 1128 1129 1130 1131 1132 1133

    return ToCPU(devID, value);
}

/* 
get the key value of a tuple in a sparse tensor 
>> i - i-th tuple in the tuple list of the sparse tensor
<< return - key of the tuple
*/
liyinqiao committed
1134
int XTensor::GetKeyInSparse(int i) const
xiaotong committed
1135
{
liyinqiao committed
1136 1137
    CheckNTErrors(i >= 0 && i < unitNum, "Index is out of range!");
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");
xiaotong committed
1138

liyinqiao committed
1139 1140
    char* d = (char*)data + sizeof(int);
    int* key = (int*)(d + (sizeof(int) + sizeof(DTYPE)) * i);
xiaotong committed
1141 1142 1143 1144 1145 1146
    
    return ToCPUInt(devID, key);
}

/* 
set the value of a cell 
liyinqiao committed
1147
>> value - value we tend to set
xiaotong committed
1148
>> index - index of the cell for each dimension
liyinqiao committed
1149
>> size - size of the index
xiaotong committed
1150
*/
1151
bool XTensor::Set(DTYPE value, int index[], int size)
xiaotong committed
1152
{
liyinqiao committed
1153
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");
1154

xiaotong committed
1155 1156 1157
    return SetToDevice(devID, GetCell(index, size), value);
}

liyinqiao committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
/*
set the value of a cell with its offset in the array
>> value - the value we intend to set
>> offset - the offset in the array
*/
bool XTensor::Set(DTYPE value, int offset)
{
    CheckNTErrors(offset >= 0 && offset < unitNum, "Invalid index!");
    CheckNTErrors(data != NULL, "Cannot use an uninitialized tensor!");

    DTYPE* d = (DTYPE*)data + offset;

    return SetToDevice(devID, d, value);
}

/*
set the value of a cell in a 0d tensor
>> value - value we tend to set
<< return - succeeded or not
*/
bool XTensor::Set0D(DTYPE value)
{
    CheckNTErrors(order == 0, "Cannot get a 0d cell for a tensor whose order is not 0!");
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");

    int dims[1] = {0};

    return SetToDevice(devID, GetCell(dims, 0), value);
}

xiaotong committed
1188 1189
/* 
set the value of a cell in a 1d tensor 
liyinqiao committed
1190
>> value - value we tend to set
xiaotong committed
1191
>> i - item offset
liyinqiao committed
1192
<< return - succeeded or not
xiaotong committed
1193 1194 1195
*/
bool XTensor::Set1D(DTYPE value, int i)
{
liyinqiao committed
1196 1197 1198
    CheckNTErrors(order == 1, "Cannot get a 1d cell for a tensor whose order is not 1!");
    CheckNTErrors(i >= 0 && i < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");
xiaotong committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213

    int dims[1] = {i};

    return SetToDevice(devID, GetCell(dims, 1), value);
}

/* 
set the value of a cell in a 2d tensor in default type
>> value - value we tend to set
>> ni - row index
>> mi - column index
<< return - succeeded or not
*/
bool XTensor::Set2D(DTYPE value, int ni, int mi)
{
liyinqiao committed
1214 1215 1216 1217
    CheckNTErrors(order == 2, "Cannot get a 2d cell for a tensor whose order is not 2!");
    CheckNTErrors(ni >= 0 && ni < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(mi >= 0 && mi < dimSize[1], "dimension 1 is out of range!");
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");
xiaotong committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233

    int dims[2] = {ni, mi};

    return SetToDevice(devID, GetCell(dims, 2), value);
}

/* 
set the value of a cell in a 3d tensor in default type
>> value - value we tend to set
>> d0 - index of demension 0
>> d1 - index of demension 1
>> d2 - index of demension 2
<< return - succeeded or not
*/
bool XTensor::Set3D(DTYPE value, int d0, int d1, int d2)
{
liyinqiao committed
1234
    CheckNTErrors(order == 3, "Cannot get a 3d cell for a tensor whose order is not 3!");
1235 1236
    CheckNTErrors(d0 >= 0 && d0 < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(d1 >= 0 && d1 < dimSize[1], "dimension 1 is out of range!");
liyinqiao committed
1237
    CheckNTErrors(d2 >= 0 && d2 < dimSize[2], "dimension 2 is out of range!");
1238
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");
xiaotong committed
1239

1240
    int dims[3] = {d0, d1, d2};
xiaotong committed
1241 1242 1243

    return SetToDevice(devID, GetCell(dims, 3), value);
}
liyinqiao committed
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    
/*
set the integer value of a cell by its offset
>> value - value we tend to set to the item
>> offset - offset of the item
*/
bool XTensor::SetInt(int value, int offset)
{
    CheckNTErrors(offset >= 0 && offset < unitNum, "Invalid index!");
    CheckNTErrors(data != NULL, "Cannot use an uninitialized tensor!");
    
    int* d = (int*)data + offset;
    
    return SetToDeviceInt(devID, d, value);
}


/* 
set the integer value of a cell 
>> value - value we tend to set
>> index - index of the cell for each dimension
>> size - size of the index
<< return - succeeded or not
*/
bool XTensor::SetInt(int value, int index[], int size)
{
    CheckNTErrors(dataType == X_INT, "The tensor is not in integer type.");

    return SetToDeviceInt(devID, GetCell(index, size), value);
}

/*
set the integer value of a cell in a 1d tensor
>> value - value we tend to set
<< return - succeeded or not
*/
bool XTensor::Set0DInt(int value)
{
    CheckNTErrors(order == 0, "Cannot get a 0d cell for a tensor whose order is not 0!");
    CheckNTErrors(dataType == X_INT, "The tensor is not in integer type.");

    int dims[1] = {0};

    return SetToDeviceInt(devID, GetCell(dims, 0), value);
}

/* 
set the integer value of a cell in a 1d tensor 
>> value - value we tend to set
>> i - item offset
<< return - succeeded or not
*/
bool XTensor::Set1DInt(int value, int i)
{
    CheckNTErrors(order == 1, "Cannot get a 1d cell for a tensor whose order is not 1!");
    CheckNTErrors(i >= 0 && i < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(dataType == X_INT, "The tensor is not in integer type.");

    int dims[1] = {i};

    return SetToDeviceInt(devID, GetCell(dims, 1), value);
}

/* 
set the integer value of a cell in a 2d tensor in default type
>> value - value we tend to set
>> ni - row index
>> mi - column index
<< return - succeeded or not
*/
bool XTensor::Set2DInt(int value, int ni, int mi)
{
    CheckNTErrors(order == 2, "Cannot get a 2d cell for a tensor whose order is not 2!");
    CheckNTErrors(ni >= 0 && ni < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(mi >= 0 && mi < dimSize[1], "dimension 1 is out of range!");
    CheckNTErrors(dataType == X_INT, "The tensor is not in integer type.");

    int dims[2] = {ni, mi};

    return SetToDeviceInt(devID, GetCell(dims, 2), value);
}

/* 
set the integer value of a cell in a 3d tensor in default type
>> value - value we tend to set
>> d0 - index of demension 0
>> d1 - index of demension 1
>> d2 - index of demension 2
<< return - succeeded or not
*/
bool XTensor::Set3DInt(int value, int d0, int d1, int d2)
{
    CheckNTErrors(order == 3, "Cannot get a 3d cell for a tensor whose order is not 3!");
    CheckNTErrors(d0 >= 0 && d0 < dimSize[0], "dimension 0 is out of range!");
    CheckNTErrors(d1 >= 0 && d1 < dimSize[1], "dimension 1 is out of range!");
    CheckNTErrors(d2 >= 0 && d2 < dimSize[2], "dimension 2 is out of range!");
    CheckNTErrors((dataType == X_INT), "The tensor is not in integer type.");

    int dims[3] = {d0, d1, d2};

    return SetToDeviceInt(devID, GetCell(dims, 3), value);
}
xiaotong committed
1346 1347 1348 1349 1350 1351 1352 1353

/* 
increase the value of a cell in a 2d tensor
>> value - value we tend to set
>> ni - row index
>> mi - column index
<< return - succeeded or not
*/
liyinqiao committed
1354
bool XTensor::Add2D(DTYPE value, int ni, int mi)
xiaotong committed
1355
{
liyinqiao committed
1356 1357 1358 1359
    CheckNTErrors(ni >= 0 && ni < dimSize[0], "the row index is out of range!");
    CheckNTErrors(mi >= 0 && mi < dimSize[1], "the column index is out of range!");
    CheckNTErrors(dataType == DEFAULT_DTYPE, "The tensor is not in default type.");
    CheckNTErrors(isSparse == false, "TODO!");
xiaotong committed
1360 1361

    if(devID < 0){
liyinqiao committed
1362
        DTYPE* p = (DTYPE*)data + ni * dimSize[1] + mi;
xiaotong committed
1363

liyinqiao committed
1364
        CheckNTErrors((p != NULL), "No data array is found!");
xiaotong committed
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

        *p = *p + value;
    
        return true;
    }
    else{
        int dims[2] = {ni, mi};
        return SetToDevice(devID, GetCell(dims, 2), Get2D(ni, mi) + value);
    }
}

/* get the number of non-zero elements (in a sparse tensor) */
liyinqiao committed
1377
int XTensor::GetNonzeroSize() const
xiaotong committed
1378 1379 1380 1381 1382 1383 1384
{
    if(!isSparse){
        XPRINT(1, stderr, "WARNING! Counting non-zero elements in a dense tensor might be slow!\n");
        CheckNTErrors(devID < 0, "TODO");
        if(dataType == DEFAULT_DTYPE){
            int count = 0;
            for(int i = 0; i < unitNum; i++){
liyinqiao committed
1385
                DTYPE value = *(DTYPE*)((char*)data + i * sizeof(DTYPE));
xiaotong committed
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
                if(value == 0)
                    count++;
            }
            return count;
        }
        else{
            ShowNTErrors("TODO!");
            return -1;
        }
    }
    else{
        /* return the head of the tuple list */
        return unitNumNonZero;
    }
}

/* 
1403
set the tensor as "temporary" 
1404
>> myIsTMP - the flag
1405
*/
liyinqiao committed
1406
void XTensor::SetTMPFlag(bool myIsTmp)
1407 1408 1409 1410 1411
{
    isTmp = myIsTmp;
}

/* 
1412 1413 1414
set the tensor as "keep-gradient" 
>> myIsGrad - the flag
*/
liyinqiao committed
1415
void XTensor::SetGradFlag(bool myIsGrad)
1416 1417 1418 1419 1420
{
    isGrad = myIsGrad;
}

/* 
liyinqiao committed
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
set the tensor as "variable" 
>> myIsVar - the flag
*/
void XTensor::SetVarFlag(bool myIsVar)
{
    isVar = myIsVar;
    if(isVar)
        SetGradFlag(true);
}

/* 
xiaotong committed
1432 1433 1434 1435 1436 1437 1438
resize a tensor with a specified tensor size
>> myOrder - order of the tensor
>> myDimSize - the size of each dimension
>> myDataType - unit size (e.g., int, float, and double)
>> myDenseRatio - how often an element has non-zero value
<< return - succeeded or not
*/
liyinqiao committed
1439
bool XTensor::Resize(const int myOrder, const int* myDimSize, 
xiaotong committed
1440 1441 1442 1443 1444 1445 1446
                     const TENSOR_DATA_TYPE myDataType, const float myDenseRatio)
{
    /* free old mem */
    if(data != NULL){
        if (mem == NULL)
            XMemFree(devID, data);
        else
liyinqiao committed
1447
            mem->Release(data, GetDataSizeInChar(), signature);
xiaotong committed
1448 1449
    }

liyinqiao committed
1450 1451 1452 1453 1454 1455 1456
    signature = mem != NULL ? mem->GetSignature() : 0;
    
    order = myOrder;
    unitNum = 1;
    unitNumNonZero = 0;
    isInit = true;

xiaotong committed
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
    bool filledData = true;
    bool zeroData = false;
    for(int i = 0; i < order; i++){
        dimSize[i] = abs(myDimSize[i]);
        if(myDimSize[i] < 0)
            filledData = false;
        if(myDimSize[i] == 0)
            zeroData = true;
        unitNum *= dimSize[i];
    }

    data = NULL;
    denseRatio = myDenseRatio;
    isSparse = denseRatio < 1.0F ? true : false;
    dataType = myDataType;
    unitSize = GetUnitSize(dataType);

    if(myDataType != DEFAULT_DTYPE)
        isDefaultDType = false;
    else
        isDefaultDType = true;

    if(zeroData){
        unitNum = 0;
        return false;
    }

    if(isSparse){
        /*
        for sparse matrices, we use a list of tuple (key, value), 
1487
        ordered by key. Take a (2-dimensional) matrix as an example, 
xiaotong committed
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
        we have key = m * i + j;
        The data array is
        ---------
        | 0 | 3 |
        ---------
        | 5 | 0 |
        ---------
        we have
        2
        (0, 1, 3)
        (1, 0, 5)
        where the first number (2) indicates the number of elements.
        */
        
        int num = int(unitNum * denseRatio + 1);
liyinqiao committed
1503 1504 1505
        int tupleSize = sizeof(int) + sizeof(DTYPE);
        int size = sizeof(int) + tupleSize * (num);

xiaotong committed
1506
        if(filledData){
liyinqiao committed
1507
            int* d = NULL;
xiaotong committed
1508 1509 1510 1511 1512

            if(mem == NULL){
                d = new int[size];
                memset(d, 0, size);
            }
liyinqiao committed
1513
            else{
xiaotong committed
1514
                d = (int*)mem->Alloc(mem->devID, size);
liyinqiao committed
1515
            }
xiaotong committed
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530

            if(d == NULL)
                return false;

#if !defined(UNSAFE_BUT_FAST_MEM)
            XMem::SetZero(d, sizeof(int), mem);
#endif
            data = d;
        }
        return true;
    }
    else{
        if(filledData){
            /* allocate the new one */
            if(mem == NULL){
1531
                data = XMemAlloc(devID, unitNum * unitSize); 
xiaotong committed
1532
#if defined(UNSAFE_BUT_FAST_MEM)
1533
                XMemSet(devID, data, 0, unitNum * unitSize);
xiaotong committed
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
#endif
            }
            else
                data = (void*)mem->Alloc(mem->devID, unitNum * unitSize);

            if(data == NULL)
                return false;
        }

#if !defined(UNSAFE_BUT_FAST_MEM)
        if(data != NULL)
            XMem::SetZero(data, unitNum * unitSize, mem);
#endif
        return true;
    }
}

/* 
liyinqiao committed
1552
resize a tensor by another
xiaotong committed
1553 1554
>> myTensor - tensor for reference
*/
liyinqiao committed
1555
bool XTensor::Resize(const XTensor* myTensor)
xiaotong committed
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
{
    denseRatio = myTensor->denseRatio;
    TENSOR_DATA_TYPE myDataType = myTensor->dataType;

    if(myDataType != DEFAULT_DTYPE)
        isDefaultDType = false;
    else
        isDefaultDType = true;

    return Resize(myTensor->order, myTensor->dimSize, myDataType, denseRatio);
}

/* 
binary search to find an element in a sparse tensor
>> key - for search
>> value - value for return
>> position - the position of the tuple.
              it is the previous one if there is no hit
liyinqiao committed
1574
<< return - found it or not?
xiaotong committed
1575
*/
liyinqiao committed
1576
bool XTensor::BinarySearch(int key, DTYPE& value, void*& position) const
xiaotong committed
1577 1578 1579 1580
{
    CheckNTErrors((isSparse), "A sparse tensor is required!");
    CheckNTErrors((dataType == DEFAULT_DTYPE), "The tensor is not in the default type.");

liyinqiao committed
1581
    int* d = (int*)data;
xiaotong committed
1582 1583 1584 1585 1586 1587 1588

    if(key < 0 || *d == 0){
        value = 0;
        position = NULL;
        return false;
    }

liyinqiao committed
1589 1590
    int low = 0;
    int high = *d - 1;
xiaotong committed
1591 1592
    int last = -1;
    bool ok = false;
liyinqiao committed
1593
    int* k = NULL;
xiaotong committed
1594
    int headSize = sizeof(int);
liyinqiao committed
1595 1596
    int tupleSize = sizeof(int) + sizeof(DTYPE);
    char* p = (char*)data + headSize;
xiaotong committed
1597 1598

    while (low <= high){  
liyinqiao committed
1599
        int mid = low + (high - low)/2;
xiaotong committed
1600
        k = (int*)(p + tupleSize * mid);
liyinqiao committed
1601
        if(*k == key){
xiaotong committed
1602
            ok = true;
liyinqiao committed
1603
            high = mid - 1;
xiaotong committed
1604
            break;
liyinqiao committed
1605
        }
xiaotong committed
1606
        else if(*k > key){
liyinqiao committed
1607
            high = mid - 1;
xiaotong committed
1608 1609
        }
        else{
liyinqiao committed
1610
            low = mid + 1;
xiaotong committed
1611 1612
            last = mid;
        }
liyinqiao committed
1613
    }
xiaotong committed
1614 1615

    if(ok){
liyinqiao committed
1616
        DTYPE* p = (DTYPE*)((char*)k + sizeof(int));
xiaotong committed
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
        value = *p;
        position = k;
        return true;
    }
    else{
        value = 0;
        if(last == -1)
            position = NULL;
        else
            position = (char*)data + headSize + tupleSize * last;
        return false;
    }
}

/* 
dump data to a file 
>> file - where to domp the data
>> label - label of the tensor
>> n - number of items to dump
liyinqiao committed
1636
>> beg - the first item id
xiaotong committed
1637 1638
>> verbose - verbose level
*/
liyinqiao committed
1639
void XTensor::Dump(FILE* file, const char* label, const int n, const int beg, const int verbose)
xiaotong committed
1640 1641 1642 1643
{
    if (verbose > verboseLevel)
        return;

liyinqiao committed
1644
    void* d = data;
xiaotong committed
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
    bool isNewData = false;

#ifdef USE_CUDA
    if (devID >= 0) {
        CudaGPUToCPUFlush(this);
        d = dataHost;
        isNewData = true;
    }
#endif

    if (d == NULL) {
        if (isSparse) {
            int num = 0;
            for (int i = 0; i < order; i++)
liyinqiao committed
1659
                num *= dimSize[i];
xiaotong committed
1660 1661
            num = int(num * denseRatio + 1);
            int tupleSize = sizeof(int) + sizeof(DTYPE);
liyinqiao committed
1662
            int size = sizeof(int) + tupleSize * (num);
xiaotong committed
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675

            d = new char[size];
            memset(d, 0, size);
        }
        else {
            d = new char[unitNum * unitSize];
            memset(d, 0, unitNum * unitSize);
        }
        isNewData = true;
    }

    if (label != NULL)
        fprintf(file, "%s ", label);
1676 1677 1678
    
    if(isInit){
        fprintf(file, "order=%d dimsize=", order);
liyinqiao committed
1679 1680 1681
        if(order == 0) {
            fprintf(file, "%d,", dimSize[0]);
        }
1682 1683 1684 1685 1686 1687 1688 1689
        for (int i = 0; i < order; i++) {
            fprintf(file, "%d", dimSize[i]);
            if (i < order - 1)
                fprintf(file, ",");
        }
    }
    else{
        fprintf(file, "order=-1 dimsize=-1");
xiaotong committed
1690 1691 1692 1693
    }

    fprintf(file, " dtype=%s dense=%f\n", GetDataTypeName(dataType), denseRatio);

1694 1695 1696
    if(!isInit){
        fprintf(file, "NULL");
    }
xiaotong committed
1697
    if (!isSparse) {
liyinqiao committed
1698
        int end = MIN(n > 0 ? beg + n : beg + unitNum, unitNum);
xiaotong committed
1699
        if (dataType == DEFAULT_DTYPE) {
liyinqiao committed
1700 1701 1702 1703 1704 1705 1706
            for(int i = beg; i < end; i++){
                DTYPE f = ((DTYPE*)d)[i];
                if(i == beg)
                    fprintf(file, "%e", f);
                else
                    fprintf(file, " %e", f);

xiaotong committed
1707
            }
liyinqiao committed
1708 1709 1710 1711 1712 1713 1714 1715
        }
        else if (dataType == X_INT) {
            for(int i = beg; i < end; i++){
                int f = ((int*)d)[i];
                if(i == beg)
                    fprintf(file, "%d", f);
                else
                    fprintf(file, " %d", f);
xiaotong committed
1716 1717
            }
        }
liyinqiao committed
1718 1719 1720 1721 1722 1723 1724 1725
        else if (dataType == X_FLOAT16) {
            for(int i = beg; i < end; i++){
                DTYPE f = ((unsigned short*)d)[i];
                if(i == beg)
                    fprintf(file, "%e", f);
                else
                    fprintf(file, " %e", f);
            }
xiaotong committed
1726
        }
liyinqiao committed
1727 1728
        else
            ShowNTErrors("TODO!");
xiaotong committed
1729 1730 1731
    }
    else {
        int num = this->unitNumNonZero > 0 ? *(int*)d : 0;
liyinqiao committed
1732 1733
        if (beg + n > 0)
            num = MIN(num, beg + n);
xiaotong committed
1734
        fprintf(file, "%d ", num);
liyinqiao committed
1735
        for (int i = beg; i < num; i++) {
xiaotong committed
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
            int key = GetKeyInSparse(i);
            DTYPE value = GetInSparse(i);
            fprintf(file, "[%d]%e ", key, value);
        }
    }
    fprintf(file, "\n");

    if (isNewData) {
        delete[](char*)d;
#ifdef USE_CUDA
        if (devID >= 0)
            dataHost = NULL;
#endif
    }
}

/* 
1753
dump data to a file
liyinqiao committed
1754
>> tensor - the tensor for dumping
1755 1756
>> file - where to domp the data
>> label - label of the tensor
liyinqiao committed
1757 1758
>> n - number of the items to dump
>> beg - the first item id
1759 1760
>> verbose - verbose level
*/
liyinqiao committed
1761
void XTensor::Dump(const XTensor* tensor, FILE* file, const char* label, const int n, const int beg, const int verbose)
1762 1763 1764
{
    XTensor a(tensor->order, tensor->dimSize, tensor->dataType, tensor->denseRatio, tensor->devID, tensor->mem);
    _CopyValues(tensor, &a);
liyinqiao committed
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
    a.Dump(file, label, n, beg, verbose);
}

/* 
dump data to a binary file 
>> file - where to dump the data
*/
void XTensor::BinaryDump(FILE* file)
{
    XTensor tmp;
    InitTensorOnCPU(&tmp, this);
    _CopyValues(this, &tmp);

    switch (dataType) {
        case X_INT: {
            fwrite(tmp.data, sizeof(int), unitNum, file);
            break;
        }
        case X_FLOAT16: {
            fwrite(tmp.data, sizeof(unsigned short), unitNum, file);
            break;
        }
        default: {
            fwrite(tmp.data, sizeof(float), unitNum, file);
            break;
        }
    }
1792 1793 1794
}

/* 
xiaotong committed
1795 1796 1797 1798
read data from a file
>> file - where to load the data
>> label - label of the tensor
*/
liyinqiao committed
1799
void XTensor::Read(FILE* file, const char* label)
xiaotong committed
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
{
    char typeName[32] = "";
    char dimSizeName[128] = "";
    int dimNum;
    int dims[MAX_TENSOR_DIM_NUM];
    float dRatio;

    int head = (int)strlen(label);
    if (label != NULL) {
        for (int i = 0; i < head; i++) {
            char c = fgetc(file);
            CheckNTErrors(c == label[i], "Incorrect tensor label!");
        }
    }

    fgetc(file);

    if (fscanf(file, "order=%d dimsize=%s dtype=%s dense=%f",
xiaotong committed
1818
                      &dimNum, dimSizeName, typeName, &dRatio) < 4) {
xiaotong committed
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
        ShowNTErrors("Incorrect format when reading the tensor!");
    }

    char c;
    
    do {
        c = fgetc(file);
    } while (c != '\n' && c != EOF);

    isSparse = dRatio < 1.0F ? true : false;

    int o = 0;
    bool sameSize = true;
liyinqiao committed
1832
    char* p = dimSizeName;
xiaotong committed
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
    while (*p != 0) {
        while (*p == ' ' || *p == '\t')
            p++;
        int dsize = 0;
        while (*p != ',' && *p != ' ' && *p != '\t' && *p != '\0') {
            CheckNTErrors(*p >= '0' && *p <= '9', "Incorrect number format!");
            dsize = dsize * 10 + (*p - '0');
            p++;
        }
        p++;
        dims[o++] = dsize;
        if (dims[o - 1] != dimSize[o - 1])
            sameSize = false;
    }

    CheckNTErrors(o == dimNum, "Incorrect dimension number!");
    for (int i = 0; i < o; i++) {
        CheckNTErrors(dimSize[i] == dims[i], "Incorrect dimension size!");
    }

    if (!sameSize || dRatio > denseRatio || GetDataType(typeName) != dataType)
        Resize(dimNum, dims, GetDataType(typeName), dRatio);

liyinqiao committed
1856 1857
    void* dataBuf = XMemAlloc(-1, GetDataSizeInChar());
    void* dataBackup = data;
xiaotong committed
1858 1859 1860 1861 1862
    data = dataBuf;

    if (!isSparse) {
        if (dataType == DEFAULT_DTYPE) {
            for (int i = 0; i < unitNum; i++) {
liyinqiao committed
1863
                DTYPE* f = ((DTYPE*)data) + i;
xiaotong committed
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
                if (fscanf(file, "%e", f) < 1) {
                    ShowNTErrors("Incorrect tensor format!");
                }
            }
        }
        else {
            ShowNTErrors("TODO!");
        }
    }
    else {
        int num = 0;
        if (fscanf(file, "%d", &num) < 1) {
            ShowNTErrors("Incorrect tensor format!");
        }

        for (int i = 0; i < num; i++) {
            int key;
            DTYPE value;
            if (fscanf(file, "[%d]%e", &key, &value) < 3) {
                ShowNTErrors("Incorrect sparse tensor format!");
            }

            int ds[MAX_TENSOR_DIM_NUM];
            for (int i = 0; i < order; i++) {
liyinqiao committed
1888 1889
                ds[i] = key % dimSize[i];
                key /= dimSize[i];
xiaotong committed
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
            }
            Set(value, ds);
        }
    }


    do {
        c = fgetc(file);
    } while (c != '\n' && c != EOF);

    XMemCopy(dataBackup, devID, data, -1, GetDataSizeInChar());
    data = dataBackup;

    delete[](char*)dataBuf;
}

liyinqiao committed
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
/* 
read data from a binary file
>>> file - the file stream pointer
>>> offset - the distance from the start to this tensor
*/
void XTensor::BinaryRead(FILE* file, size_t offset)
{
    switch (dataType) {
        case X_INT: {
            int* d = new int[unitNum];
            fread(d, sizeof(int), unitNum, file);
            SetData(d, unitNum);
            delete[] d;
            break;
        }
        case X_FLOAT16: {
            unsigned short* d = new unsigned short[unitNum];
            fread(d, sizeof(unsigned short), unitNum, file);
            SetData(d, unitNum);
            delete[] d;
            break;
        }
        default: {
            float* d = new float[unitNum];
            fread(d, sizeof(float), unitNum, file);
            SetData(d, unitNum);
            delete[] d;
            break;
        }
    }
}

xiaotong committed
1938 1939 1940 1941
/*
flush the data to the target device
>> targetMem - memory pool on the target device
*/
liyinqiao committed
1942
void XTensor::FlushToMem(XMem* targetMem)
xiaotong committed
1943 1944 1945 1946 1947 1948 1949
{
    if (targetMem == NULL)
        return;

    if (targetMem->devID >= 0) {
#ifdef USE_CUDA
        if (devID < 0) {
liyinqiao committed
1950
            TensorList l(1);
xiaotong committed
1951 1952 1953 1954
            l.Add(this);
            CudaCPUToGPUFlush(&l, targetMem->devID, targetMem);
        }
        else if (mem != targetMem) {
liyinqiao committed
1955
            void* tmpData = targetMem->Alloc(targetMem->devID, GetDataSizeInChar());
xiaotong committed
1956
            XMemCopy(tmpData, targetMem->devID, data, devID, GetDataSizeInChar());
liyinqiao committed
1957
            mem->Release(data, GetDataSizeInChar(), signature);
xiaotong committed
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
            data = tmpData;
            mem = targetMem;
            devID = mem->devID;
        }
#else
        ShowNTErrors("Recompile the code with USE_CUDA!");
#endif
    }
    else {
        if (devID >= 0) {
#ifdef USE_CUDA
liyinqiao committed
1969
            CudaGPUToCPUFlush(this, targetMem->devID, targetMem);
xiaotong committed
1970 1971 1972 1973
#else
            ShowNTErrors("Recompile the code with USE_CUDA!");
#endif
        }
liyinqiao committed
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
        else if (mem != targetMem) {
            void* tmpData = targetMem->Alloc(targetMem->devID, GetDataSizeInChar());
            XMemCopy(tmpData, targetMem->devID, data, devID, GetDataSizeInChar());
            if (mem != NULL)
                mem->Release(data, GetDataSizeInChar(), signature);
            else
                XMemFree(devID, data);
            data = tmpData;
            mem = targetMem;
            devID = mem->devID;
        }
xiaotong committed
1985 1986 1987 1988 1989 1990 1991
    }
}

/*
allocate the memory space of the tensor (in the global memory) 
>> tensor - the tensor we intend to process
>> myMem - the memory pool we are using
liyinqiao committed
1992
>> useBuf - indicates whether we use the buffer in the memory pool
xiaotong committed
1993
*/
liyinqiao committed
1994
void XTensor::AllocateData(XTensor* tensor, XMem* myMem, bool useBuf)
xiaotong committed
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
{
    if(tensor == NULL)
        return;

    if(myMem == NULL){
        if(tensor->data != NULL)
            FreeData(tensor, NULL, false);
        tensor->data = XMemAlloc(tensor->devID, tensor->GetDataSizeInChar());
        tensor->isInGlobalMem = true;
    }
    else{
        CheckNTErrors((tensor->data == NULL), "Cannot renew the space for the tensor");
        if(useBuf){
            tensor->data = myMem->AllocBuf(tensor->devID, tensor->GetDataSizeInChar());
            tensor->isInGlobalMem = false;
        }
        else{
            tensor->data = myMem->AllocGlobal(tensor->devID, tensor->GetDataSizeInChar());
            tensor->isInGlobalMem = true;
        }
    }
liyinqiao committed
2016 2017

    tensor->signature = 0;
xiaotong committed
2018 2019 2020 2021 2022 2023
}

/* 
free the memory space of the tensor (in the global memory) 
>> tensor - the tensor we intend to process
>> myMem - the memory pool we are using
liyinqiao committed
2024
>> useBuf - indicates whether we use the buffer in the memory pool
xiaotong committed
2025
*/
liyinqiao committed
2026
void XTensor::FreeData(XTensor* tensor, XMem* myMem, bool useBuf)
xiaotong committed
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
{
    if(tensor == NULL)
        return;

    if(myMem == NULL){
        XMemFree(tensor->devID, tensor->data);
    }
    else{
        if(tensor->isInGlobalMem)
            myMem->ReleaseGlobal(tensor->devID, tensor->data);
        else
            myMem->ReleaseBuf(tensor->devID, tensor->GetDataSizeInChar());
    }

    tensor->data = NULL;
    tensor->isInGlobalMem = false;
}

liyinqiao committed
2045 2046
/* overloading of the plus-sign */
XTensor operator+ (const DTYPE shift, const XTensor& tensor)
xiaotong committed
2047
{
liyinqiao committed
2048
    return ScaleAndShift(tensor, 1, shift);
xiaotong committed
2049 2050
}

liyinqiao committed
2051 2052
/* overloading of the minus-sign */
XTensor  operator- (const DTYPE shift, const XTensor& tensor)
xiaotong committed
2053
{
liyinqiao committed
2054
    return ScaleAndShift(tensor, 1, -shift);
xiaotong committed
2055 2056
}

liyinqiao committed
2057 2058
/* overloading of the multiply-sign */
XTensor  operator* (const DTYPE scale, const XTensor& tensor)
xiaotong committed
2059
{
liyinqiao committed
2060
    return ScaleAndShift(tensor, scale, 0);
xiaotong committed
2061 2062
}

liyinqiao committed
2063 2064
/* overloading of the division-sign */
XTensor  operator/ (const DTYPE scale, const XTensor& tensor)
xiaotong committed
2065
{
liyinqiao committed
2066
    return ScaleAndShift(tensor, (DTYPE)1.0F / scale, 0);
xiaotong committed
2067 2068 2069
}

} /* end of the nts (NiuTrans.Tensor) namespace */