host_tensor.hpp 8.7 KB
Newer Older
Chao Liu's avatar
Chao Liu committed
1
2
#ifndef HOST_TENSOR_HPP
#define HOST_TENSOR_HPP
3

Chao Liu's avatar
Chao Liu committed
4
5
6
#include <thread>
#include <vector>
#include <numeric>
Chao Liu's avatar
Chao Liu committed
7
#include <algorithm>
Chao Liu's avatar
Chao Liu committed
8
#include <utility>
Chao Liu's avatar
Chao Liu committed
9
10
#include <cassert>
#include <iostream>
Chao Liu's avatar
Chao Liu committed
11

zjing14's avatar
zjing14 committed
12
template <typename Range>
Chao Liu's avatar
Chao Liu committed
13
std::ostream& LogRange(std::ostream& os, Range&& range, std::string delim)
Chao Liu's avatar
Chao Liu committed
14
15
{
    bool first = true;
Chao Liu's avatar
Chao Liu committed
16
    for(auto&& v : range)
Chao Liu's avatar
Chao Liu committed
17
18
19
20
21
    {
        if(first)
            first = false;
        else
            os << delim;
Chao Liu's avatar
Chao Liu committed
22
        os << v;
Chao Liu's avatar
Chao Liu committed
23
24
25
26
    }
    return os;
}

zjing14's avatar
zjing14 committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
template <typename T, typename Range>
std::ostream& LogRangeAsType(std::ostream& os, Range&& range, std::string delim)
{
    bool first = true;
    for(auto&& v : range)
    {
        if(first)
            first = false;
        else
            os << delim;
        os << T{v};
    }
    return os;
}

Chao Liu's avatar
Chao Liu committed
42
typedef enum {
Chao Liu's avatar
Chao Liu committed
43
44
45
46
    Half  = 0,
    Float = 1,
} DataType_t;

zjing14's avatar
zjing14 committed
47
template <typename T>
Chao Liu's avatar
Chao Liu committed
48
49
50
51
52
53
54
struct DataType;

template <>
struct DataType<float> : std::integral_constant<DataType_t, DataType_t::Float>
{
};

zjing14's avatar
zjing14 committed
55
template <typename F, typename T, std::size_t... Is>
Chao Liu's avatar
Chao Liu committed
56
57
58
59
60
auto call_f_unpack_args_impl(F f, T args, std::index_sequence<Is...>)
{
    return f(std::get<Is>(args)...);
}

zjing14's avatar
zjing14 committed
61
template <typename F, typename T>
Chao Liu's avatar
Chao Liu committed
62
63
auto call_f_unpack_args(F f, T args)
{
Chao Liu's avatar
Chao Liu committed
64
    constexpr std::size_t N = std::tuple_size<T>{};
Chao Liu's avatar
Chao Liu committed
65
66
67
68

    return call_f_unpack_args_impl(f, args, std::make_index_sequence<N>{});
}

zjing14's avatar
zjing14 committed
69
template <typename F, typename T, std::size_t... Is>
Chao Liu's avatar
Chao Liu committed
70
71
72
73
74
auto construct_f_unpack_args_impl(T args, std::index_sequence<Is...>)
{
    return F(std::get<Is>(args)...);
}

zjing14's avatar
zjing14 committed
75
template <typename F, typename T>
Chao Liu's avatar
Chao Liu committed
76
77
auto construct_f_unpack_args(F, T args)
{
Chao Liu's avatar
Chao Liu committed
78
    constexpr std::size_t N = std::tuple_size<T>{};
Chao Liu's avatar
Chao Liu committed
79
80
81
82

    return construct_f_unpack_args_impl<F>(args, std::make_index_sequence<N>{});
}

