summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/tensor/serialization/DenseBinaryFormat.java
blob: 4d4d947557d166b0c0bfe35b857d0765a9451f4b (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
package com.yahoo.tensor.serialization;

import com.google.common.annotations.Beta;
import com.yahoo.io.GrowableByteBuffer;
import com.yahoo.tensor.DimensionSizes;
import com.yahoo.tensor.IndexedTensor;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.text.Utf8;

import java.util.Iterator;

/**
 * Implementation of a dense binary format for a tensor on the form:
 *
 * Sorted dimensions = num_dimensions [dimension_str_len dimension_str_bytes dimension_size_int]*
 * Cell_values = [double, double, double, ...]*
 * where values are encoded in order of increasing indexes in each dimension, increasing 
 * indexes of later dimensions in the dimension type before earlier.
 * 
 * @author bratseth
 */
@Beta
public class DenseBinaryFormat implements BinaryFormat {

    @Override
    public void encode(GrowableByteBuffer buffer, Tensor tensor) {
        if ( ! ( tensor instanceof IndexedTensor))
            throw new RuntimeException("The dense format is only supported for indexed tensors");
        encodeDimensions(buffer, (IndexedTensor)tensor);
        encodeCells(buffer, tensor);
    }

    private void encodeDimensions(GrowableByteBuffer buffer, IndexedTensor tensor) {
        buffer.putInt1_4Bytes(tensor.type().dimensions().size());
        for (int i = 0; i < tensor.type().dimensions().size(); i++) {
            encodeString(buffer, tensor.type().dimensions().get(i).name());
            buffer.putInt1_4Bytes(tensor.dimensionSizes().size(i));
        }
    }

    private void encodeCells(GrowableByteBuffer buffer, Tensor tensor) {
        Iterator<Double> i = tensor.valueIterator();
        if ( ! i.hasNext()) { // no values: Encode as NaN, as 0 dimensions may also mean 1 value
            buffer.putDouble(Double.NaN);
        }
        else {
            while (i.hasNext())
                buffer.putDouble(i.next());
        }
    }

    private void encodeString(GrowableByteBuffer buffer, String value) {
        byte[] stringBytes = Utf8.toBytes(value);
        buffer.putInt1_4Bytes(stringBytes.length);
        buffer.put(stringBytes);
    }

    @Override
    public Tensor decode(TensorType type, GrowableByteBuffer buffer) {
        DimensionSizes sizes = decodeDimensionSizes(type, buffer);        
        Tensor.Builder builder = Tensor.Builder.of(type, sizes);
        decodeCells(sizes, buffer, (IndexedTensor.BoundBuilder)builder);
        return builder.build();
    }

    private DimensionSizes decodeDimensionSizes(TensorType type, GrowableByteBuffer buffer) {
        int dimensionCount = buffer.getInt1_4Bytes();
        if (type.dimensions().size() != dimensionCount)
            throw new IllegalArgumentException("Type/instance mismatch: Instance has " + dimensionCount + 
                                               " dimensions but type is " + type);
        
        DimensionSizes.Builder builder = new DimensionSizes.Builder(dimensionCount);
        for (int i = 0; i < dimensionCount; i++) {
            TensorType.Dimension expectedDimension = type.dimensions().get(i);

            String encodedName = decodeString(buffer);
            int encodedSize = buffer.getInt1_4Bytes();

            if ( ! expectedDimension.name().equals(encodedName))
                throw new IllegalArgumentException("Type/instance mismatch: Instance has '" + encodedName +
                                                   "' as dimension " + i + " but type is " + type);

            if (expectedDimension.size().isPresent() && expectedDimension.size().get() < encodedSize)
                throw new IllegalArgumentException("Type/instance mismatch: Instance has size " + encodedSize + 
                                                   " in " + expectedDimension  + " in type " + type);

            builder.set(i, encodedSize);
        }
        return builder.build();
    }

    private void decodeCells(DimensionSizes sizes, GrowableByteBuffer buffer, IndexedTensor.BoundBuilder builder) {
        for (int i = 0; i < sizes.totalSize(); i++)
            builder.cellByDirectIndex(i, buffer.getDouble());
    }

    private String decodeString(GrowableByteBuffer buffer) {
        int stringLength = buffer.getInt1_4Bytes();
        byte[] stringBytes = new byte[stringLength];
        buffer.get(stringBytes);
        return Utf8.toString(stringBytes);
    }

}