aboutsummaryrefslogtreecommitdiffstats
path: root/model-integration/src/main/java/ai/vespa/modelintegration/evaluator/OnnxEvaluator.java
blob: cd698eb16473883fb2ec011c660ffbead16b1c6e (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

package ai.vespa.modelintegration.evaluator;

import ai.onnxruntime.NodeInfo;
import ai.onnxruntime.OnnxTensor;
import ai.onnxruntime.OnnxValue;
import ai.onnxruntime.OrtException;
import ai.onnxruntime.OrtSession;
import ai.vespa.modelintegration.evaluator.OnnxRuntime.ModelPathOrData;
import ai.vespa.modelintegration.evaluator.OnnxRuntime.ReferencedOrtSession;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import static ai.vespa.modelintegration.evaluator.OnnxRuntime.isCudaError;


/**
 * Evaluates an ONNX Model by deferring to ONNX Runtime.
 *
 * @author lesters
 */
public class OnnxEvaluator implements AutoCloseable {

    private static final Logger LOG = Logger.getLogger(OnnxEvaluator.class.getName());

    private final ReferencedOrtSession session;

    OnnxEvaluator(String modelPath, OnnxEvaluatorOptions options, OnnxRuntime runtime) {
        session = createSession(ModelPathOrData.of(modelPath), runtime, options, true);
    }

    OnnxEvaluator(byte[] data, OnnxEvaluatorOptions options, OnnxRuntime runtime) {
        session = createSession(ModelPathOrData.of(data), runtime, options, true);
    }

    public Tensor evaluate(Map<String, Tensor> inputs, String output) {
        Map<String, OnnxTensor> onnxInputs = null;
        try {
            output = mapToInternalName(output);
            onnxInputs = TensorConverter.toOnnxTensors(inputs, OnnxRuntime.ortEnvironment(), session.instance());
            try (OrtSession.Result result = session.instance().run(onnxInputs, Collections.singleton(output))) {
                return TensorConverter.toVespaTensor(result.get(0));
            }
        } catch (OrtException e) {
            throw new RuntimeException("ONNX Runtime exception", e);
        } finally {
            if (onnxInputs != null) {
                onnxInputs.values().forEach(OnnxTensor::close);
            }
        }
    }

    public Map<String, Tensor> evaluate(Map<String, Tensor> inputs) {
        Map<String, OnnxTensor> onnxInputs = null;
        try {
            onnxInputs = TensorConverter.toOnnxTensors(inputs, OnnxRuntime.ortEnvironment(), session.instance());
            Map<String, Tensor> outputs = new HashMap<>();
            try (OrtSession.Result result = session.instance().run(onnxInputs)) {
                for (Map.Entry<String, OnnxValue> output : result) {
                    String mapped = TensorConverter.asValidName(output.getKey());
                    outputs.put(mapped, TensorConverter.toVespaTensor(output.getValue()));
                }
                return outputs;
            }
        } catch (OrtException e) {
            throw new RuntimeException("ONNX Runtime exception", e);
        } finally {
            if (onnxInputs != null) {
                onnxInputs.values().forEach(OnnxTensor::close);
            }
        }
    }

    public record IdAndType(String id, TensorType type) { }

    private Map<String, IdAndType> toSpecMap(Map<String, NodeInfo> infoMap) {
        Map<String, IdAndType> result = new HashMap<>();
        for (var info : infoMap.entrySet()) {
            String name = info.getKey();
            String ident = TensorConverter.asValidName(name);
            TensorType t = TensorConverter.toVespaType(info.getValue().getInfo());
            result.put(name, new IdAndType(ident, t));
        }
        return result;
    }

    public Map<String, IdAndType> getInputs() {
        try {
            return toSpecMap(session.instance().getInputInfo());
        } catch (OrtException e) {
            throw new RuntimeException("ONNX Runtime exception", e);
        }
    }

    public Map<String, IdAndType> getOutputs() {
        try {
            return toSpecMap(session.instance().getOutputInfo());
        } catch (OrtException e) {
            throw new RuntimeException("ONNX Runtime exception", e);
        }
    }

    public Map<String, TensorType> getInputInfo() {
        try {
            return TensorConverter.toVespaTypes(session.instance().getInputInfo());
        } catch (OrtException e) {
            throw new RuntimeException("ONNX Runtime exception", e);
        }
    }

    public Map<String, TensorType> getOutputInfo() {
        try {
            return TensorConverter.toVespaTypes(session.instance().getOutputInfo());
        } catch (OrtException e) {
            throw new RuntimeException("ONNX Runtime exception", e);
        }
    }

    @Override
    public void close() throws IllegalStateException {
        try {
            session.close();
        } catch (UncheckedOrtException e) {
            throw new IllegalStateException("Failed to close ONNX session", e);
        } catch (IllegalStateException e) {
            throw new IllegalStateException("Already closed", e);
        }
    }

    private static ReferencedOrtSession createSession(ModelPathOrData model, OnnxRuntime runtime,
                                                      OnnxEvaluatorOptions options, boolean tryCuda) {
        if (options == null) {
            options = new OnnxEvaluatorOptions();
        }
        try {
            boolean loadCuda = tryCuda && options.requestingGpu();
            ReferencedOrtSession session = runtime.acquireSession(model, options, loadCuda);
            if (loadCuda) {
                LOG.log(Level.INFO, "Created session with CUDA using GPU device " + options.gpuDeviceNumber());
            }
            return session;
        } catch (OrtException e) {
            if (e.getCode() == OrtException.OrtErrorCode.ORT_NO_SUCHFILE) {
                throw new IllegalArgumentException("No such file: " + model.path().get());
            }
            if (tryCuda && isCudaError(e) && !options.gpuDeviceRequired()) {
                LOG.log(Level.INFO, "Failed to create session with CUDA using GPU device " +
                                       options.gpuDeviceNumber() + ". Falling back to CPU. Reason: " + e.getMessage());
                return createSession(model, runtime, options, false);
            }
            if (isCudaError(e)) {
                throw new IllegalArgumentException("GPU device is required, but CUDA initialization failed", e);
            }
            throw new RuntimeException("ONNX Runtime exception", e);
        }
    }

    // For unit testing
    OrtSession ortSession() { return session.instance(); }

    private String mapToInternalName(String outputName) throws OrtException {
        var info = session.instance().getOutputInfo();
        var internalNames = info.keySet();
        for (String name : internalNames) {
            if (name.equals(outputName)) {
                return name;
            }
        }
        for (String name : internalNames) {
            String mapped = TensorConverter.asValidName(name);
            if (mapped.equals(outputName)) {
                return name;
            }
        }
        // Probably will not work, but give the correct error from session.run
        return outputName;
    }

}