dim.h 13.4 KB
Newer Older
朔-望's avatar
朔-望 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
//  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

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <type_traits>

#include "platform/hostdevice.h"

namespace paddle_mobile {
24
    namespace framework {
朔-望's avatar
朔-望 已提交
25

26 27 28
        // Statically sized, statically indexed dimension
        template <int i> struct Dim {
            static constexpr int dimensions = i;
朔-望's avatar
朔-望 已提交
29

30 31 32 33 34 35 36
            template <typename... Args>
            HOSTDEVICE Dim(int64_t _head, Args... _tail)
                : head(_head), tail(_tail...) {
                static_assert(
                    sizeof...(_tail) == i - 1,
                    "Dim initialized with the wrong number of parameters");
            }
朔-望's avatar
朔-望 已提交
37

38 39 40
            HOSTDEVICE
            Dim(int64_t _head, const Dim<i - 1> &_tail)
                : head(_head), tail(_tail) {}
朔-望's avatar
朔-望 已提交
41

42 43
            HOSTDEVICE
            Dim() : head(0), tail() {}
朔-望's avatar
朔-望 已提交
44

45 46 47 48 49 50
            /** Construct a Dim from a linear index and size.  Uses Fortran
             * order
             * indexing. */
            HOSTDEVICE
            Dim(int64_t idx, const Dim<i> &size)
                : head(idx % size.head), tail(idx / size.head, size.tail) {}
朔-望's avatar
朔-望 已提交
51

52 53 54
            /** Construct a Dim with each dimension set to the given index */
            HOSTDEVICE
            Dim(int64_t idx) : head(idx), tail(idx) {}
朔-望's avatar
朔-望 已提交
55

56 57 58 59
            HOSTDEVICE
            bool operator==(const Dim<i> &o) const {
                return (head == o.head) && (tail == o.tail);
            }
朔-望's avatar
朔-望 已提交
60

61 62
            HOSTDEVICE
            bool operator!=(const Dim<i> &o) const { return !(*this == o); }
朔-望's avatar
朔-望 已提交
63

64 65 66 67
            HOSTDEVICE
            int64_t &operator[](int idx);
            HOSTDEVICE
            int64_t operator[](int idx) const;
朔-望's avatar
朔-望 已提交
68

69
            HOST std::string to_string() const;
朔-望's avatar
朔-望 已提交
70

71 72 73
            int64_t head;
            Dim<i - 1> tail;
        };
朔-望's avatar
朔-望 已提交
74

75 76 77
        // Base case specialization
        template <> struct Dim<0> {
            static constexpr int dimensions = 0;
朔-望's avatar
朔-望 已提交
78

79 80
            HOSTDEVICE
            Dim(int64_t _head) {}
朔-望's avatar
朔-望 已提交
81

82 83
            HOSTDEVICE
            Dim() {}
朔-望's avatar
朔-望 已提交
84

85 86
            HOSTDEVICE
            Dim(int idx, const Dim<0> &size) {
朔-望's avatar
朔-望 已提交
87
#ifndef __CUDA_ARCH__
88 89 90
                if (idx > 0) {
                    throw std::invalid_argument("Index out of range.");
                }
朔-望's avatar
朔-望 已提交
91
#else
92
                PADDLE_ASSERT(idx == 0);
朔-望's avatar
朔-望 已提交
93
#endif
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
            }

            HOSTDEVICE
            bool operator==(const Dim<0> &o) const { return true; }

            HOSTDEVICE
            bool operator!=(const Dim<0> &o) const { return false; }

            HOSTDEVICE
            int64_t &operator[](int idx);
            HOSTDEVICE
            int64_t operator[](int idx) const;
        };

        namespace {

            // Helper for accessing Dim classes
            template <int i> struct DimGetter {
                // Return a copy if Dim is const
                template <typename D>
                HOSTDEVICE static int64_t impl(const D &d) {
                    return DimGetter<i - 1>::impl(d.tail);
                }
                // Return a reference if Dim is mutable
                template <typename D> HOSTDEVICE static int64_t &impl(D &d) {
                    return DimGetter<i - 1>::impl(d.tail);
                }
            };

            // Eureka! We found the element!
            template <> struct DimGetter<0> {
                // Return a copy if Dim is const
                template <typename D>
                HOSTDEVICE static int64_t impl(const D &d) {
                    return d.head;
                }
                // Return a reference if Dim is mutable
                template <typename D> HOSTDEVICE static int64_t &impl(D &d) {
                    return d.head;
                }
            };