Chao Liu's avatar
Chao Liu committed
83
struct HostTensorDescriptor
Chao Liu's avatar
Chao Liu committed
84
{
Chao Liu's avatar
Chao Liu committed
85
    HostTensorDescriptor() = delete;
Chao Liu's avatar
Chao Liu committed
86
87

    template <typename X>
Chao Liu's avatar
Chao Liu committed
88
    HostTensorDescriptor(std::vector<X> lens);
Chao Liu's avatar
Chao Liu committed
89
90

    template <typename X, typename Y>
Chao Liu's avatar
Chao Liu committed
91
    HostTensorDescriptor(std::vector<X> lens, std::vector<Y> strides);
Chao Liu's avatar
Chao Liu committed
92
93
94

    void CalculateStrides();

zjing14's avatar
zjing14 committed
95
    template <typename Range>
Chao Liu's avatar
Chao Liu committed
96
    HostTensorDescriptor(const Range& lens) : mLens(lens.begin(), lens.end())
Chao Liu's avatar
Chao Liu committed
97
98
99
100
    {
        this->CalculateStrides();
    }

zjing14's avatar
zjing14 committed
101
    template <typename Range1, typename Range2>
Chao Liu's avatar
Chao Liu committed
102
    HostTensorDescriptor(const Range1& lens, const Range2& strides)
Chao Liu's avatar
Chao Liu committed
103
        : mLens(lens.begin(), lens.end()), mStrides(strides.begin(), strides.end())
Chao Liu's avatar
Chao Liu committed
104
105
    {
    }
Chao Liu's avatar
Chao Liu committed
106

Chao Liu's avatar
Chao Liu committed
107
    std::size_t GetNumOfDimension() const;
Chao Liu's avatar
Chao Liu committed
108
109
110
    std::size_t GetElementSize() const;
    std::size_t GetElementSpace() const;

Chao Liu's avatar
Chao Liu committed
111
112
113
    const std::vector<std::size_t>& GetLengths() const;
    const std::vector<std::size_t>& GetStrides() const;

zjing14's avatar
zjing14 committed
114
    template <typename... Is>
115
    std::size_t GetOffsetFromMultiIndex(Is... is) const
Chao Liu's avatar
Chao Liu committed
116
    {
Chao Liu's avatar
Chao Liu committed
117
        assert(sizeof...(Is) == this->GetNumOfDimension());
Chao Liu's avatar
Chao Liu committed
118
119
        std::initializer_list<std::size_t> iss{static_cast<std::size_t>(is)...};
        return std::inner_product(iss.begin(), iss.end(), mStrides.begin(), std::size_t{0});
Chao Liu's avatar
Chao Liu committed
120
121
122
123
124
125
126
    }

    private:
    std::vector<std::size_t> mLens;
    std::vector<std::size_t> mStrides;
};

Chao Liu's avatar
Chao Liu committed
127
struct joinable_thread : std::thread
Chao Liu's avatar
Chao Liu committed
128
{
zjing14's avatar
zjing14 committed
129
    template <typename... Xs>
Chao Liu's avatar
Chao Liu committed
130
131
132
    joinable_thread(Xs&&... xs) : std::thread(std::forward<Xs>(xs)...)
    {
    }
Chao Liu's avatar
Chao Liu committed
133

Chao Liu's avatar
Chao Liu committed
134
135
    joinable_thread(joinable_thread&&) = default;
    joinable_thread& operator=(joinable_thread&&) = default;
Chao Liu's avatar
Chao Liu committed
136

Chao Liu's avatar
Chao Liu committed
137
138
139
140
141
142
    ~joinable_thread()
    {
        if(this->joinable())
            this->join();
    }
};
Chao Liu's avatar
Chao Liu committed
143

zjing14's avatar
zjing14 committed
144
template <typename F, typename... Xs>
Chao Liu's avatar
Chao Liu committed
145
146
147
struct ParallelTensorFunctor
{
    F mF;
Chao Liu's avatar
Chao Liu committed
148
    static constexpr std::size_t NDIM = sizeof...(Xs);
Chao Liu's avatar
Chao Liu committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    std::array<std::size_t, NDIM> mLens;
    std::array<std::size_t, NDIM> mStrides;
    std::size_t mN1d;

