hl_cuda_sequence.cu 13.2 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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. */

#include "hl_base.h"
#include "hl_device_functions.cuh"
X
Xin Pan 已提交
17
#include "paddle/legacy/utils/Logging.h"
Z
zhangjinchao01 已提交
18

L
liaogang 已提交
19 20
__global__ void KeMaxSequenceForward(real* input,
                                     const int* sequence,
Z
zhangjinchao01 已提交
21
                                     real* output,
L
liaogang 已提交
22
                                     int* index,
Z
zhangjinchao01 已提交
23 24 25 26 27 28
                                     int numSequences,
                                     int dim) {
  int dimIdx = threadIdx.x;
  int sequenceId = blockIdx.x;
  if (sequenceId >= numSequences) return;
  int start = sequence[sequenceId];
L
liaogang 已提交
29
  int end = sequence[sequenceId + 1];
Z
zhangjinchao01 已提交
30 31 32 33 34

  for (int i = dimIdx; i < dim; i += blockDim.x) {
    real tmp = -HL_FLOAT_MAX;
    int tmpId = -1;
    for (int insId = start; insId < end; insId++) {
L
liaogang 已提交
35 36
      if (tmp < input[insId * dim + i]) {
        tmp = input[insId * dim + i];
Z
zhangjinchao01 已提交
37 38 39
        tmpId = insId;
      }
    }
L
liaogang 已提交
40 41
    output[sequenceId * dim + i] = tmp;
    index[sequenceId * dim + i] = tmpId;
Z
zhangjinchao01 已提交
42 43 44 45 46 47
  }
}

void hl_max_sequence_forward(real* input,
                             const int* sequence,
                             real* output,
L
liaogang 已提交
48
                             int* index,
Z
zhangjinchao01 已提交
49 50 51 52 53 54 55 56 57
                             int numSequences,
                             int dim) {
  CHECK_NOTNULL(input);
  CHECK_NOTNULL(sequence);
  CHECK_NOTNULL(output);
  CHECK_NOTNULL(index);

  dim3 threads(256, 1);
  dim3 grid(numSequences, 1);
L
liaogang 已提交
58 59
  KeMaxSequenceForward<<<grid, threads, 0, STREAM_DEFAULT>>>(
      input, sequence, output, index, numSequences, dim);
Z
zhangjinchao01 已提交
60 61 62
  CHECK_SYNC("hl_max_sequence_forward failed");
}

L
liaogang 已提交
63 64
__global__ void KeMaxSequenceBackward(
    real* outputGrad, int* index, real* inputGrad, int numSequences, int dim) {
Z
zhangjinchao01 已提交
65 66
  int idx = threadIdx.x + blockIdx.x * blockDim.x;
  int colIdx = idx % dim;
L
liaogang 已提交
67
  if (idx < numSequences * dim) {
Z
zhangjinchao01 已提交
68 69 70 71 72
    int insId = index[idx];
    inputGrad[insId * dim + colIdx] += outputGrad[idx];
  }
}

L
liaogang 已提交
73 74
void hl_max_sequence_backward(
    real* outputGrad, int* index, real* inputGrad, int numSequences, int dim) {
Z
zhangjinchao01 已提交
75 76 77 78 79 80 81
  CHECK_NOTNULL(outputGrad);
  CHECK_NOTNULL(index);
  CHECK_NOTNULL(inputGrad);

  unsigned int blocks = (numSequences * dim + 128 - 1) / 128;
  dim3 threads(128, 1);
  dim3 grid(blocks, 1);
L
liaogang 已提交
82 83
  KeMaxSequenceBackward<<<grid, threads, 0, STREAM_DEFAULT>>>(
      outputGrad, index, inputGrad, numSequences, dim);
Z
zhangjinchao01 已提交
84 85 86
  CHECK_SYNC("hl_max_sequence_backward failed");
}

