XMem.h 12 KB
Newer Older
1
/* NiuTrans.Tensor - an open-source tensor library
liyinqiao committed
2
 * Copyright (C) 2017, Natural Language Processing Lab, Northeastern University. 
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * 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 (xiaotong@mail.neu.edu.cn) 2016-5-25
 *
 */

#ifndef __XMEM_H__
#define __XMEM_H__

liyinqiao committed
27
#include <stdio.h>
28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <stdlib.h>

#ifdef CUDA_BLAS
#define USE_CUDA
#endif

#ifdef USE_CUDA
// the CUDA stuff
#include <cuda_runtime.h>
#include <cublas_v2.h>
#include <cuda.h>
#include <curand.h>
#endif

liyinqiao committed
42 43 44 45 46 47 48 49 50
#ifdef __APPLE__
#include <sys/types.h>
#include <sys/sysctl.h>
#elif WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

51 52 53 54 55 56 57 58 59 60 61 62
/* the nts (NiuTrans.Tensor) namespace */
namespace nts{

typedef unsigned long long MTYPE;
typedef long long int      MTYPEINT;
typedef long long          INT_64;

//#define CUDA_PITCH 256
#define CUDA_PITCH 1
#define CUDA_HOST_MALLOC 1
#define MY_PITCH CUDA_PITCH
#define BUF_PITCH 256
liyinqiao committed
63
#define MIN_BLOCK_SIZE_FOR_MEMPOOL 256 * 1024 * 1024
64
#define MIN_BLOCK_NUM_FOR_MEMPOOL 1024
liyinqiao committed
65 66
#define MAX_CPU_MEM_NUM 16
#define MAX_GPU_MEM_NUM 16
67 68 69 70 71 72 73

/* 
mode of runnig a memory pool 
- UNI_FREE: free all memory space when the memory allocation is no use
- FREE_ON_THE_FLY: run in normal "malloc" and "free" ways
*/
enum MEMPOOL_MODE {UNI_FREE, FREE_ON_THE_FLY};
liyinqiao committed
74 75
    
struct MPieceNode;
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

/* header of a memory piece (FREE_ON_THE_FLY) */
struct MHeader
{
    /* state of the memory piece 
       1: free
       2: in use
    */
    int state;

    /* size of the allocated memory */
    MTYPE size;

    /* pointer to the header of the previous memory piece */
    MHeader * pre;

    /* pointer to the header of the next memory piece */
    MHeader * next;

    /* id of the memory block */
    int blockID;
liyinqiao committed
97 98 99
    
    /* pointer to the index node */
    MPieceNode * indexNode;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
};

/* index of memory piece */
struct MPieceNode
{
    /* size of the memory piece */
    MTYPE size;

    /* previous node */
    MPieceNode * pre;

    /* next node */
    MPieceNode * next;

    /* pointer to the head of a memory piece */
    void * p;
liyinqiao committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    
    /* pointer to the head of memory that is returned back to the user */
    void * pReal;

    /* header of the memory piece */
    MHeader head;
};

/* memory block */
struct XMemBlock
{
    /* pointer to where to start */
    void * mem;

    /* size of the block */
    MTYPE size;

    /* size of the used memory in this block */
    MTYPE used;

    /* desired size of the block */
    MTYPE sizeDesired;
    
    /* first head of the block */
    MHeader * head;
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
};

/* 
memory pool.
Basically a memory pool runs in two ways. It can be an naive implementation (uni-free mode)
that allocates the memory in a continuous manner and free the used memory space
in the end - the user does not need to call the "memfree" function
when a small piece of memory is not used any more. Instead we call the "go back"
function to the initial state when all memory space in the memory pool is not in use.
Another way (free on-the-fly mode) is to allocate and free the memory space as in standard 
"malloc" and "free" manners. Here we do it on a pre-allocated memory block. This mode is 
more flexible but relatively slower than the uni-free mode.
*/
class XMem
{
public:
    /* 
    device id 
    <0:  CPU memory
    >=0: GPU device ID
    */
    int devID;

    /* mode of running the memory pool */
    MEMPOOL_MODE mode;

liyinqiao committed
167 168 169
    /* signature */
    MTYPE signature;

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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    /* indicates whether the memory allocation is static */
    bool isStatic;

    /* memory blocks */
    XMemBlock * blocks;

    /* number of memory blocks */
    int blockNum;

    /* max size of a block */
    MTYPE maxBlockSize;

    /* total size of all memory blocks */
    MTYPE totalBlockSize;

    /* total size of used memory */
    MTYPE totalUsed;

