host_tensor.cpp 1.42 KB
Newer Older
Chao Liu's avatar
Chao Liu committed
1
2
3
#include <boost/range/adaptor/transformed.hpp>
#include <cassert>

Chao Liu's avatar
Chao Liu committed
4
#include "host_tensor.hpp"
Chao Liu's avatar
Chao Liu committed
5

Chao Liu's avatar
Chao Liu committed
6
void HostTensorDescriptor::CalculateStrides()
Chao Liu's avatar
Chao Liu committed
7
8
9
{
    mStrides.clear();
    mStrides.resize(mLens.size(), 0);
Chao Liu's avatar
Chao Liu committed
10
    if(mStrides.empty())
Chao Liu's avatar
Chao Liu committed
11
12
13
14
15
16
17
        return;

    mStrides.back() = 1;
    std::partial_sum(
        mLens.rbegin(), mLens.rend() - 1, mStrides.rbegin() + 1, std::multiplies<std::size_t>());
}

Chao Liu's avatar
Chao Liu committed
18
std::size_t HostTensorDescriptor::GetNumOfDimension() const { return mLens.size(); }
Chao Liu's avatar
Chao Liu committed
19

Chao Liu's avatar
Chao Liu committed
20
std::size_t HostTensorDescriptor::GetElementSize() const
Chao Liu's avatar
Chao Liu committed
21
22
23
24
25
26
{
    assert(mLens.size() == mStrides.size());
    return std::accumulate(
        mLens.begin(), mLens.end(), std::size_t{1}, std::multiplies<std::size_t>());
}

Chao Liu's avatar
Chao Liu committed
27
std::size_t HostTensorDescriptor::GetElementSpace() const
Chao Liu's avatar
Chao Liu committed
28
{
Chao Liu's avatar
Chao Liu committed
29
    auto ls = mLens | boost::adaptors::transformed([](std::size_t v) { return v - 1; });
Chao Liu's avatar
Chao Liu committed
30
31
    return std::inner_product(ls.begin(), ls.end(), mStrides.begin(), std::size_t{0}) + 1;
}
Chao Liu's avatar
Chao Liu committed
32

Chao Liu's avatar
Chao Liu committed
33
const std::vector<std::size_t>& HostTensorDescriptor::GetLengths() const { return mLens; }
Chao Liu's avatar
Chao Liu committed
34

Chao Liu's avatar
Chao Liu committed
35
const std::vector<std::size_t>& HostTensorDescriptor::GetStrides() const { return mStrides; }
36
37
38
39
40
41
42
43
44
45
46
47
48

void ostream_HostTensorDescriptor(const HostTensorDescriptor& desc, std::ostream& os)
{
    os << "dim " << desc.GetNumOfDimension() << ", ";

    os << "lengths {";
    LogRange(os, desc.GetLengths(), ", ");
    os << "}, ";

    os << "strides {";
    LogRange(os, desc.GetStrides(), ", ");
    os << "}" << std::endl;
}