    ParallelTensorFunctor(F f, Xs... xs) : mF(f), mLens({static_cast<std::size_t>(xs)...})
    {
        mStrides.back() = 1;
        std::partial_sum(mLens.rbegin(),
                         mLens.rend() - 1,
                         mStrides.rbegin() + 1,
                         std::multiplies<std::size_t>());
        mN1d = mStrides[0] * mLens[0];
    }

Chao Liu's avatar
Chao Liu committed
163
164
165
166
167
168
169
170
171
172
173
174
175
    std::array<std::size_t, NDIM> GetNdIndices(std::size_t i) const
    {
        std::array<std::size_t, NDIM> indices;

        for(int idim = 0; idim < NDIM; ++idim)
        {
            indices[idim] = i / mStrides[idim];
            i -= indices[idim] * mStrides[idim];
        }

        return indices;
    }

Chao Liu's avatar
Chao Liu committed
176
    void operator()(std::size_t num_thread = std::thread::hardware_concurrency()) const
Chao Liu's avatar
Chao Liu committed
177
178
179
180
181
182
183
184
    {
        std::size_t work_per_thread = (mN1d + num_thread - 1) / num_thread;

        std::vector<joinable_thread> threads(num_thread);

        for(std::size_t it = 0; it < num_thread; ++it)
        {
            std::size_t iw_begin = it * work_per_thread;
Chao Liu's avatar
Chao Liu committed
185
            std::size_t iw_end   = std::min((it + 1) * work_per_thread, mN1d);
Chao Liu's avatar
Chao Liu committed
186
187
188

            auto f = [=] {
                for(std::size_t iw = iw_begin; iw < iw_end; ++iw)
Chao Liu's avatar
Chao Liu committed
189
190
191
                {
                    call_f_unpack_args(mF, GetNdIndices(iw));
                }
Chao Liu's avatar
Chao Liu committed
192
193
194
195
196
197
            };
            threads[it] = joinable_thread(f);
        }
    }
};

zjing14's avatar
zjing14 committed
198
template <typename F, typename... Xs>
Chao Liu's avatar
Chao Liu committed
199
auto make_ParallelTensorFunctor(F f, Xs... xs)
Chao Liu's avatar
Chao Liu committed
200
{
Chao Liu's avatar
Chao Liu committed
201
    return ParallelTensorFunctor<F, Xs...>(f, xs...);
Chao Liu's avatar
Chao Liu committed
202
203
}