L
liaogang 已提交
87
template <int blockDimX, int blockDimY, int gridDimX, bool AddRow>
Z
zhangjinchao01 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100
__global__ void KeMatrixAddRows(real* output,
                                real* table,
                                int* ids,
                                int numSamples,
                                int tableSize,
                                int dim) {
  int idx = threadIdx.x;
  int idy = threadIdx.y;
  int sampleId = blockIdx.x + idy * gridDimX;

  while (sampleId < numSamples) {
    int tableId = ids[sampleId];
    if ((0 <= tableId) && (tableId < tableSize)) {
L
liaogang 已提交
101 102
      real* outputData = output + sampleId * dim;
      real* tableData = table + tableId * dim;
Z
zhangjinchao01 已提交
103 104 105 106
      for (int i = idx; i < dim; i += blockDimX) {
        if (AddRow == 0) {
          outputData[i] += tableData[i];
        } else {
107
          paddle::paddleAtomicAdd(&tableData[i], outputData[i]);
Z
zhangjinchao01 已提交
108 109 110
        }
      }
    }
L
liaogang 已提交
111
    sampleId += blockDimY * gridDimX;
Z
zhangjinchao01 已提交
112 113 114
  }
}

L
liaogang 已提交
115 116 117 118 119 120 121 122 123 124
template <int blockDimX,
          int blockDimY,
          int gridDimX,
          bool seq2batch,
          bool isAdd>
__global__ void KeSequence2Batch(real* batch,
                                 real* sequence,
                                 const int* batchIndex,
                                 int seqWidth,
                                 int batchCount) {
Z
zhangjinchao01 已提交
125 126 127 128 129
  int idx = threadIdx.x;
  int idy = threadIdx.y;
  int id = blockIdx.x + idy * gridDimX;
  while (id < batchCount) {
    int seqId = batchIndex[id];
L
liaogang 已提交
130 131
    real* batchData = batch + id * seqWidth;
    real* seqData = sequence + seqId * seqWidth;
Z
zhangjinchao01 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    for (int i = idx; i < seqWidth; i += blockDimX) {
      if (seq2batch) {
        if (isAdd) {
          batchData[i] += seqData[i];
        } else {
          batchData[i] = seqData[i];
        }
      } else {
        if (isAdd) {
          seqData[i] += batchData[i];
        } else {
          seqData[i] = batchData[i];
        }
      }
    }
L
liaogang 已提交
147
    id += blockDimY * gridDimX;
Z
zhangjinchao01 已提交
148 149 150
  }
}

L
liaogang 已提交
151 152 153
void hl_sequence2batch_copy(real* batch,
                            real* sequence,
                            const int* batchIndex,
Z
zhangjinchao01 已提交
154 155 156 157 158 159 160 161 162 163
                            int seqWidth,
                            int batchCount,
                            bool seq2batch) {
  CHECK_NOTNULL(sequence);
  CHECK_NOTNULL(batch);
  CHECK_NOTNULL(batchIndex);

  dim3 threads(128, 8);
  dim3 grid(8, 1);
  if (seq2batch) {
L
liaogang 已提交
164 165
    KeSequence2Batch<128, 8, 8, 1, 0><<<grid, threads, 0, STREAM_DEFAULT>>>(
        batch, sequence, batchIndex, seqWidth, batchCount);
Z
zhangjinchao01 已提交
166
  } else {
L
liaogang 已提交
167 168
    KeSequence2Batch<128, 8, 8, 0, 0><<<grid, threads, 0, STREAM_DEFAULT>>>(
        batch, sequence, batchIndex, seqWidth, batchCount);
Z
zhangjinchao01 已提交
169 170 171 172
  }
  CHECK_SYNC("hl_sequence2batch_copy failed");
}

L
liaogang 已提交
173 174 175
void hl_sequence2batch_add(real* batch,
                           real* sequence,
                           int* batchIndex,
Z
zhangjinchao01 已提交
176 177 178 179 180 181 182 183 184 185
                           int seqWidth,
                           int batchCount,
                           bool seq2batch) {
  CHECK_NOTNULL(sequence);
  CHECK_NOTNULL(batch);
  CHECK_NOTNULL(batchIndex);

  dim3 threads(128, 8);
  dim3 grid(8, 1);
  if (seq2batch) {
L
liaogang 已提交
186 187
    KeSequence2Batch<128, 8, 8, 1, 1><<<grid, threads, 0, STREAM_DEFAULT>>>(
        batch, sequence, batchIndex, seqWidth, batchCount);
Z
zhangjinchao01 已提交
188
  } else {
L
liaogang 已提交
189 190
    KeSequence2Batch<128, 8, 8, 0, 1><<<grid, threads, 0, STREAM_DEFAULT>>>(
        batch, sequence, batchIndex, seqWidth, batchCount);
Z
zhangjinchao01 已提交
191 192 193 194
  }
  CHECK_SYNC("hl_sequence2batch_add failed");
}

