diff options
Diffstat (limited to 'config-model/src/main/java/com')
11 files changed, 139 insertions, 180 deletions
diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/RankProfile.java b/config-model/src/main/java/com/yahoo/searchdefinition/RankProfile.java index 937151c0d3a..16e494c2db1 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/RankProfile.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/RankProfile.java @@ -449,7 +449,7 @@ public class RankProfile implements Serializable, Cloneable { addRankProperty(new RankProperty(name, parameter)); } - private void addRankProperty(RankProperty rankProperty) { + public void addRankProperty(RankProperty rankProperty) { // Just the usual multimap semantics here List<RankProperty> properties = rankProperties.get(rankProperty.getName()); if (properties == null) { @@ -541,14 +541,15 @@ public class RankProfile implements Serializable, Cloneable { /** Returns an unmodifiable view of the functions in this */ public Map<String, RankingExpressionFunction> getFunctions() { - if (functions.isEmpty() && getInherited() == null) return Collections.emptyMap(); - if (functions.isEmpty()) return getInherited().getFunctions(); + if (functions.size() == 0 && getInherited() == null) return Collections.emptyMap(); + if (functions.size() == 0) return getInherited().getFunctions(); if (getInherited() == null) return Collections.unmodifiableMap(functions); // Neither is null Map<String, RankingExpressionFunction> allFunctions = new LinkedHashMap<>(getInherited().getFunctions()); allFunctions.putAll(functions); return Collections.unmodifiableMap(allFunctions); + } public int getKeepRankCount() { @@ -694,7 +695,7 @@ public class RankProfile implements Serializable, Cloneable { for (Map.Entry<String, RankingExpressionFunction> entry : functions.entrySet()) { RankingExpressionFunction rankingExpressionFunction = entry.getValue(); RankingExpression compiled = compile(rankingExpressionFunction.function().getBody(), queryProfiles, importedModels, getConstants(), inlineFunctions, expressionTransforms); - compiledFunctions.put(entry.getKey(), rankingExpressionFunction.withExpression(compiled)); + compiledFunctions.put(entry.getKey(), rankingExpressionFunction.withBody(compiled)); } return compiledFunctions; } @@ -897,7 +898,7 @@ public class RankProfile implements Serializable, Cloneable { /** A function in a rank profile */ public static class RankingExpressionFunction { - private ExpressionFunction function; + private final ExpressionFunction function; /** True if this should be inlined into calling expressions. Useful for very cheap functions. */ private final boolean inline; @@ -907,17 +908,13 @@ public class RankProfile implements Serializable, Cloneable { this.inline = inline; } - public void setReturnType(TensorType type) { - this.function = function.withReturnType(type); - } - public ExpressionFunction function() { return function; } public boolean inline() { return inline && function.arguments().isEmpty(); // only inline no-arg functions; } - public RankingExpressionFunction withExpression(RankingExpression expression) { + public RankingExpressionFunction withBody(RankingExpression expression) { return new RankingExpressionFunction(function.withBody(expression), inline); } diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java index a988da9664e..f42d5de21e8 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/Search.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/Search.java @@ -59,6 +59,9 @@ public class Search implements Serializable, ImmutableSearch { // Field sets private FieldSets fieldSets = new FieldSets(); + // Whether or not this object has been processed. + private boolean processed; + // The unique name of this search definition. private String name; @@ -582,6 +585,17 @@ public class Search implements Serializable, ImmutableSearch { return false; } + public void process() { + if (processed) { + throw new IllegalStateException("Search '" + getName() + "' already processed."); + } + processed = true; + } + + public boolean isProcessed() { + return processed; + } + /** * The field set settings for this search * diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/SearchBuilder.java b/config-model/src/main/java/com/yahoo/searchdefinition/SearchBuilder.java index 151ad02a3fa..3c2ebc058ac 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/SearchBuilder.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/SearchBuilder.java @@ -188,6 +188,10 @@ public class SearchBuilder { throw new IllegalArgumentException("Search has no name."); } String rawName = rawSearch.getName(); + if (rawSearch.isProcessed()) { + throw new IllegalArgumentException("A search definition with a search section called '" + rawName + + "' has already been processed."); + } for (Search search : searchList) { if (rawName.equals(search.getName())) { throw new IllegalArgumentException("A search definition with a search section called '" + rawName + @@ -243,7 +247,8 @@ public class SearchBuilder { DocumentModelBuilder builder = new DocumentModelBuilder(model); for (Search search : new SearchOrderer().order(searchList)) { - new FieldOperationApplierForSearch().process(search); // TODO: Why is this not in the regular list? + new FieldOperationApplierForSearch().process(search); + // These two needed for a couple of old unit tests, ideally these are just read from app process(search, deployLogger, new QueryProfiles(queryProfileRegistry), validate); built.add(search); } diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/derived/DerivedConfiguration.java b/config-model/src/main/java/com/yahoo/searchdefinition/derived/DerivedConfiguration.java index 7c2d9a3b0ad..9a00ee5bbd0 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/derived/DerivedConfiguration.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/derived/DerivedConfiguration.java @@ -74,11 +74,21 @@ public class DerivedConfiguration { QueryProfileRegistry queryProfiles, ImportedModels importedModels) { Validator.ensureNotNull("Search definition", search); + if ( ! search.isProcessed()) { + throw new IllegalArgumentException("Search '" + search.getName() + "' not processed."); + } this.search = search; if ( ! search.isDocumentsOnly()) { streamingFields = new VsmFields(search); streamingSummary = new VsmSummary(search); } + if (abstractSearchList != null) { + for (Search abstractSearch : abstractSearchList) { + if (!abstractSearch.isProcessed()) { + throw new IllegalArgumentException("Search '" + search.getName() + "' not processed."); + } + } + } if ( ! search.isDocumentsOnly()) { attributeFields = new AttributeFields(search); summaries = new Summaries(search, deployLogger); diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/derived/RawRankProfile.java b/config-model/src/main/java/com/yahoo/searchdefinition/derived/RawRankProfile.java index 279b5334187..c041d5c6a89 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/derived/RawRankProfile.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/derived/RawRankProfile.java @@ -13,7 +13,6 @@ import com.yahoo.searchlib.rankingexpression.integration.ml.ImportedModels; import com.yahoo.searchlib.rankingexpression.parser.ParseException; import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode; import com.yahoo.searchlib.rankingexpression.rule.SerializationContext; -import com.yahoo.tensor.TensorType; import com.yahoo.vespa.config.search.RankProfilesConfig; import java.nio.charset.Charset; @@ -24,7 +23,6 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; /** * A rank profile derived from a search definition, containing exactly the features available natively in the server @@ -182,39 +180,32 @@ public class RawRankProfile implements RankProfilesConfig.Producer { private void derivePropertiesAndSummaryFeaturesFromFunctions(Map<String, RankProfile.RankingExpressionFunction> functions) { if (functions.isEmpty()) return; - - List<ExpressionFunction> functionExpressions = functions.values().stream().map(f -> f.function()).collect(Collectors.toList()); + Map<String, ExpressionFunction> expressionFunctions = new LinkedHashMap<>(); + for (Map.Entry<String, RankProfile.RankingExpressionFunction> function : functions.entrySet()) { + expressionFunctions.put(function.getKey(), function.getValue().function()); + } Map<String, String> functionProperties = new LinkedHashMap<>(); - functionProperties.putAll(deriveFunctionProperties(functions, functionExpressions)); - + functionProperties.putAll(deriveFunctionProperties(expressionFunctions)); if (firstPhaseRanking != null) { - functionProperties.putAll(firstPhaseRanking.getRankProperties(functionExpressions)); + functionProperties.putAll(firstPhaseRanking.getRankProperties(new ArrayList<>(expressionFunctions.values()))); } if (secondPhaseRanking != null) { - functionProperties.putAll(secondPhaseRanking.getRankProperties(functionExpressions)); + functionProperties.putAll(secondPhaseRanking.getRankProperties(new ArrayList<>(expressionFunctions.values()))); } for (Map.Entry<String, String> e : functionProperties.entrySet()) { rankProperties.add(new RankProfile.RankProperty(e.getKey(), e.getValue())); } - SerializationContext context = new SerializationContext(functionExpressions, null, functionProperties); + SerializationContext context = new SerializationContext(expressionFunctions.values(), null, functionProperties); replaceFunctionSummaryFeatures(context); } - private Map<String, String> deriveFunctionProperties(Map<String, RankProfile.RankingExpressionFunction> functions, - List<ExpressionFunction> functionExpressions) { - SerializationContext context = new SerializationContext(functionExpressions); - for (Map.Entry<String, RankProfile.RankingExpressionFunction> e : functions.entrySet()) { - String expressionString = e.getValue().function().getBody().getRoot().toString(new StringBuilder(), context, null, null).toString(); - context.addFunctionSerialization(RankingExpression.propertyName(e.getKey()), expressionString); - - for (Map.Entry<String, TensorType> argumentType : e.getValue().function().argumentTypes().entrySet()) - context.addArgumentTypeSerialization(e.getKey(), argumentType.getKey(), argumentType.getValue()); - if (e.getValue().function().returnType().isPresent()) - context.addFunctionTypeSerialization(e.getKey(), e.getValue().function().returnType().get()); - else if (e.getValue().function().arguments().isEmpty()) - throw new IllegalStateException("Type of function '" + e.getKey() + "' is not resolved"); + private Map<String, String> deriveFunctionProperties(Map<String, ExpressionFunction> functions) { + SerializationContext context = new SerializationContext(functions); + for (Map.Entry<String, ExpressionFunction> e : functions.entrySet()) { + String expression = e.getValue().getBody().getRoot().toString(new StringBuilder(), context, null, null).toString(); + context.addFunctionSerialization(RankingExpression.propertyName(e.getKey()), expression); } return context.serializedFunctions(); } diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/processing/Processing.java b/config-model/src/main/java/com/yahoo/searchdefinition/processing/Processing.java index 15d295736c1..8c8c32389e2 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/processing/Processing.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/processing/Processing.java @@ -7,8 +7,10 @@ import com.yahoo.searchdefinition.Search; import com.yahoo.searchdefinition.processing.multifieldresolver.RankProfileTypeSettingsProcessor; import com.yahoo.vespa.model.container.search.QueryProfiles; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.List; /** * Executor of processors. This defines the right order of processor execution. @@ -73,20 +75,12 @@ public class Processing { ReferenceFieldsProcessor::new, FastAccessValidator::new, ReservedFunctionNames::new, - RankingExpressionTypeResolver::new, + RankingExpressionTypeValidator::new, // These should be last: IndexingValidation::new, IndexingValues::new); } - /** Processors of rank profiles only (those who tolerate and so something useful when the search field is null) */ - private Collection<ProcessorFactory> rankProfileProcessors() { - return Arrays.asList( - RankProfileTypeSettingsProcessor::new, - ReservedFunctionNames::new, - RankingExpressionTypeResolver::new); - } - /** * Runs all search processors on the given {@link Search} object. These will modify the search object, <b>possibly * exchanging it with another</b>, as well as its document types. @@ -99,26 +93,12 @@ public class Processing { public void process(Search search, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfiles queryProfiles, boolean validate, boolean documentsOnly) { Collection<ProcessorFactory> factories = processors(); + search.process(); factories.stream() .map(factory -> factory.create(search, deployLogger, rankProfileRegistry, queryProfiles)) .forEach(processor -> processor.process(validate, documentsOnly)); } - /** - * Runs rank profiles processors only. - * - * @param deployLogger The log to log messages and warnings for application deployment to - * @param rankProfileRegistry a {@link com.yahoo.searchdefinition.RankProfileRegistry} - * @param queryProfiles The query profiles contained in the application this search is part of. - */ - public void processRankProfiles(DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, - QueryProfiles queryProfiles, boolean validate, boolean documentsOnly) { - Collection<ProcessorFactory> factories = rankProfileProcessors(); - factories.stream() - .map(factory -> factory.create(null, deployLogger, rankProfileRegistry, queryProfiles)) - .forEach(processor -> processor.process(validate, documentsOnly)); - } - @FunctionalInterface public interface ProcessorFactory { Processor create(Search search, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfiles queryProfiles); diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/processing/RankingExpressionTypeResolver.java b/config-model/src/main/java/com/yahoo/searchdefinition/processing/RankingExpressionTypeValidator.java index 4c8b5910b78..102d1910360 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/processing/RankingExpressionTypeResolver.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/processing/RankingExpressionTypeValidator.java @@ -7,44 +7,39 @@ import com.yahoo.searchdefinition.RankProfile; import com.yahoo.searchdefinition.RankProfileRegistry; import com.yahoo.searchdefinition.Search; import com.yahoo.searchlib.rankingexpression.RankingExpression; -import com.yahoo.searchlib.rankingexpression.Reference; import com.yahoo.searchlib.rankingexpression.rule.ExpressionNode; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.TypeContext; import com.yahoo.vespa.model.container.search.QueryProfiles; -import java.util.Map; - /** - * Resolves and assigns types to all functions in a ranking expression, and - * validates the types of all ranking expressions under a search instance: + * Validates the types of all ranking expressions under a search instance: * Some operators constrain the types of inputs, and first-and second-phase expressions - * must return scalar values. - * - * In addition, the existence of all referred attribute, query and constant + * must return scalar values. In addition, the existence of all referred attribute, query and constant * features is ensured. * * @author bratseth */ -public class RankingExpressionTypeResolver extends Processor { +public class RankingExpressionTypeValidator extends Processor { private final QueryProfileRegistry queryProfiles; - public RankingExpressionTypeResolver(Search search, - DeployLogger deployLogger, - RankProfileRegistry rankProfileRegistry, - QueryProfiles queryProfiles) { + public RankingExpressionTypeValidator(Search search, + DeployLogger deployLogger, + RankProfileRegistry rankProfileRegistry, + QueryProfiles queryProfiles) { super(search, deployLogger, rankProfileRegistry, queryProfiles); this.queryProfiles = queryProfiles.getRegistry(); } @Override public void process(boolean validate, boolean documentsOnly) { + if ( ! validate) return; if (documentsOnly) return; for (RankProfile profile : rankProfileRegistry.rankProfilesOf(search)) { try { - resolveTypesIn(profile, validate); + validate(profile); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("In " + search + ", " + profile, e); @@ -52,34 +47,20 @@ public class RankingExpressionTypeResolver extends Processor { } } - /** - * Resolves the types of all functions in the given profile - * - * @throws IllegalArgumentException if validate is true and the given rank profile does not produce valid types - */ - private void resolveTypesIn(RankProfile profile, boolean validate) { - TypeContext<Reference> context = profile.typeContext(queryProfiles); - for (Map.Entry<String, RankProfile.RankingExpressionFunction> function : profile.getFunctions().entrySet()) { - if ( ! function.getValue().function().arguments().isEmpty()) continue; - TensorType type = resolveType(function.getValue().function().getBody(), - "function '" + function.getKey() + "'", - context); - function.getValue().setReturnType(type); - } - - if (validate) { - profile.getSummaryFeatures().forEach(f -> resolveType(f, "summary feature " + f, context)); - ensureValidDouble(profile.getFirstPhaseRanking(), "first-phase expression", context); - ensureValidDouble(profile.getSecondPhaseRanking(), "second-phase expression", context); - } + /** Throws an IllegalArgumentException if the given rank profile does not produce valid type */ + private void validate(RankProfile profile) { + TypeContext context = profile.typeContext(queryProfiles); + profile.getSummaryFeatures().forEach(f -> ensureValid(f, "summary feature " + f, context)); + ensureValidDouble(profile.getFirstPhaseRanking(), "first-phase expression", context); + ensureValidDouble(profile.getSecondPhaseRanking(), "second-phase expression", context); } - private TensorType resolveType(RankingExpression expression, String expressionDescription, TypeContext context) { + private TensorType ensureValid(RankingExpression expression, String expressionDescription, TypeContext context) { if (expression == null) return null; - return resolveType(expression.getRoot(), expressionDescription, context); + return ensureValid(expression.getRoot(), expressionDescription, context); } - private TensorType resolveType(ExpressionNode expression, String expressionDescription, TypeContext context) { + private TensorType ensureValid(ExpressionNode expression, String expressionDescription, TypeContext context) { TensorType type; try { type = expression.type(context); @@ -94,7 +75,7 @@ public class RankingExpressionTypeResolver extends Processor { private void ensureValidDouble(RankingExpression expression, String expressionDescription, TypeContext context) { if (expression == null) return; - TensorType type = resolveType(expression, expressionDescription, context); + TensorType type = ensureValid(expression, expressionDescription, context); if ( ! type.equals(TensorType.empty)) throw new IllegalArgumentException("The " + expressionDescription + " must produce a double " + "(a tensor with no dimensions), but produces " + type); diff --git a/config-model/src/main/java/com/yahoo/searchdefinition/processing/multifieldresolver/RankProfileTypeSettingsProcessor.java b/config-model/src/main/java/com/yahoo/searchdefinition/processing/multifieldresolver/RankProfileTypeSettingsProcessor.java index 3bde76c1c79..ec4cbdfe58b 100644 --- a/config-model/src/main/java/com/yahoo/searchdefinition/processing/multifieldresolver/RankProfileTypeSettingsProcessor.java +++ b/config-model/src/main/java/com/yahoo/searchdefinition/processing/multifieldresolver/RankProfileTypeSettingsProcessor.java @@ -44,7 +44,6 @@ public class RankProfileTypeSettingsProcessor extends Processor { } private void processAttributeFields() { - if (search == null) return; // we're processing global profiles for (SDField field : search.allConcreteFields()) { Attribute attribute = field.getAttributes().get(field.getName()); if (attribute != null && attribute.tensorType().isPresent()) { @@ -54,7 +53,6 @@ public class RankProfileTypeSettingsProcessor extends Processor { } private void processImportedFields() { - if (search == null) return; // we're processing global profiles Optional<ImportedFields> importedFields = search.importedFields(); if (importedFields.isPresent()) { importedFields.get().fields().forEach((fieldName, field) -> processImportedField(field)); diff --git a/config-model/src/main/java/com/yahoo/vespa/model/Service.java b/config-model/src/main/java/com/yahoo/vespa/model/Service.java index 29ec26b06d2..620e44bc11a 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/Service.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/Service.java @@ -7,7 +7,7 @@ import java.util.HashMap; import java.util.Optional; /** - * Representation of a markProcessed which runs a service + * Representation of a process which runs a service * * @author gjoranv */ diff --git a/config-model/src/main/java/com/yahoo/vespa/model/VespaModel.java b/config-model/src/main/java/com/yahoo/vespa/model/VespaModel.java index 13304ea10ee..4b70b1b5ae2 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/VespaModel.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/VespaModel.java @@ -32,9 +32,7 @@ import com.yahoo.searchdefinition.RankProfileRegistry; import com.yahoo.searchdefinition.RankingConstants; import com.yahoo.searchdefinition.derived.AttributeFields; import com.yahoo.searchdefinition.derived.RankProfileList; -import com.yahoo.searchdefinition.processing.Processing; import com.yahoo.searchlib.rankingexpression.ExpressionFunction; -import com.yahoo.vespa.model.container.search.QueryProfiles; import com.yahoo.vespa.model.ml.ConvertedModel; import com.yahoo.searchlib.rankingexpression.RankingExpression; import com.yahoo.searchlib.rankingexpression.integration.ml.ImportedModel; @@ -170,7 +168,7 @@ public final class VespaModel extends AbstractConfigProducerRoot implements Seri createGlobalRankProfiles(deployState.getImportedModels(), deployState.rankProfileRegistry(), - deployState.getQueryProfiles()); + deployState.getQueryProfiles().getRegistry()); this.rankProfileList = new RankProfileList(null, // null search -> global rankingConstants, AttributeFields.empty, @@ -221,23 +219,26 @@ public final class VespaModel extends AbstractConfigProducerRoot implements Seri /** Adds generic application specific clusters of services */ private void addServiceClusters(ApplicationPackage app, VespaModelBuilder builder) { - serviceClusters.addAll(builder.getClusters(app, this)); + for (ServiceCluster sc : builder.getClusters(app, this)) + serviceClusters.add(sc); } /** - * Creates a rank profile not attached to any search definition, for each imported model in the application package, - * and adds it to the given rank profile registry. + * Creates a rank profile not attached to any search definition, for each imported model in the application package */ - private void createGlobalRankProfiles(ImportedModels importedModels, - RankProfileRegistry rankProfileRegistry, - QueryProfiles queryProfiles) { + private ImmutableList<RankProfile> createGlobalRankProfiles(ImportedModels importedModels, + RankProfileRegistry rankProfileRegistry, + QueryProfileRegistry queryProfiles) { + List<RankProfile> profiles = new ArrayList<>(); if ( ! importedModels.all().isEmpty()) { // models/ directory is available for (ImportedModel model : importedModels.all()) { RankProfile profile = new RankProfile(model.name(), this, rankProfileRegistry); rankProfileRegistry.add(profile); ConvertedModel convertedModel = ConvertedModel.fromSource(new ModelName(model.name()), - model.name(), profile, queryProfiles.getRegistry(), model); - convertedModel.expressions().values().forEach(f -> profile.addFunction(f, false)); + model.name(), profile, queryProfiles, model); + for (Map.Entry<String, RankingExpression> entry : convertedModel.expressions().entrySet()) { + profile.addFunction(new ExpressionFunction(entry.getKey(), entry.getValue()), false); + } } } else { // generated and stored model information may be available instead @@ -247,12 +248,12 @@ public final class VespaModel extends AbstractConfigProducerRoot implements Seri RankProfile profile = new RankProfile(modelName, this, rankProfileRegistry); rankProfileRegistry.add(profile); ConvertedModel convertedModel = ConvertedModel.fromStore(new ModelName(modelName), modelName, profile); - convertedModel.expressions().values().forEach(f -> profile.addFunction(f, false)); + for (Map.Entry<String, RankingExpression> entry : convertedModel.expressions().entrySet()) { + profile.addFunction(new ExpressionFunction(entry.getKey(), entry.getValue()), false); + } } } - new Processing().processRankProfiles(deployState.getDeployLogger(), - rankProfileRegistry, - queryProfiles, true, false); + return ImmutableList.copyOf(profiles); } /** Returns the global rank profiles as a rank profile list */ diff --git a/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java b/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java index fb0109ed32e..adf5c81283e 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java @@ -48,7 +48,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -68,14 +67,14 @@ public class ConvertedModel { private final ModelName modelName; private final String modelDescription; - private final ImmutableMap<String, ExpressionFunction> expressions; + private final ImmutableMap<String, RankingExpression> expressions; /** The source importedModel, or empty if this was created from a stored converted model */ private final Optional<ImportedModel> sourceModel; private ConvertedModel(ModelName modelName, String modelDescription, - Map<String, ExpressionFunction> expressions, + Map<String, RankingExpression> expressions, Optional<ImportedModel> sourceModel) { this.modelName = modelName; this.modelDescription = modelDescription; @@ -133,23 +132,23 @@ public class ConvertedModel { * if signatures are used, or the expression name if signatures are not used and there are multiple * expressions, and the second is the output name if signature names are used. */ - public Map<String, ExpressionFunction> expressions() { return expressions; } + public Map<String, RankingExpression> expressions() { return expressions; } /** * Returns the expression matching the given arguments. */ public ExpressionNode expression(FeatureArguments arguments, RankProfileTransformContext context) { - ExpressionFunction expression = selectExpression(arguments); - if (sourceModel.isPresent()) // we should verify - verifyInputs(expression.getBody(), sourceModel.get(), context.rankProfile(), context.queryProfiles()); - return expression.getBody().getRoot(); + RankingExpression expression = selectExpression(arguments); + if (sourceModel.isPresent()) // we can verify + verifyRequiredFunctions(expression, sourceModel.get(), context.rankProfile(), context.queryProfiles()); + return expression.getRoot(); } - private ExpressionFunction selectExpression(FeatureArguments arguments) { + private RankingExpression selectExpression(FeatureArguments arguments) { if (expressions.isEmpty()) throw new IllegalArgumentException("No expressions available in " + this); - ExpressionFunction expression = expressions.get(arguments.toName()); + RankingExpression expression = expressions.get(arguments.toName()); if (expression != null) return expression; if ( ! arguments.signature().isPresent()) { @@ -159,7 +158,7 @@ public class ConvertedModel { } if ( ! arguments.output().isPresent()) { - List<Map.Entry<String, ExpressionFunction>> entriesWithTheRightPrefix = + List<Map.Entry<String, RankingExpression>> entriesWithTheRightPrefix = expressions.entrySet().stream().filter(entry -> entry.getKey().startsWith(arguments.signature().get() + ".")).collect(Collectors.toList()); if (entriesWithTheRightPrefix.size() < 1) throw new IllegalArgumentException("No expressions named '" + arguments.signature().get() + @@ -180,10 +179,10 @@ public class ConvertedModel { // ----------------------- Static model conversion/storage below here - private static Map<String, ExpressionFunction> convertAndStore(ImportedModel model, - RankProfile profile, - QueryProfileRegistry queryProfiles, - ModelStore store) { + private static Map<String, RankingExpression> convertAndStore(ImportedModel model, + RankProfile profile, + QueryProfileRegistry queryProfiles, + ModelStore store) { // Add constants Set<String> constantsReplacedByFunctions = new HashSet<>(); model.smallConstants().forEach((k, v) -> transformSmallConstant(store, profile, k, v)); @@ -194,8 +193,8 @@ public class ConvertedModel { addGeneratedFunctions(model, profile); // Add expressions - Map<String, ExpressionFunction> expressions = new HashMap<>(); - for (Pair<String, ExpressionFunction> output : model.outputExpressions()) { + Map<String, RankingExpression> expressions = new HashMap<>(); + for (Pair<String, RankingExpression> output : model.outputExpressions()) { addExpression(output.getSecond(), output.getFirst(), constantsReplacedByFunctions, model, store, profile, queryProfiles, @@ -211,21 +210,21 @@ public class ConvertedModel { return expressions; } - private static void addExpression(ExpressionFunction expression, + private static void addExpression(RankingExpression expression, String expressionName, Set<String> constantsReplacedByFunctions, ImportedModel model, ModelStore store, RankProfile profile, QueryProfileRegistry queryProfiles, - Map<String, ExpressionFunction> expressions) { - expression = expression.withBody(replaceConstantsByFunctions(expression.getBody(), constantsReplacedByFunctions)); - reduceBatchDimensions(expression.getBody(), model, profile, queryProfiles); + Map<String, RankingExpression> expressions) { + expression = replaceConstantsByFunctions(expression, constantsReplacedByFunctions); + reduceBatchDimensions(expression, model, profile, queryProfiles); store.writeExpression(expressionName, expression); expressions.put(expressionName, expression); } - private static Map<String, ExpressionFunction> convertStored(ModelStore store, RankProfile profile) { + private static Map<String, RankingExpression> convertStored(ModelStore store, RankProfile profile) { for (Pair<String, Tensor> constant : store.readSmallConstants()) profile.addConstant(constant.getFirst(), asValue(constant.getSecond())); @@ -291,15 +290,15 @@ public class ConvertedModel { } /** - * Verify that the inputs declared in the given expression exists in the given rank profile as functions, - * and return tensors of the correct types. + * Verify that the functions referred in the given expression exists in the given rank profile, + * and return tensors of the types specified in requiredFunctions. */ - private static void verifyInputs(RankingExpression expression, ImportedModel model, - RankProfile profile, QueryProfileRegistry queryProfiles) { + private static void verifyRequiredFunctions(RankingExpression expression, ImportedModel model, + RankProfile profile, QueryProfileRegistry queryProfiles) { Set<String> functionNames = new HashSet<>(); addFunctionNamesIn(expression.getRoot(), functionNames, model); for (String functionName : functionNames) { - TensorType requiredType = model.inputs().get(functionName); + TensorType requiredType = model.requiredFunctions().get(functionName); if (requiredType == null) continue; // Not a required function RankProfile.RankingExpressionFunction rankingExpressionFunction = profile.getFunctions().get(functionName); @@ -376,7 +375,7 @@ public class ConvertedModel { List<ExpressionNode> children = ((TensorFunctionNode)node).children(); if (children.size() == 1 && children.get(0) instanceof ReferenceNode) { ReferenceNode referenceNode = (ReferenceNode) children.get(0); - if (model.inputs().containsKey(referenceNode.getName())) { + if (model.requiredFunctions().containsKey(referenceNode.getName())) { return reduceBatchDimensionExpression(tensorFunction, typeContext); } } @@ -384,7 +383,7 @@ public class ConvertedModel { } if (node instanceof ReferenceNode) { ReferenceNode referenceNode = (ReferenceNode) node; - if (model.inputs().containsKey(referenceNode.getName())) { + if (model.requiredFunctions().containsKey(referenceNode.getName())) { return reduceBatchDimensionExpression(TensorFunctionNode.wrapArgument(node), typeContext); } } @@ -452,8 +451,7 @@ public class ConvertedModel { Set<String> constantsReplacedByFunctions) { if (constantsReplacedByFunctions.isEmpty()) return expression; return new RankingExpression(expression.getName(), - replaceConstantsByFunctions(expression.getRoot(), - constantsReplacedByFunctions)); + replaceConstantsByFunctions(expression.getRoot(), constantsReplacedByFunctions)); } private static ExpressionNode replaceConstantsByFunctions(ExpressionNode node, Set<String> constantsReplacedByFunctions) { @@ -526,21 +524,19 @@ public class ConvertedModel { * @param name the name of this ranking expression - may have 1-3 parts separated by dot where the first part * is always the model name */ - void writeExpression(String name, ExpressionFunction expression) { - StringBuilder b = new StringBuilder(expression.getBody().getRoot().toString()); - for (Map.Entry<String, TensorType> input : expression.argumentTypes().entrySet()) - b.append('\n').append(input.getKey()).append('\t').append(input.getValue()); - application.getFile(modelFiles.expressionPath(name)).writeFile(new StringReader(b.toString())); + void writeExpression(String name, RankingExpression expression) { + application.getFile(modelFiles.expressionPath(name)) + .writeFile(new StringReader(expression.getRoot().toString())); } - Map<String, ExpressionFunction> readExpressions() { - Map<String, ExpressionFunction> expressions = new HashMap<>(); + Map<String, RankingExpression> readExpressions() { + Map<String, RankingExpression> expressions = new HashMap<>(); ApplicationFile expressionPath = application.getFile(modelFiles.expressionsPath()); if ( ! expressionPath.exists() || ! expressionPath.isDirectory()) return Collections.emptyMap(); for (ApplicationFile expressionFile : expressionPath.listFiles()) { - try (BufferedReader reader = new BufferedReader(expressionFile.createReader())){ + try (Reader reader = new BufferedReader(expressionFile.createReader())){ String name = expressionFile.getPath().getName(); - expressions.put(name, readExpression(name, reader)); + expressions.put(name, new RankingExpression(name, reader)); } catch (IOException e) { throw new UncheckedIOException("Failed reading " + expressionFile.getPath(), e); @@ -552,22 +548,8 @@ public class ConvertedModel { return expressions; } - private ExpressionFunction readExpression(String name, BufferedReader reader) - throws IOException, ParseException { - // First line is expression - RankingExpression expression = new RankingExpression(name, reader.readLine()); - // Next lines are inputs on the format name\ttensorTypeSpec - Map<String, TensorType> inputs = new LinkedHashMap<>(); - String line; - while (null != (line = reader.readLine())) { - String[] parts = line.split("\t"); - inputs.put(parts[0], TensorType.fromSpec(parts[1])); - } - return new ExpressionFunction(name, new ArrayList<>(inputs.keySet()), expression, inputs, Optional.empty()); - } - /** Adds this function expression to the application package so it can be read later. */ - public void writeFunction(String name, RankingExpression expression) { + void writeFunction(String name, RankingExpression expression) { application.getFile(modelFiles.functionsPath()).appendFile(name + "\t" + expression.getRoot().toString() + "\n"); } @@ -579,20 +561,20 @@ public class ConvertedModel { if ( ! file.exists()) return Collections.emptyList(); List<Pair<String, RankingExpression>> functions = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader(file.createReader())) { - String line; - while (null != (line = reader.readLine())) { - String[] parts = line.split("\t"); - String name = parts[0]; - try { - RankingExpression expression = new RankingExpression(parts[0], parts[1]); - functions.add(new Pair<>(name, expression)); - } catch (ParseException e) { - throw new IllegalStateException("Could not parse " + name, e); - } + BufferedReader reader = new BufferedReader(file.createReader()); + String line; + while (null != (line = reader.readLine())) { + String[] parts = line.split("\t"); + String name = parts[0]; + try { + RankingExpression expression = new RankingExpression(parts[0], parts[1]); + functions.add(new Pair<>(name, expression)); + } + catch (ParseException e) { + throw new IllegalStateException("Could not parse " + name, e); } - return functions; } + return functions; } catch (IOException e) { throw new UncheckedIOException(e); |