summaryrefslogtreecommitdiffstats
path: root/searchlib/src/vespa/searchlib/tensor/dense_tensor_store.cpp
blob: cb24bb4edf7f8a0fea6528e389d3e7bcb7d4305f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "dense_tensor_store.h"
#include <vespa/eval/tensor/tensor.h>
#include <vespa/eval/tensor/dense/dense_tensor_view.h>
#include <vespa/eval/tensor/dense/mutable_dense_tensor_view.h>
#include <vespa/eval/tensor/dense/dense_tensor.h>
#include <vespa/eval/tensor/serialization/typed_binary_format.h>
#include <vespa/searchlib/datastore/datastore.hpp>

using search::datastore::Handle;
using vespalib::tensor::Tensor;
using vespalib::tensor::DenseTensor;
using vespalib::tensor::DenseTensorView;
using vespalib::tensor::MutableDenseTensorView;
using vespalib::eval::ValueType;

namespace search {
namespace tensor {

constexpr size_t MIN_BUFFER_CLUSTERS = 1024;

DenseTensorStore::BufferType::BufferType()
    : datastore::BufferType<char>(RefType::align(1),
                              MIN_BUFFER_CLUSTERS,
                              RefType::offsetSize() / RefType::align(1)),
      _unboundDimSizesSize(0u)
{
}

DenseTensorStore::BufferType::~BufferType()
{
}

void
DenseTensorStore::BufferType::cleanHold(void *buffer, uint64_t offset,
                                        uint64_t len, CleanContext)
{
    // Clear both tensor dimension size information and cells.
    memset(static_cast<char *>(buffer) + offset - _unboundDimSizesSize, 0, len);
}

size_t
DenseTensorStore::BufferType::getReservedElements(uint32_t bufferId) const
{
    return datastore::BufferType<char>::getReservedElements(bufferId) +
        RefType::align(_unboundDimSizesSize);
}

DenseTensorStore::DenseTensorStore(const ValueType &type)
    : TensorStore(_concreteStore),
      _concreteStore(),
      _bufferType(),
      _type(type),
      _numBoundCells(1u),
      _numUnboundDims(0u),
      _cellSize(sizeof(double)),
      _emptyCells()
{
    for (const auto & dim : _type.dimensions()) {
        if (dim.is_bound()) {
            _numBoundCells *= dim.size;
        } else {
            ++_numUnboundDims;
        }
    }
    _emptyCells.resize(_numBoundCells, 0.0);
    _bufferType.setUnboundDimSizesSize(_numUnboundDims * sizeof(uint32_t));
    _store.addType(&_bufferType);
    _store.initActiveBuffers();
}

DenseTensorStore::~DenseTensorStore()
{
    _store.dropBuffers();
}

const void *
DenseTensorStore::getRawBuffer(RefType ref) const
{
    return _store.getBufferEntry<char>(ref.bufferId(),
                                         ref.offset());
}


size_t
DenseTensorStore::getNumCells(const void *buffer) const
{
    const uint32_t *unboundDimSizeEnd = static_cast<const uint32_t *>(buffer);
    const uint32_t *unboundDimSizeStart = unboundDimSizeEnd - _numUnboundDims;
    size_t numCells = _numBoundCells;
    for (auto unboundDimSize = unboundDimSizeStart; unboundDimSize != unboundDimSizeEnd; ++unboundDimSize) {
        numCells *= *unboundDimSize;
    }
    return numCells;
}

namespace {

void clearPadAreaAfterBuffer(char *buffer, size_t bufSize, size_t alignedBufSize, uint32_t unboundDimSizesSize) {
    size_t padSize = alignedBufSize - unboundDimSizesSize - bufSize;
    memset(buffer + bufSize, 0, padSize);
}

}

Handle<char>
DenseTensorStore::allocRawBuffer(size_t numCells)
{
    size_t bufSize = numCells * _cellSize;
    size_t alignedBufSize = alignedSize(numCells);
    auto result = _concreteStore.rawAllocator<char>(_typeId).alloc(alignedBufSize);
    clearPadAreaAfterBuffer(result.data, bufSize, alignedBufSize, unboundDimSizesSize());
    return result;
}

Handle<char>
DenseTensorStore::allocRawBuffer(size_t numCells,
                                 const std::vector<uint32_t> &unboundDimSizes)
{
    assert(unboundDimSizes.size() == _numUnboundDims);
    auto ret = allocRawBuffer(numCells);
    if (_numUnboundDims > 0) {
        memcpy(ret.data - unboundDimSizesSize(),
               &unboundDimSizes[0], unboundDimSizesSize());
    }
    assert(numCells == getNumCells(ret.data));
    return ret;
}

void
DenseTensorStore::holdTensor(EntryRef ref)
{
    if (!ref.valid()) {
        return;
    }
    const void *buffer = getRawBuffer(ref);
    size_t numCells = getNumCells(buffer);
    _concreteStore.holdElem(ref, alignedSize(numCells));
}

TensorStore::EntryRef
DenseTensorStore::move(EntryRef ref)
{
    if (!ref.valid()) {
        return RefType();
    }
    auto oldraw = getRawBuffer(ref);
    size_t numCells = getNumCells(oldraw);
    auto newraw = allocRawBuffer(numCells);
    memcpy(newraw.data - unboundDimSizesSize(),
           static_cast<const char *>(oldraw) - unboundDimSizesSize(),
           numCells * _cellSize + unboundDimSizesSize());
    _concreteStore.holdElem(ref, alignedSize(numCells));
    return newraw.ref;
}

namespace {

void makeConcreteType(MutableDenseTensorView &tensor,
                      const void *buffer,
                      uint32_t numUnboundDims)
{
    const uint32_t *unboundDimSizeEnd = static_cast<const uint32_t *>(buffer);
    const uint32_t *unboundDimSizeBegin = unboundDimSizeEnd - numUnboundDims;
    tensor.setUnboundDimensions(unboundDimSizeBegin, unboundDimSizeEnd);
}

}

std::unique_ptr<Tensor>
DenseTensorStore::getTensor(EntryRef ref) const
{
    if (!ref.valid()) {
        return std::unique_ptr<Tensor>();
    }
    auto raw = getRawBuffer(ref);
    size_t numCells = getNumCells(raw);
    if (_numUnboundDims == 0) {
        return std::make_unique<DenseTensorView>
                (_type,
                 DenseTensorView::CellsRef(static_cast<const double *>(raw), numCells));
    } else {
        std::unique_ptr <MutableDenseTensorView> result =
                std::make_unique<MutableDenseTensorView>(_type,
                                                         DenseTensorView::CellsRef(static_cast<const double *>(raw),
                                                                               numCells));
        makeConcreteType(*result, raw, _numUnboundDims);
        return result;
    }
}

void
DenseTensorStore::getTensor(EntryRef ref, MutableDenseTensorView &tensor) const
{
    if (!ref.valid()) {
        tensor.setCells(DenseTensorView::CellsRef(&_emptyCells[0], _emptyCells.size()));
        if (_numUnboundDims > 0) {
            tensor.setUnboundDimensionsForEmptyTensor();
        }
    } else {
        auto raw = getRawBuffer(ref);
        size_t numCells = getNumCells(raw);
        tensor.setCells(DenseTensorView::CellsRef(static_cast<const double *>(raw), numCells));
        if (_numUnboundDims > 0) {
            makeConcreteType(tensor, raw, _numUnboundDims);
        }
    }
}

namespace
{

void
checkMatchingType(const ValueType &lhs, const ValueType &rhs, size_t numCells)
{
    (void) numCells;
    size_t checkNumCells = 1u;
    auto rhsItr = rhs.dimensions().cbegin();
    auto rhsItrEnd = rhs.dimensions().cend();
    (void) rhsItrEnd;
    for (const auto &dim : lhs.dimensions()) {
        (void) dim;
        assert(rhsItr != rhsItrEnd);
        assert(dim.name == rhsItr->name);
        assert(rhsItr->is_bound());
        assert(!dim.is_bound() || dim.size == rhsItr->size);
        checkNumCells *= rhsItr->size;
        ++rhsItr;
    }
    assert(numCells == checkNumCells);
    assert(rhsItr == rhsItrEnd);
}

void
setDenseTensorUnboundDimSizes(void *buffer, const ValueType &lhs, uint32_t numUnboundDims, const ValueType &rhs)
{
    uint32_t *unboundDimSizeEnd = static_cast<uint32_t *>(buffer);
    uint32_t *unboundDimSize = unboundDimSizeEnd - numUnboundDims;
    auto rhsItr = rhs.dimensions().cbegin();
    auto rhsItrEnd = rhs.dimensions().cend();
    (void) rhsItrEnd;
    for (const auto &dim : lhs.dimensions()) {
        assert (rhsItr != rhsItrEnd);
        if (!dim.is_bound()) {
            assert(unboundDimSize != unboundDimSizeEnd);
            *unboundDimSize = rhsItr->size;
            ++unboundDimSize;
        }
        ++rhsItr;
    }
    assert (rhsItr == rhsItrEnd);
    assert(unboundDimSize == unboundDimSizeEnd);
}

}

template <class TensorType>
TensorStore::EntryRef
DenseTensorStore::setDenseTensor(const TensorType &tensor)
{
    size_t numCells = tensor.cellsRef().size();
    checkMatchingType(_type, tensor.type(), numCells);
    auto raw = allocRawBuffer(numCells);
    setDenseTensorUnboundDimSizes(raw.data, _type, _numUnboundDims, tensor.type());
    memcpy(raw.data, &tensor.cellsRef()[0], numCells * _cellSize);
    return raw.ref;
}

TensorStore::EntryRef
DenseTensorStore::setTensor(const Tensor &tensor)
{
    const DenseTensorView *view(dynamic_cast<const DenseTensorView *>(&tensor));
    if (view) {
        return setDenseTensor(*view);
    }
    abort();
}

}  // namespace search::tensor
}  // namespace search