    /* current mem block that is using */
    XMemBlock * curBlock;

    /* id of the current mem block */
    int curBlockID;

    /* id of the final mem block that is used */
    int finalBlockID;

    /* pointer to the buffer used to store temp data */
    void * buf;

    /* size of the buffer */
    MTYPE bufSize;

    /* size of the used buffer in this block */
    MTYPE bufUsed;

    /* name of the memory pool */
    char * name;

    /* pin for the memory. It is used for recording the starting address
       before we apply for a large amount of the memory. Then we can go
       back to this point for memory release. */
    int curBlockPin;
    MTYPE curUsedPin;
    MTYPE bufUsedPin;

liyinqiao committed
216 217 218
    /* indicates whether the memory pool is initialized */
    bool isInitialized;

219 220 221 222 223 224 225 226 227 228
#ifdef USE_CUDA
    /* handle used for cublas */
    cublasHandle_t cublasHandle;

    /* random number generator for cuda code */
    curandGenerator_t randGen;
#endif

public:
    /* index of the free memory pieces */
liyinqiao committed
229 230 231 232
    MPieceNode * memIndex;
    
    /* for double buffering */
    MPieceNode * memIndex2;
233 234

    /* maximum number of index nodes */
liyinqiao committed
235
    INT_64 nodeNum;
236 237

    /* count of the used nodes */
liyinqiao committed
238
    INT_64 nodeNumUsed;
239 240 241 242 243 244 245 246 247 248

    /* minimal size allocation for each index entry */
    MTYPE * minSizeIndex;

    /* number of the index entries */
    int indexEntryNum;

    /* index offset */
    int indexOffset;

liyinqiao committed
249 250 251
    /* indicates whether we merge free memory pieces on the fly */
    bool mergeFreeOTF;

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
public:

    /* constructor */
    XMem();

    /* constructor */
    XMem(int myDevID,
         MEMPOOL_MODE myMode = UNI_FREE,
         MTYPE myBlockSize = MIN_BLOCK_SIZE_FOR_MEMPOOL, 
         int myBlockNum = MIN_BLOCK_NUM_FOR_MEMPOOL, 
         MTYPE myBufSize = 0);

    /* deconstructor */
    ~XMem();

    /* initialize it */
    void Initialize(int myDevID, MEMPOOL_MODE myMode, MTYPE myBlockSize, int myBlockNum, MTYPE myBufSize);

    /* free memory */
    void Free();

    /* free a piece of memory */
    void Free(int myDevID, void * mem);

liyinqiao committed
276 277 278
    /* get signature */
    MTYPE GetSignature();

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    /* use string as the name of the memory pool */
    void SetName(const char * myName);

    /* switch to the device we want to work */
    void SetDevice(int myDevID);

    /* switch to the device (with fast cuda execution mode) we want to work */
    void SetDeviceFast(int myDevID);

    /* run in static mode */
    void SetStaticMode(bool myIsStatic);

    /* specify if the memory pool is used for tensor computation (rather
       than storage */
    void SetComputationMode(bool myIsForComputation);

    /* initialize the index */
liyinqiao committed
296
    void SetIndex(INT_64 indexSize, MTYPE minSizeFirst = 256, int minSizeNum = 20);
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

    /* get device id */
    int GetDevID();

    /* set desired memory block size */
    void SetDesiredSize(int myDevID, int blockID, MTYPE mySize);

    /* require a piece of memory */
    void * Alloc(MTYPE mySize);

    /* require a piece of memory */
    void * Alloc(int myDevID, MTYPE mySize);

    /* require a piece of memory in a dynamic manner */
    void * AllocDynamic(int myDevID, MTYPE mySize);

    /* require a piece of memory with fixed size (if possible) */
    void * AllocStatic(int myDevID, MTYPE mySize);

    /* require a piece of memory that is not in the memory pool */
    void * AllocGlobal(int myDevID, MTYPE mySize);

    /* get the available size of the memory that can be used */
    MTYPE GetAvailableSize(int myDevID);

    /* require a piece of memory in the buffer */
    void * AllocBuf(int myDevID, MTYPE mySize, int pitch = BUF_PITCH);

    /* release a piece of memory */
liyinqiao committed
326
    void Release(void * p, MTYPE size, MTYPE code);
327 328

    /* release a piece of memory */
liyinqiao committed
329
    void Release(int myDevID, void * p, MTYPE size);
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

    /* release a piece of memory in the buffer */
    void ReleaseBuf(int myDevID, MTYPE mySize, int pitch = BUF_PITCH);

