summaryrefslogtreecommitdiffstats
path: root/model-evaluation/src/main/java/ai/vespa/models/evaluation/ModelsEvaluator.java
blob: 48c71b5a04abc78e9d18e76dd3faa9787f9faf96 (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
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.models.evaluation;

import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableMap;
import com.yahoo.component.AbstractComponent;
import com.yahoo.vespa.config.search.RankProfilesConfig;
import com.yahoo.vespa.config.search.core.RankingConstantsConfig;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * Evaluates machine-learned models added to Vespa applications and available as config form.
 * Usage:
 * <code>Tensor result = evaluator.bind("foo", value).bind("bar", value").evaluate()</code>
 *
 * @author bratseth
 */
@Beta
public class ModelsEvaluator extends AbstractComponent {

    private final ImmutableMap<String, Model> models;

    public ModelsEvaluator(RankProfilesConfig config, RankingConstantsConfig constantsConfig) {
        models = ImmutableMap.copyOf(new RankProfilesConfigImporter().importFrom(config, constantsConfig));
    }

    /** Returns the models of this as an immutable map */
    public Map<String, Model> models() { return models; }

    /**
     * Returns a function which can be used to evaluate the given function in the given model
     *
     * @param modelName the name of the model
     * @param names the 0-2 name components identifying the output to compute
     * @throws IllegalArgumentException if the function or model is not present
     */
    public FunctionEvaluator evaluatorOf(String modelName, String ... names) {
        return requireModel(modelName).evaluatorOf(names);
    }

    /** Returns the given model, or throws a IllegalArgumentException if it does not exist */
    public Model requireModel(String name) {
        Model model = models.get(name);
        if (model == null)
            throw new IllegalArgumentException("No model named '" + name + "'. Available models: " +
                                               String.join(", ", models.keySet()));
        return model;
    }

}