L
liaogang 已提交
195 196 197 198 199 200 201
template <bool normByTimes, bool seq2batch>
__global__ void KeSequence2BatchPadding(real* batch,
                                        real* sequence,
                                        const int* sequenceStartPositions,
                                        const size_t sequenceWidth,
                                        const size_t maxSequenceLength,
                                        const size_t numSequences) {
202 203 204 205 206 207 208 209
  int batchIdx = blockIdx.y;
  int sequenceStart = sequenceStartPositions[batchIdx];
  int sequenceLength = sequenceStartPositions[batchIdx + 1] - sequenceStart;

  int sequenceIdx = blockIdx.x * blockDim.y + threadIdx.y;
  int batchBaseIdx = (sequenceIdx * numSequences + batchIdx) * sequenceWidth;
  int sequenceBaseIdx = (sequenceStart + sequenceIdx) * sequenceWidth;

L
Liu Yiqun 已提交
210 211
  real scale = normByTimes ? (1.0f / (real)sequenceLength) : 1.0f;

212 213 214
  if (sequenceIdx < sequenceLength) {
    if (seq2batch) {
      /* sequence -> batch */
L
Liu Yiqun 已提交
215 216
      for (int i = threadIdx.x; i < sequenceWidth; i += blockDim.x) {
        batch[batchBaseIdx + i] = scale * sequence[sequenceBaseIdx + i];
217 218 219
      }
    } else {
      /* batch -> sequence */
L
Liu Yiqun 已提交
220 221
      for (int i = threadIdx.x; i < sequenceWidth; i += blockDim.x) {
        sequence[sequenceBaseIdx + i] = scale * batch[batchBaseIdx + i];
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
      }
    }
  } else if (sequenceIdx < maxSequenceLength) {
    if (seq2batch) {
      /* sequence -> batch */
      for (int i = threadIdx.x; i < sequenceWidth; i += blockDim.x) {
        batch[batchBaseIdx + i] = 0;
      }
    }
  }
}

void hl_sequence2batch_copy_padding(real* batch,
                                    real* sequence,
                                    const int* sequenceStartPositions,
                                    const size_t sequenceWidth,
                                    const size_t maxSequenceLength,
                                    const size_t numSequences,
                                    bool normByTimes,
                                    bool seq2batch) {
  CHECK_NOTNULL(batch);
  CHECK_NOTNULL(sequence);
  CHECK_NOTNULL(sequenceStartPositions);

  if (!normByTimes && numSequences == 1) {
    size_t elementCount = maxSequenceLength * sequenceWidth;
    if (seq2batch) {
      /* sequence -> batch */
      hl_memcpy_device2device(batch, sequence, sizeof(real) * elementCount);
    } else {
      /* batch -> sequence */
      hl_memcpy_device2device(sequence, batch, sizeof(real) * elementCount);
    }
    return;
  }

  const int CUDA_BLOCK_SIZE = 512;

  /* At least use 32 threads to copy sequenceWidth elements,
     and at least 8 elements for each thread. */
  int blockDimX = ((((sequenceWidth + 7) >> 3) + 31) >> 5) << 5;
  blockDimX = (blockDimX < CUDA_BLOCK_SIZE) ? blockDimX : CUDA_BLOCK_SIZE;

  int blockDimY = CUDA_BLOCK_SIZE / blockDimX;
  dim3 threads(blockDimX, blockDimY);

D
dangqingqing 已提交
268
  int gridDimX = (maxSequenceLength + blockDimY - 1) / blockDimY;
269 270 271 272 273 274
  int gridDimY = numSequences;
  dim3 grid(gridDimX, gridDimY);

  if (seq2batch) {
    /* sequence -> batch */
    if (normByTimes) {
L
liaogang 已提交
275 276 277 278 279 280 281
      KeSequence2BatchPadding<1, 1><<<grid, threads, 0, STREAM_DEFAULT>>>(
          batch,
          sequence,
          sequenceStartPositions,
          sequenceWidth,
          maxSequenceLength,
          numSequences);
282
    } else {
L
liaogang 已提交
283 284 285 286 287 288 289
      KeSequence2BatchPadding<0, 1><<<grid, threads, 0, STREAM_DEFAULT>>>(
          batch,
          sequence,
          sequenceStartPositions,
          sequenceWidth,
          maxSequenceLength,
          numSequences);
290 291 292 293
    }
  } else {
    /* batch -> sequence */
    if (normByTimes) {
L
liaogang 已提交
294 295 296 297 298 299 300
      KeSequence2BatchPadding<1, 0><<<grid, threads, 0, STREAM_DEFAULT>>>(
          batch,
          sequence,
          sequenceStartPositions,
          sequenceWidth,
          maxSequenceLength,
          numSequences);
301
    } else {
L
liaogang 已提交
302 303 304 305 306 307 308
      KeSequence2BatchPadding<0, 0><<<grid, threads, 0, STREAM_DEFAULT>>>(
          batch,
          sequence,
          sequenceStartPositions,
          sequenceWidth,
          maxSequenceLength,
          numSequences);
309 310 311 312 313 314
    }
  }

  CHECK_SYNC("hl_sequence2batch_copy_padding failed");
}