    /* release a piece of memory that is not in the memory pool */
    void ReleaseGlobal(int myDevID, void * p);

    /* allocate a piece of memory as "malloc" */
    void * AllocStandard(int myDevID, MTYPE mySize, bool myIsRebuiltIndex = false);

    /* find the highest set bit (or most significant set bit) in an integer-64 */
    int GetMSB(MTYPE mySize);

    /* find the index entry for allocation query */
    int FindIndexEntry(MTYPE mySize);

liyinqiao committed
346
    /* remove an index node for available memory pieces */
347 348
    void RemoveIndexNode(MPieceNode * node, MPieceNode * entry = NULL);

liyinqiao committed
349 350 351 352 353 354 355 356
    /* add an index node for available memory pieces */
    void AddFreeIndexNode(MPieceNode * node, MPieceNode * entry = NULL);
    
    /* remove an index node for memory pieces in use */
    void RemoveAllocIndexNode(MPieceNode * node, MPieceNode * entry = NULL);
    
    /* add an index node for available memory pieces */
    void AddAllocIndexNode(MPieceNode * node, MPieceNode * entry = NULL);
357 358

    /* release a piece of memory as "free" */
liyinqiao committed
359
    void ReleaseStandard(int myDevID, void * p, MTYPE size);
360 361 362 363 364 365 366 367 368 369 370 371 372 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

    /* rebuild index to merge small fragments of memory and free the block with no use */
    void RebuildIndex();

    /* reset buffer */
    void Reset(int myDevID);

    /* get pitch for aligned memory */
    MTYPE GetPitch(int myDevID, MTYPE baseAddress, MTYPE mySize);

    /* get pitched address for aligned memory */
    void * GetPitchedAddress(void * address, MTYPE pitch);

    /* get current address (for use) */
    void * GetAddress();

    /* clear it */
    void Clear();

    /* clear the buffer */
    void ClearBuf();

    /* clear the memory pool and the buffer */
    void ClearAll();

    /* set a variable to the input value */
    static
    void Copy(void * tgt, void * src, int size, XMem * tgtMem = NULL, XMem * srcMem = NULL);

    /* set a float-typed variable to the input value */
    static
    void CopyFloat(float * tgt, float * src, XMem * tgtMem = NULL, XMem * srcMem = NULL);

    /* set a variable to 0 */
    static
    void SetZero(void * tgt, MTYPE size, XMem * tgtMem = NULL);

    /* record the pin point */
    void SetPin();

    /* go back to the pin point */
    void BackToPin();

    /* record the pin point for buffer */
    void SetPinBuf();

    /* go back to the pin point for buffer */
    void BackToPinBuf();

    /* transform a size into a number (in million) */
    static
    MTYPE GetMemSize(const char * size);

    /* transform a size into a number (in Bytes) */
    static
    MTYPE GetMemSizeInBytes(const char * size);

    /* create a new cublas handle */
    void CreateBLASHandle();

liyinqiao committed
420 421 422
    /* show profile of the memory pool */
    void ShowMemUsage(FILE * file);

423 424 425 426 427 428 429
#ifdef USE_CUDA
    /* get the handle of cublas */
    cublasHandle_t * GetCublasHandle();
#endif

};

liyinqiao committed
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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
/*
a class for the management of memory
*/
class XMemManager
{
private:
    /* cpu memory pool information */
    XMem CPUMems[MAX_CPU_MEM_NUM];

    /* number of cpu memory pools */
    int nCPUMem;

    /* gpu memory pool information */
    XMem GPUMems[MAX_GPU_MEM_NUM];

    /* number of gpu memory pools */
    int nGPUMem;

public:
    /* constructor */
    XMemManager();

    /* de-constructor */
    ~XMemManager();

    /* get memory size */
    MTYPE GetAvailableMemory();

    /* get GPU memory size */
    MTYPE GetAvailableGPUMemory(int devID);

    /* get buffer size */
    void GetBufferSize(MTYPE freeMem, MTYPE * myBufSize);

    /* initialize it and set the global memory information */
    void Initialize();

    /* free it */
    void Free();

    /* get global memory pool */
    XMem * GetMem(const int devID);

    /* get global memory size */
    int GetMemSize(const int devID, MTYPE * myBlockSize, int * myBlockNum, MTYPE * myBufSize);

    /* show memory information */
    void ShowMemInfo();
};

/* managing the memories */
extern XMemManager GMems;

//extern XMem * GMem;

//extern int testxmemid;
//extern void * recordp;
487 488 489 490

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

#endif