zjing14's avatar
zjing14 committed
204
template <typename T>
Chao Liu's avatar
Chao Liu committed
205
struct Tensor
Chao Liu's avatar
Chao Liu committed
206
{
zjing14's avatar
zjing14 committed
207
    template <typename X>
Chao Liu's avatar
Chao Liu committed
208
    Tensor(std::initializer_list<X> lens) : mDesc(lens), mData(mDesc.GetElementSpace())
Chao Liu's avatar
Chao Liu committed
209
210
    {
    }
Chao Liu's avatar
Chao Liu committed
211

zjing14's avatar
zjing14 committed
212
    template <typename X>
Chao Liu's avatar
Chao Liu committed
213
    Tensor(std::vector<X> lens) : mDesc(lens), mData(mDesc.GetElementSpace())
Chao Liu's avatar
Chao Liu committed
214
215
    {
    }
Chao Liu's avatar
Chao Liu committed
216

zjing14's avatar
zjing14 committed
217
    template <typename X, typename Y>
Chao Liu's avatar
Chao Liu committed
218
    Tensor(std::vector<X> lens, std::vector<Y> strides)
Chao Liu's avatar
Chao Liu committed
219
        : mDesc(lens, strides), mData(mDesc.GetElementSpace())
Chao Liu's avatar
Chao Liu committed
220
221
    {
    }
Chao Liu's avatar
Chao Liu committed
222

Chao Liu's avatar
Chao Liu committed
223
    Tensor(const HostTensorDescriptor& desc) : mDesc(desc), mData(mDesc.GetElementSpace()) {}
Chao Liu's avatar
Chao Liu committed
224

zjing14's avatar
zjing14 committed
225
    template <typename G>
Chao Liu's avatar
Chao Liu committed
226
227
    void GenerateTensorValue(G g, std::size_t num_thread = 1)
    {
Chao Liu's avatar
Chao Liu committed
228
        switch(mDesc.GetNumOfDimension())
Chao Liu's avatar
Chao Liu committed
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
        {
        case 1:
        {
            auto f = [&](auto i) { (*this)(i) = g(i); };
            make_ParallelTensorFunctor(f, mDesc.GetLengths()[0])(num_thread);
            break;
        }
        case 2:
        {
            auto f = [&](auto i0, auto i1) { (*this)(i0, i1) = g(i0, i1); };
            make_ParallelTensorFunctor(f, mDesc.GetLengths()[0], mDesc.GetLengths()[1])(num_thread);
            break;
        }
        case 3:
        {
            auto f = [&](auto i0, auto i1, auto i2) { (*this)(i0, i1, i2) = g(i0, i1, i2); };
            make_ParallelTensorFunctor(
                f, mDesc.GetLengths()[0], mDesc.GetLengths()[1], mDesc.GetLengths()[2])(num_thread);
            break;
        }
        case 4:
        {
            auto f = [&](auto i0, auto i1, auto i2, auto i3) {
                (*this)(i0, i1, i2, i3) = g(i0, i1, i2, i3);
            };
            make_ParallelTensorFunctor(f,
                                       mDesc.GetLengths()[0],
                                       mDesc.GetLengths()[1],
                                       mDesc.GetLengths()[2],
                                       mDesc.GetLengths()[3])(num_thread);
            break;
        }
        default: throw std::runtime_error("unspported dimension");
        }
    }

zjing14's avatar
zjing14 committed
265
    template <typename... Is>
Chao Liu's avatar
Chao Liu committed
266
267
    T& operator()(Is... is)
    {
268
        return mData[mDesc.GetOffsetFromMultiIndex(is...)];
Chao Liu's avatar
Chao Liu committed
269
270
    }

zjing14's avatar
zjing14 committed
271
    template <typename... Is>
Chao Liu's avatar
Chao Liu committed
272
273
    const T& operator()(Is... is) const
    {
274
        return mData[mDesc.GetOffsetFromMultiIndex(is...)];
Chao Liu's avatar
Chao Liu committed
275
276
277
278
279
280
281
282
283
284
    }

    typename std::vector<T>::iterator begin() { return mData.begin(); }

    typename std::vector<T>::iterator end() { return mData.end(); }

    typename std::vector<T>::const_iterator begin() const { return mData.begin(); }

    typename std::vector<T>::const_iterator end() const { return mData.end(); }

Chao Liu's avatar
Chao Liu committed
285
    HostTensorDescriptor mDesc;
Chao Liu's avatar
Chao Liu committed
286
287
    std::vector<T> mData;
};
288

289
290
template <typename X>
HostTensorDescriptor::HostTensorDescriptor(std::vector<X> lens) : mLens(lens)
Chao Liu's avatar
Chao Liu committed
291
{
292
293
    this->CalculateStrides();
}
Chao Liu's avatar
Chao Liu committed
294

295
296
297
298
template <typename X, typename Y>
HostTensorDescriptor::HostTensorDescriptor(std::vector<X> lens, std::vector<Y> strides)
    : mLens(lens), mStrides(strides)
{
Chao Liu's avatar
Chao Liu committed
299
300
}

301
302
void ostream_HostTensorDescriptor(const HostTensorDescriptor& desc, std::ostream& os = std::cout);

zjing14's avatar
zjing14 committed
303
template <typename T>
Chao Liu's avatar
Chao Liu committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
void check_error(const Tensor<T>& ref, const Tensor<T>& result)
{
    float error     = 0;
    float max_diff  = -1;
    float ref_value = 0, result_value = 0;
    for(int i = 0; i < ref.mData.size(); ++i)
    {
        error += std::abs(double(ref.mData[i]) - double(result.mData[i]));
        float diff = std::abs(double(ref.mData[i]) - double(result.mData[i]));
        if(max_diff < diff)
        {
            max_diff     = diff;
            ref_value    = ref.mData[i];
            result_value = result.mData[i];
        }
    }

    std::cout << "error: " << error << std::endl;
    std::cout << "max_diff: " << max_diff << ", " << ref_value << ", " << result_value << std::endl;
}

325
#endif