L
liaogang 已提交
315
__device__ inline float my_rsqrt(float x) { return rsqrtf(x); }
Z
zhangjinchao01 已提交
316

L
liaogang 已提交
317
__device__ inline double my_rsqrt(double x) { return rsqrt(x); }
Z
zhangjinchao01 已提交
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

__global__ void KeSequenceAvgForward(real* dst,
                                     real* src,
                                     const int* starts,
                                     int height,
                                     int width,
                                     const int mode) {
  int gid = blockIdx.x * blockDim.x + threadIdx.x;
  int row = gid / width;
  int col = gid % width;

  if (gid < height * width) {
    int start = starts[row];
    int end = starts[row + 1];
    int seqLength = end - start;
    if (seqLength == 0) return;
    real sum = 0.0;
L
Luo Tao 已提交
335 336
    for (int i = start; i < end; i++) {
      sum += src[i * width + col];
Z
zhangjinchao01 已提交
337
    }
L
liaogang 已提交
338 339
    sum = mode == 1 ? sum : (mode == 0 ? sum / seqLength
                                       : sum * my_rsqrt((real)seqLength));
H
hedaoyuan 已提交
340
    dst[gid] += sum;
Z
zhangjinchao01 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  }
}

void hl_sequence_avg_forward(real* dst,
                             real* src,
                             const int* starts,
                             int height,
                             int width,
                             const int mode) {
  CHECK_NOTNULL(dst);
  CHECK_NOTNULL(src);
  CHECK_NOTNULL(starts);

  int block = 512;
  int grid = DIVUP(width * height, 512);

  CHECK(mode == 0 || mode == 1 || mode == 2)
L
liaogang 已提交
358
      << "mode error in hl_sequence_avg_forward!";
Z
zhangjinchao01 已提交
359

L
liaogang 已提交
360 361
  KeSequenceAvgForward<<<grid, block, 0, STREAM_DEFAULT>>>(
      dst, src, starts, height, width, mode);
Z
zhangjinchao01 已提交
362 363
  CHECK_SYNC("hl_sequence_avg_forward failed");
}
L
Luo Tao 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

__global__ void KeSequenceAvgBackward(real* dst,
                                      real* src,
                                      const int* starts,
                                      int height,
                                      int width,
                                      const int mode) {
  int gid = blockIdx.x * blockDim.x + threadIdx.x;
  int row = gid / width;
  int col = gid % width;

  if (gid < height * width) {
    int start = starts[row];
    int end = starts[row + 1];
    int seqLength = end - start;
    if (seqLength == 0) return;
    real grad = src[gid];
L
liaogang 已提交
381 382
    grad = mode == 1 ? grad : (mode == 0 ? grad / seqLength
                                         : grad * my_rsqrt((real)seqLength));
L
Luo Tao 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    for (int i = start; i < end; i++) {
      dst[i * width + col] += grad;
    }
  }
}

void hl_sequence_avg_backward(real* dst,
                              real* src,
                              const int* starts,
                              int height,
                              int width,
                              const int mode) {
  CHECK_NOTNULL(dst);
  CHECK_NOTNULL(src);
  CHECK_NOTNULL(starts);

  int block = 512;
  int grid = DIVUP(width * height, 512);

  CHECK(mode == 0 || mode == 1 || mode == 2)
L
liaogang 已提交
403
      << "mode error in hl_sequence_avg_backward!";
L
Luo Tao 已提交
404

L
liaogang 已提交
405 406
  KeSequenceAvgBackward<<<grid, block, 0, STREAM_DEFAULT>>>(
      dst, src, starts, height, width, mode);
L
Luo Tao 已提交
407 408
  CHECK_SYNC("hl_sequence_avg_backward failed");
}