            template <int D> HOSTDEVICE int64_t &indexer(Dim<D> &dim, int idx) {
朔-望's avatar
朔-望 已提交
137
#ifndef __CUDA_ARCH__
138 139 140 141
                if (idx < 0) {
                    throw std::invalid_argument(
                        "Tried to access a negative dimension");
                }
朔-望's avatar
朔-望 已提交
142
#else
143
                PADDLE_ASSERT(idx >= 0);
朔-望's avatar
朔-望 已提交
144
#endif
145 146 147 148 149
                if (idx == 0) {
                    return dim.head;
                }
                return indexer(dim.tail, idx - 1);
            }
朔-望's avatar
朔-望 已提交
150

151
            template <> HOSTDEVICE int64_t &indexer<0>(Dim<0> &dim, int idx) {
朔-望's avatar
朔-望 已提交
152
#ifndef __CUDA_ARCH__
153
                throw std::invalid_argument("Invalid index");
朔-望's avatar
朔-望 已提交
154
#else
155
                PADDLE_ASSERT(false);
朔-望's avatar
朔-望 已提交
156
#if CUDA_VERSION < 8000
157 158 159
                // On CUDA versions previous to 8.0, only __shared__ variables
                // could be declared as static in the device code.
                int64_t head = 0;
朔-望's avatar
朔-望 已提交
160
#else
161
                static int64_t head = 0;
朔-望's avatar
朔-望 已提交
162
#endif
163
                return head;
朔-望's avatar
朔-望 已提交
164
#endif
165
            }
朔-望's avatar
朔-望 已提交
166

167 168
            template <int D>
            HOSTDEVICE int64_t indexer(const Dim<D> &dim, int idx) {
朔-望's avatar
朔-望 已提交
169
#ifndef __CUDA_ARCH__
170 171 172 173
                if (idx < 0) {
                    throw std::invalid_argument(
                        "Tried to access a negative dimension");
                }
朔-望's avatar
朔-望 已提交
174
#else
175
                PADDLE_ASSERT(idx >= 0);
朔-望's avatar
朔-望 已提交
176
#endif
177 178 179 180 181 182 183 184
                if (idx == 0) {
                    return dim.head;
                }
                return indexer(dim.tail, idx - 1);
            }

            template <>
            HOSTDEVICE int64_t indexer<0>(const Dim<0> &dim, int idx) {
朔-望's avatar
朔-望 已提交
185
#ifndef __CUDA_ARCH__
186
                throw std::invalid_argument("Invalid index");
朔-望's avatar
朔-望 已提交
187
#else
188
                PADDLE_ASSERT(false);
朔-望's avatar
朔-望 已提交
189
#if CUDA_VERSION < 8000
190 191 192
                // On CUDA versions previous to 8.0, only __shared__ variables
                // could be declared as static in the device code.
                int64_t head = 0;
朔-望's avatar
朔-望 已提交
193
#else
194
                static int64_t head = 0;
朔-望's avatar
朔-望 已提交
195
#endif
196
                return head;
朔-望's avatar
朔-望 已提交
197
#endif
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 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
            }

        } // namespace
        // Static access to constant Dim
        template <int i, int l> HOSTDEVICE int64_t get(const Dim<l> &d) {
            return DimGetter<i>::impl(d);
        }

        // Static access to mutable Dim
        template <int i, int l> HOSTDEVICE int64_t &get(Dim<l> &d) {
            return DimGetter<i>::impl(d);
        }

        // Dynamic access to constant Dim
        template <int l> HOSTDEVICE int64_t Dim<l>::operator[](int i) const {
            //  std::cout << "l: " << l << std::endl;
            return indexer(*this, i);
        }

        // Dynamic access to mutable Dim
        template <int l> HOSTDEVICE int64_t &Dim<l>::operator[](int i) {
            return indexer(*this, i);
        }

        // Dynamic access to constant Dim
        inline HOSTDEVICE int64_t Dim<0>::operator[](int i) const {
            return indexer(*this, i);
        }

        // Dynamic access to mutable Dim
        inline HOSTDEVICE int64_t &Dim<0>::operator[](int i) {
            return indexer(*this, i);
        }

        // Dynamic access to constant Dim
        // without std::enable_if will try to instantiate this on get<0>(d)
        template <int l>
        HOSTDEVICE typename std::enable_if<(l > 0), int64_t>::type
        get(const Dim<l> &d, int i) {
            return d[i];
        }

        // Dynamic access to mutable Dim
        template <int l>
        HOSTDEVICE typename std::enable_if<(l > 0), int64_t &>::type
        get(Dim<l> &d, int i) {
            return d[i];
        }

        // Dot product of two dims
        template <int i>
        HOSTDEVICE int64_t linearize(const Dim<i> &a, const Dim<i> &b) {
            return a.head * b.head + linearize(a.tail, b.tail);
        }

        // Base case dot product of two Dims
        // Notice it is inline because it is no longer a template
        template <>
        HOSTDEVICE inline int64_t linearize(const Dim<0> &a, const Dim<0> &b) {
            return 0;
        }

        // Product of a Dim
        template <int i>
        HOSTDEVICE int64_t product(const Dim<i> &a, int prod = 1) {
            return prod * a.head * product(a.tail);
        }

