random_crop_op.h 7.7 KB
Newer Older
Y
yuyang18 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright (c) 2018 PaddlePaddle Authors. 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.

#pragma once

F
stash  
fengjiayi 已提交
17
#include <vector>
18

Y
yuyang18 已提交
19 20 21
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/for_range.h"
22
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
F
stash  
fengjiayi 已提交
23 24
#include <thrust/random.h>
#endif
Y
yuyang18 已提交
25 26 27 28 29 30 31 32

namespace paddle {
namespace operators {

template <typename DeviceContext>
struct Random;

template <>
L
Leo Chen 已提交
33
struct Random<phi::CPUContext> {
Y
yuyang18 已提交
34 35 36 37 38 39
  using Engine = std::minstd_rand;

  template <typename T>
  using UniformIntDist = std::uniform_int_distribution<T>;
};

40
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
Y
yuyang18 已提交
41
template <>
L
Leo Chen 已提交
42
struct Random<phi::GPUContext> {
Y
yuyang18 已提交
43 44 45 46 47
  using Engine = thrust::minstd_rand;

  template <typename T>
  using UniformIntDist = thrust::uniform_int_distribution<T>;
};
F
stash  
fengjiayi 已提交
48
#endif
Y
yuyang18 已提交
49 50

template <typename T>
51 52 53 54 55 56
HOSTDEVICE inline void StridedMemcpy(const T* x,
                                     const size_t* x_dims,
                                     T* out,
                                     const size_t* out_dims,
                                     int i,
                                     int rank,
F
stash  
fengjiayi 已提交
57 58 59 60 61 62 63 64 65 66
                                     size_t prod_x_remain,
                                     size_t prod_out_remain,
                                     const size_t* offsets) {
  size_t x_dim_i = x_dims[i];
  size_t out_dim_i = out_dims[i];
  size_t x_stride = prod_x_remain / x_dim_i;
  size_t out_stride = prod_out_remain / out_dim_i;
  size_t offset_i = offsets[i];

  if (i == rank - 1) {
Y
yuyang18 已提交
67
    x += offset_i;
F
stash  
fengjiayi 已提交
68
    for (size_t j = 0; j < out_dim_i; ++j) {
Y
yuyang18 已提交
69 70 71 72
      *out++ = *x++;
    }
  } else {
    x += offset_i * x_stride;
Y
yuyang18 已提交
73
    for (size_t j = 0; j < out_dim_i; ++j) {
74 75
      StridedMemcpy<T>(
          x, x_dims, out, out_dims, i + 1, rank, x_stride, out_stride, offsets);
Y
yuyang18 已提交
76 77 78 79 80 81 82 83 84 85
      x += x_stride;
      out += out_stride;
    }
  }
}

template <typename DeviceContext, typename T>
struct RandomCropFunctor {
  const T* x_;
  T* out_;
F
stash  
fengjiayi 已提交
86 87 88
  size_t x_dims_[9];
  size_t out_dims_[9];
  int num_batchsize_dims_;
Y
yuyang18 已提交
89 90 91
  int rank_;
  int64_t seed_;

F
stash  
fengjiayi 已提交
92 93 94 95
  size_t prod_batchsize_dims_;
  size_t prod_x_ins_dims_;
  size_t prod_out_ins_dims_;

96 97 98 99 100
  RandomCropFunctor(const T* x,
                    T* out,
                    const framework::DDim& x_dims,
                    const framework::DDim& out_dims,
                    int num_batchsize_dims,
F
stash  
fengjiayi 已提交
101
                    int64_t seed)
Y
yuyang18 已提交
102 103
      : x_(x),
        out_(out),
F
stash  
fengjiayi 已提交
104 105
        num_batchsize_dims_(num_batchsize_dims),
        rank_(x_dims.size()),
Y
yuyang18 已提交
106
        seed_(seed) {
107
    PADDLE_ENFORCE_EQ(
108 109
        x_dims.size(),
        out_dims.size(),
110 111 112 113
        platform::errors::InvalidArgument(
            "The dimensions of Input(X) must equal to be the dimensions"
            "of Output(Out), but received dimensions of Input(X) is [%d],"
            "received dimensions of Output(Out) is [%d].",
114 115
            x_dims.size(),
            out_dims.size()));
116
    PADDLE_ENFORCE_GT(
117 118
        rank_,
        num_batchsize_dims_,
119 120 121 122 123
        platform::errors::InvalidArgument(
            "The dimensions of Input(X) must be greater than the diff"
            "value of Input(X)'s dimensions minus Atrr(shape)'s dimensions,"
            "But received Input(X)'s dimensions is [%d], received value of"
            "Input(X)'s dimensions minus Attr(shape)'s dimensions is [%d].",
124 125
            rank_,
            num_batchsize_dims_));
F
stash  
fengjiayi 已提交
126 127 128
    prod_batchsize_dims_ = 1;
    prod_x_ins_dims_ = 1;
    prod_out_ins_dims_ = 1;
Y
yuyang18 已提交
129
    for (size_t i = 0; i < static_cast<size_t>(rank_); ++i) {
F
stash  
fengjiayi 已提交
130 131 132 133
      size_t x_dim_i = x_dims[i];
      size_t out_dim_i = out_dims[i];
      x_dims_[i] = x_dim_i;
      out_dims_[i] = out_dim_i;
Y
yuyang18 已提交
134
      if (i < static_cast<size_t>(num_batchsize_dims_)) {
135
        PADDLE_ENFORCE_EQ(
136 137
            x_dim_i,
            out_dim_i,
138 139 140 141
            platform::errors::InvalidArgument(
                "The first [%d] dimension value of Input(X) and Output(Out)"
                "must be equal, but received the [%d] dimension value of"
                "Input(X) and Output(Out) respectively are [%d] and [%d].",
142 143 144 145
                num_batchsize_dims_,
                i,
                x_dim_i,
                out_dim_i));
F
stash  
fengjiayi 已提交
146 147 148 149 150 151
        prod_batchsize_dims_ *= x_dim_i;
      } else {
        prod_x_ins_dims_ *= x_dim_i;
        prod_out_ins_dims_ *= out_dim_i;
      }
    }
Y
yuyang18 已提交
152 153
  }

F
stash  
fengjiayi 已提交
154
  HOSTDEVICE void operator()(size_t ins_idx) {
Y
yuyang18 已提交
155
    typename Random<DeviceContext>::Engine engine(seed_);
F
stash  
fengjiayi 已提交
156
    engine.discard(ins_idx * (rank_ - num_batchsize_dims_));
157
    size_t offsets[9] = {};
F
stash  
fengjiayi 已提交
158
    for (int i = num_batchsize_dims_; i < rank_; ++i) {
Y
yuyang18 已提交
159
      typename Random<DeviceContext>::template UniformIntDist<size_t> dist(
F
stash  
fengjiayi 已提交
160
          0, x_dims_[i] - out_dims_[i]);
F
fengjiayi 已提交
161
      offsets[i - num_batchsize_dims_] = dist(engine);
Y
yuyang18 已提交
162
    }
F
stash  
fengjiayi 已提交
163 164 165 166

    const T* x = x_ + ins_idx * prod_x_ins_dims_;
    T* out = out_ + ins_idx * prod_out_ins_dims_;

167 168 169 170 171 172 173 174 175
    StridedMemcpy<T>(x,
                     x_dims_ + num_batchsize_dims_,
                     out,
                     out_dims_ + num_batchsize_dims_,
                     0,
                     rank_ - num_batchsize_dims_,
                     prod_x_ins_dims_,
                     prod_out_ins_dims_,
                     offsets);
Y
yuyang18 已提交
176 177 178
  }
};

Y
YuanRisheng 已提交
179
template <typename T, typename DeviceContext>
Y
yuyang18 已提交
180 181
class RandomCropKernel : public framework::OpKernel<T> {
 public:
F
stash  
fengjiayi 已提交
182
  virtual void Compute(const framework::ExecutionContext& ctx) const {
Y
yuyang18 已提交
183
    int64_t seed = 0;
184
    auto& seed_tensor = GET_DATA_SAFELY(
185
        ctx.Input<phi::DenseTensor>("Seed"), "Input", "Seed", "RandomCrop");
F
fengjiayi 已提交
186 187
    if (seed_tensor.IsInitialized()) {
      if (platform::is_cpu_place(seed_tensor.place())) {
188
        seed = *seed_tensor.template data<int64_t>();
F
fengjiayi 已提交
189 190 191
      } else {
        LOG(WARNING) << "It is slow to place seed in GPU memory. Please verify "
                        "your program";
192
        phi::DenseTensor cpu_seed;
F
fengjiayi 已提交
193 194 195
        framework::TensorCopySync(seed_tensor, platform::CPUPlace(), &cpu_seed);
        seed = *cpu_seed.data<int64_t>();
      }
Y
yuyang18 已提交
196
    } else {
M
minqiyang 已提交
197 198
      VLOG(5) << "WARNING: The input 'Seed' is not initialized, use attribute "
                 "'startup_seed' instead.";
F
fengjiayi 已提交
199
      seed = ctx.Attr<int>("startup_seed");
Y
yuyang18 已提交
200
    }
F
stash  
fengjiayi 已提交
201
    auto shape = ctx.Attr<std::vector<int>>("shape");
202
    auto& x = GET_DATA_SAFELY(
203
        ctx.Input<phi::DenseTensor>("X"), "Input", "X", "RandomCrop");
204
    auto& out = GET_DATA_SAFELY(
205
        ctx.Output<phi::DenseTensor>("Out"), "Output", "Out", "RandomCrop");
F
stash  
fengjiayi 已提交
206 207 208

    int num_batchsize_dims = x.dims().size() - shape.size();
    RandomCropFunctor<DeviceContext, T> functor(
209 210 211 212 213 214
        x.template data<T>(),
        out.template mutable_data<T>(ctx.GetPlace()),
        x.dims(),
        out.dims(),
        num_batchsize_dims,
        seed);
Y
yuyang18 已提交
215
    platform::ForRange<DeviceContext> for_range(
F
stash  
fengjiayi 已提交
216 217
        ctx.template device_context<DeviceContext>(),
        functor.prod_batchsize_dims_);
Y
yuyang18 已提交
218 219 220

    for_range(functor);

L
Leo Chen 已提交
221
    Random<phi::CPUContext>::Engine engine(seed);
F
stash  
fengjiayi 已提交
222 223
    engine.discard(functor.prod_batchsize_dims_ *
                   (functor.rank_ - functor.num_batchsize_dims_));
224
    *ctx.Output<phi::DenseTensor>("SeedOut")->mutable_data<int64_t>(
225
        phi::make_ddim({1}), platform::CPUPlace()) = engine();
Y
yuyang18 已提交
226 227 228
  }
};

F
stash  
fengjiayi 已提交
229 230
// TODO(fengjiayi): Backward of random crop op

Y
yuyang18 已提交
231 232
}  // namespace operators
}  // namespace paddle