aboutsummaryrefslogtreecommitdiffstats
path: root/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Reshape.java
blob: f96dd420d303e84ad8d575de0589d8cd602b458c (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
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.rankingexpression.importer.operations;

import ai.vespa.rankingexpression.importer.OrderedTensorType;
import com.yahoo.searchlib.rankingexpression.Reference;
import com.yahoo.searchlib.rankingexpression.evaluation.DoubleValue;
import ai.vespa.rankingexpression.importer.DimensionRenamer;
import com.yahoo.searchlib.rankingexpression.evaluation.StringValue;
import com.yahoo.searchlib.rankingexpression.evaluation.Value;
import com.yahoo.searchlib.rankingexpression.rule.ArithmeticNode;
import com.yahoo.searchlib.rankingexpression.rule.ArithmeticOperator;
import com.yahoo.searchlib.rankingexpression.rule.ComparisonNode;
import com.yahoo.searchlib.rankingexpression.rule.ConstantNode;
import com.yahoo.searchlib.rankingexpression.rule.EmbracedNode;
import com.yahoo.searchlib.rankingexpression.rule.ExpressionNode;
import com.yahoo.searchlib.rankingexpression.rule.Function;
import com.yahoo.searchlib.rankingexpression.rule.FunctionNode;
import com.yahoo.searchlib.rankingexpression.rule.GeneratorLambdaFunctionNode;
import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode;
import com.yahoo.searchlib.rankingexpression.rule.TensorFunctionNode;
import com.yahoo.searchlib.rankingexpression.rule.TruthOperator;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.functions.Generate;
import com.yahoo.tensor.functions.Reduce;
import com.yahoo.tensor.functions.Rename;
import com.yahoo.tensor.functions.ScalarFunctions;
import com.yahoo.tensor.functions.TensorFunction;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.yahoo.searchlib.rankingexpression.rule.TensorFunctionNode.wrapScalar;

public class Reshape extends IntermediateOperation {

    private final AttributeMap attributeMap;

    public Reshape(String modelName, String nodeName, List<IntermediateOperation> inputs, AttributeMap attributeMap) {
        super(modelName, nodeName, inputs);
        this.attributeMap = attributeMap;
    }

    @Override
    protected OrderedTensorType lazyGetType() {

        // required as we use tensor create
        inputs.get(0).exportAsRankingFunction = true;

        if (inputs.size() == 2) {
            return typeWithShapeAsInput();
        } else if (inputs.size() == 1) {
            return typeWithShapeAsAttribute();
        }
        throw new IllegalArgumentException("Expected 2 or 3 inputs for '" + name + "', got " + inputs.size());
    }

    private OrderedTensorType typeWithShapeAsInput() {
        IntermediateOperation newShape = inputs.get(1);
        if (newShape.getConstantValue().isEmpty())
            throw new IllegalArgumentException("Reshape " + name + ": Shape input must be a constant.");

        OrderedTensorType inputType = inputs.get(0).type().get();
        Tensor shape = newShape.getConstantValue().get().asTensor();
        List<Integer> dimSizes = new ArrayList<>(shape.type().rank());
        shape.valueIterator().forEachRemaining(v -> dimSizes.add(v.intValue()));

        // first pass - set 0 values, meaning that size is retained from input
        for (int i = 0; i < dimSizes.size(); ++i) {
            if (dimSizes.get(i) == 0) {
                if (i >= inputType.dimensions().size()) {
                    throw new IllegalArgumentException("Reshape " + name + ": 0 value for dimension not found in input");
                }
                dimSizes.set(i, inputType.dimensions().get(i).size().get().intValue());
            }
        }

        // second pass - set any -1 value, meaning that the dimension size should be expanded to fill the tensor
        for (int i = 0; i < dimSizes.size(); ++i) {
            if (dimSizes.get(i) < 0) {
                int shapeSize = dimSizes.stream().reduce(1, (a, b) -> a * b);
                int tensorSize = OrderedTensorType.tensorSize(inputType.type()).intValue();
                dimSizes.set(i, -1 * tensorSize / (shapeSize == 0 ? -1 : shapeSize));
            }
        }

        return buildOutputType(dimSizes);
    }

    private OrderedTensorType typeWithShapeAsAttribute() {
        if (attributeMap.getList("shape").isEmpty() || attributeMap.getList("shape").get().size() == 0)
            throw new IllegalArgumentException("Reshape in " + name + ": Shape attribute is empty.");

        OrderedTensorType inputType = inputs.get(0).type().get();
        List<Value> shape = attributeMap.getList("shape").get();
        List<Integer> dimSizes = new ArrayList<>(shape.size());

        for (Value v : shape) {
            int size = (int) v.asDouble();
            if (size < 0) {
                int shapeSize = (int) shape.stream().mapToDouble(Value::asDouble).reduce(1, (a, b) -> a * b);
                int tensorSize = OrderedTensorType.tensorSize(inputType.type()).intValue();
                size = -1 * shapeSize / tensorSize;
            }
            dimSizes.add(size);
        }
        return buildOutputType(dimSizes);
    }

    private OrderedTensorType buildOutputType(List<Integer> dimSizes) {
        OrderedTensorType.Builder outputTypeBuilder = new OrderedTensorType.Builder(resultValueType());
        for (int i = 0; i < dimSizes.size(); ++i) {
            outputTypeBuilder.add(TensorType.Dimension.indexed(String.format("%s_%d", vespaName(), i), dimSizes.get(i)));
        }
        return outputTypeBuilder.build();
    }

    @Override
    protected TensorFunction lazyGetFunction() {
        if ( ! inputs.stream().map(IntermediateOperation::type).allMatch(Optional::isPresent) ) return null;
        if ( ! inputs.stream().map(IntermediateOperation::function).allMatch(Optional::isPresent) ) return null;

        OrderedTensorType inputType = inputs.get(0).type().get();
        TensorFunction inputFunction = inputs.get(0).function().get();
        return reshape(inputFunction, inputType, type);
    }

    @Override
    public void addDimensionNameConstraints(DimensionRenamer renamer) {
        addConstraintsFrom(type, renamer);
    }

    @Override
    public Reshape withInputs(List<IntermediateOperation> inputs) {
        return new Reshape(modelName(), name(), inputs, attributeMap);
    }

    public TensorFunction reshape(TensorFunction inputFunction, OrderedTensorType inputType, OrderedTensorType outputType) {
        if ( ! OrderedTensorType.tensorSize(inputType.type()).equals(OrderedTensorType.tensorSize(outputType.type())))
            throw new IllegalArgumentException("New and old shape of tensor must have the same size when reshaping");

        IntermediateOperation input = inputs.get(0);
        String inputFunctionName = input.rankingExpressionFunctionName();

        List<com.yahoo.tensor.functions.Slice.DimensionValue<Reference>> dimensionValues = new ArrayList<>();

        // ala (d0 * 2 + d1)
        ExpressionNode unrolled = new EmbracedNode(unrollTensorExpression(outputType));

        long innerSize = 1;
        for (int dim = 0; dim < inputType.rank(); ++dim) {
            innerSize *= inputType.dimensions().get(dim).size().get();
        }

        for (int dim = 0; dim < inputType.rank(); ++dim) {
            String inputDimensionName = inputType.dimensions().get(dim).name();
            long inputDimensionSize = inputType.dimensions().get(dim).size().get();
            long previousInnerSize = innerSize;
            innerSize /= inputDimensionSize;

            ExpressionNode inputDimensionExpression;
            if (inputDimensionSize == 1) {
                inputDimensionExpression = new EmbracedNode(new ConstantNode(DoubleValue.zero));
            } else if (dim == (inputType.rank() - 1)) {
                ExpressionNode size = new ConstantNode(new DoubleValue(inputDimensionSize));
                ExpressionNode div = new ArithmeticNode(unrolled, ArithmeticOperator.MODULO, size);
                inputDimensionExpression = new EmbracedNode(div);
            } else {
                ExpressionNode size = new ConstantNode(new DoubleValue(innerSize));
                ExpressionNode previousSize = new ConstantNode(new DoubleValue(previousInnerSize));
                ExpressionNode mod = new ArithmeticNode(unrolled, ArithmeticOperator.MODULO, previousSize);
                ExpressionNode div = new ArithmeticNode(new EmbracedNode(mod), ArithmeticOperator.DIVIDE, size);
                inputDimensionExpression = new EmbracedNode(new FunctionNode(Function.floor, div));
            }
            dimensionValues.add(new com.yahoo.tensor.functions.Slice.DimensionValue<>(Optional.of(inputDimensionName), wrapScalar(inputDimensionExpression)));
        }

        TensorFunction<Reference> inputIndices = new TensorFunctionNode.ExpressionTensorFunction(new ReferenceNode(inputFunctionName));
        com.yahoo.tensor.functions.Slice<Reference> sliceIndices = new com.yahoo.tensor.functions.Slice<>(inputIndices, dimensionValues);
        ExpressionNode sliceExpression = new TensorFunctionNode(sliceIndices);

        TensorFunction generate = Generate.bound(outputType.type(), wrapScalar(sliceExpression));
        return generate;

        /*
        // Conceptually, reshaping consists on unrolling a tensor to an array using the dimension order,
        // then use the dimension order of the new shape to roll back into a tensor.
        // Here we create a transformation tensor that is multiplied with the from tensor to map into
        // the new shape. We have to introduce temporary dimension names and rename back if dimension names
        // in the new and old tensor type overlap.

        // Todo: change this to use tensor generate when available

        List<String> from = new ArrayList<>();
        List<String> to = new ArrayList<>();
        boolean dimensionNamesOverlap = dimensionNamesOverlap(inputType, outputType);
        if (dimensionNamesOverlap) {
            OrderedTensorType.Builder builder = new OrderedTensorType.Builder(outputType.type().valueType());
            for (int i = 0; i < outputType.rank(); ++i) {
                TensorType.Dimension dim = outputType.dimensions().get(i);
                from.add(dim.name());
                to.add("temp_" + dim.name());
                builder.add(dim.withName("temp_" + dim.name()));
            }
            outputType = builder.build();
        }

        ExpressionNode unrollFrom = unrollTensorExpression(inputType);
        ExpressionNode unrollTo = unrollTensorExpression(outputType);
        ExpressionNode transformExpression = new ComparisonNode(new EmbracedNode(unrollFrom), TruthOperator.EQUAL, new EmbracedNode(unrollTo));

        TensorType transformationType = new TensorType.Builder(inputType.type(), outputType.type()).build();
        Generate transformTensor = new Generate(transformationType,
                                                new GeneratorLambdaFunctionNode(transformationType, transformExpression).asLongListToDoubleOperator());

        TensorFunction result = new Reduce(new com.yahoo.tensor.functions.Join(inputFunction, transformTensor, ScalarFunctions.multiply()),
                          Reduce.Aggregator.sum,
                          inputType.dimensions().stream().map(TensorType.Dimension::name).collect(Collectors.toList()));

        if (dimensionNamesOverlap) {
            result = new Rename(result, to, from);
        }
        return result;
        */
    }

    /*
    private static boolean dimensionNamesOverlap(OrderedTensorType a, OrderedTensorType b) {
        return a.dimensionNames().stream().anyMatch(d -> b.type().indexOfDimension(d).isPresent());
    }
    */

    private static ExpressionNode unrollTensorExpression(OrderedTensorType type) {
        if (type.rank() == 0)
            return new ConstantNode(DoubleValue.zero);

        List<ExpressionNode> children = new ArrayList<>();
        List<ArithmeticOperator> operators = new ArrayList<>();
        int size = 1;
        for (int i = type.dimensions().size() - 1; i >= 0; --i) {
            TensorType.Dimension dimension = type.dimensions().get(i);
            children.add(0, new ReferenceNode(dimension.name()));
            if (size > 1) {
                operators.add(0, ArithmeticOperator.MULTIPLY);
                children.add(0, new ConstantNode(new DoubleValue(size)));
            }
            size *= OrderedTensorType.dimensionSize(dimension);
            if (i > 0) {
                operators.add(0, ArithmeticOperator.PLUS);
            }
        }
        return new ArithmeticNode(children, operators);
    }

    @Override
    public String operationName() { return "Reshape"; }

}