        // Base case product of a Dim
        // Notice it is inline because it is no longer a template
        template <>
        HOSTDEVICE inline int64_t product(const Dim<0> &a, int prod) {
            return prod;
        }

        // Is 0 <= idx_i < size_i for all i?
        template <int i>
        HOSTDEVICE bool contained(const Dim<i> &idx, const Dim<i> &size) {
            return ((0 <= idx.head) && (idx.head < size.head) &&
                    contained(idx.tail, size.tail));
        }

        // Base case of is 0 <= idx_i < size_i ?
        // Notice it is inline because it is no longer a template
        template <>
        HOSTDEVICE inline bool contained(const Dim<0> &idx,
                                         const Dim<0> &size) {
            return true;
        }

        /**
         * \brief Compute exclusive prefix-multiply of a Dim.
         */
        template <int i>
        HOSTDEVICE Dim<i> ex_prefix_mul(const Dim<i> &src, int mul = 1) {
            return Dim<i>(mul, ex_prefix_mul(src.tail, mul * src.head));
        }

        ///\cond HIDDEN
        // Base case of ex_prefix_mul
        // Notice it is inline because it is no longer a template
        template <>
        HOSTDEVICE inline Dim<0> ex_prefix_mul(const Dim<0> &src, int mul) {
            return Dim<0>();
        }
        ///\endcond

        /**
         * Add two dimensions together
         */
        template <int i>
        HOSTDEVICE Dim<i> dim_plus(const Dim<i> &a, const Dim<i> &b) {
            return Dim<i>(a.head + b.head, dim_plus(a.tail, b.tail));
        }

        // Base case
        template <>
        HOSTDEVICE inline Dim<0> dim_plus(const Dim<0> &a, const Dim<0> &b) {
            return Dim<0>();
        }

        template <int i>
        HOSTDEVICE Dim<i> operator+(const Dim<i> &lhs, const Dim<i> &rhs) {
            return dim_plus(lhs, rhs);
        }

        /**
         * Multiply two dimensions together
         */
        template <int i>
        HOSTDEVICE Dim<i> dim_mult(const Dim<i> &a, const Dim<i> &b) {
            return Dim<i>(a.head * b.head, dim_mult(a.tail, b.tail));
        }

        // Base case
        template <>
        HOSTDEVICE inline Dim<0> dim_mult(const Dim<0> &a, const Dim<0> &b) {
            return Dim<0>();
        }

        template <int i>
        HOSTDEVICE Dim<i> operator*(const Dim<i> &lhs, const Dim<i> &rhs) {
            return dim_mult(lhs, rhs);
        }

        /**
         * \brief Normalize strides to ensure any dimension with extent 1
         * has stride 0.
         *
         * \param size Dim object containing the size of an array
         * \param stride Dim object containing stride of an array
         * \return Dim object the same size as \p size with normalized strides
         *
         */

        template <int i>
        HOSTDEVICE Dim<i> normalize_strides(const Dim<i> &size,
                                            const Dim<i> &stride) {
            int norm_stride = size.head == 1 ? 0 : stride.head;
            return Dim<i>(norm_stride,
                          normalize_strides(size.tail, stride.tail));
        }

        ///\cond HIDDEN

        template <>
        HOSTDEVICE inline Dim<0> normalize_strides(const Dim<0> &size,
                                                   const Dim<0> &stride) {
            return Dim<0>();
        }

        ///\endcond

        /**
         * Helper function to create a Dim
         *
         * \param idxes The type of Dim constructed depends on the number of
         * params
         *
         */

        template <typename... Args>
        HOSTDEVICE Dim<sizeof...(Args)> make_dim(Args... idxes) {
            return Dim<sizeof...(Args)>(idxes...);
        }

        // Allows us to output a Dim
        // XXX For some reason, overloading fails to resolve this correctly
        template <int i>
        typename std::enable_if<(i > 1), std::ostream &>::type
        operator<<(std::ostream &os, const Dim<i> &d) {
            os << d.head << ", " << d.tail;
            return os;
        }

        // Base case that allows us to output a Dim
        // XXX I wish this could be an overload instead of a template
        template <int i>
        typename std::enable_if<(i == 1), std::ostream &>::type
        operator<<(std::ostream &os, const Dim<i> &d) {
            os << d.head;
            return os;
        }

        inline std::ostream &operator<<(std::ostream &os, const Dim<0> &d) {
            return os;
        }

        template <int i> HOST std::string Dim<i>::to_string() const {
            std::stringstream stream;

            stream << *this;

            return stream.str();
        }

        template <int D>
        HOSTDEVICE Dim<D> linear_to_dimension(int linear_index,
                                              Dim<D> extents) {
            Dim<D> result;

            for (int i = 0; i < D - 1; ++i) {
                result[i] = linear_index % extents[i];
                linear_index /= extents[i];
            }

            result[D - 1] = linear_index;

            return result;
        }

    } // namespace framework
L
liuruilong 已提交
430
} // namespace paddle_mobile