aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/tensor/functions/Matmul.java
blob: a06053c88a406b68e4535a1e049e3f8a2ac0759d (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.tensor.functions;

import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.Name;

import java.util.List;
import java.util.Objects;

/**
 * @author bratseth
 */
public class Matmul<NAMETYPE extends Name> extends CompositeTensorFunction<NAMETYPE> {

    private final TensorFunction<NAMETYPE> argument1, argument2;
    private final String dimension;

    public Matmul(TensorFunction<NAMETYPE> argument1, TensorFunction<NAMETYPE> argument2, String dimension) {
        this.argument1 = argument1;
        this.argument2 = argument2;
        this.dimension = dimension;
    }

    public static TensorType outputType(TensorType a, TensorType b, String dimension) {
        return Join.outputType(a, b);
    }

    @Override
    public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument1, argument2); }

    @Override
    public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) {
        if ( arguments.size() != 2)
            throw new IllegalArgumentException("Matmul must have 2 arguments, got " + arguments.size());
        return new Matmul<>(arguments.get(0), arguments.get(1), dimension);
    }

    @Override
    public PrimitiveTensorFunction<NAMETYPE> toPrimitive() {
        TensorFunction<NAMETYPE> primitiveArgument1 = argument1.toPrimitive();
        TensorFunction<NAMETYPE> primitiveArgument2 = argument2.toPrimitive();
        return new Reduce<>(new Join<>(primitiveArgument1, primitiveArgument2, ScalarFunctions.multiply()),
                            Reduce.Aggregator.sum,
                            dimension);
    }

    @Override
    public String toString(ToStringContext<NAMETYPE> context) {
        return "matmul(" + argument1.toString(context) + ", " + argument2.toString(context) + ", " + dimension + ")";
    }

    @Override
    public int hashCode() { return Objects.hash("matmul", argument1, argument2, dimension); }

}