forked from elastic/elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pass in ModelLoadingService to the inference rescorer. #8
Open
jtibshirani
wants to merge
3
commits into
master
Choose a base branch
from
inference-rescorer
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
...lugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/search/InferenceRescorer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License; | ||
* you may not use this file except in compliance with the Elastic License. | ||
*/ | ||
|
||
package org.elasticsearch.xpack.ml.inference.search; | ||
|
||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
import org.apache.lucene.index.DocValues; | ||
import org.apache.lucene.index.LeafReaderContext; | ||
import org.apache.lucene.index.SortedNumericDocValues; | ||
import org.apache.lucene.search.DocIdSetIterator; | ||
import org.apache.lucene.search.Explanation; | ||
import org.apache.lucene.search.IndexSearcher; | ||
import org.apache.lucene.search.ScoreDoc; | ||
import org.apache.lucene.search.TopDocs; | ||
import org.elasticsearch.ElasticsearchException; | ||
import org.elasticsearch.index.fielddata.FieldData; | ||
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; | ||
import org.elasticsearch.search.rescore.RescoreContext; | ||
import org.elasticsearch.search.rescore.Rescorer; | ||
import org.elasticsearch.xpack.core.ml.inference.results.InferenceResults; | ||
import org.elasticsearch.xpack.core.ml.inference.results.SingleValueInferenceResults; | ||
import org.elasticsearch.xpack.core.ml.inference.results.WarningInferenceResults; | ||
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceConfig; | ||
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.RegressionConfig; | ||
import org.elasticsearch.xpack.ml.inference.loadingservice.Model; | ||
|
||
import java.io.IOException; | ||
import java.util.Arrays; | ||
import java.util.Comparator; | ||
import java.util.HashMap; | ||
import java.util.HashSet; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Set; | ||
|
||
public class InferenceRescorer implements Rescorer { | ||
|
||
private static final Logger logger = LogManager.getLogger(InferenceRescorer.class); | ||
|
||
private final Model model; | ||
private final InferenceConfig inferenceConfig; | ||
private final Map<String, String> fieldMap; | ||
private final InferenceRescorerBuilder.ScoreModeSettings scoreModeSettings; | ||
|
||
InferenceRescorer(Model model, | ||
InferenceConfig inferenceConfig, | ||
Map<String, String> fieldMap, | ||
InferenceRescorerBuilder.ScoreModeSettings scoreModeSettings) { | ||
this.model = model; | ||
this.inferenceConfig = inferenceConfig; | ||
this.fieldMap = fieldMap; | ||
this.scoreModeSettings = scoreModeSettings; | ||
|
||
assert inferenceConfig instanceof RegressionConfig; | ||
} | ||
|
||
@Override | ||
public TopDocs rescore(TopDocs topDocs, IndexSearcher searcher, RescoreContext rescoreContext) throws IOException { | ||
|
||
// Copy ScoreDoc[] and sort by ascending docID: | ||
ScoreDoc[] sortedHits = topDocs.scoreDocs.clone(); | ||
Comparator<ScoreDoc> docIdComparator = Comparator.comparingInt(sd -> sd.doc); | ||
Arrays.sort(sortedHits, docIdComparator); | ||
|
||
|
||
Set<String> fieldsToRead = new HashSet<>(model.getFieldNames()); | ||
// field map is fieldname in doc -> fieldname expected by model | ||
for (Map.Entry<String, String> entry : fieldMap.entrySet()) { | ||
if (fieldsToRead.contains(entry.getValue())) { | ||
// replace the model fieldname with the doc fieldname | ||
fieldsToRead.remove(entry.getValue()); | ||
fieldsToRead.add(entry.getKey()); | ||
} | ||
} | ||
|
||
List<LeafReaderContext> leaves = searcher.getIndexReader().getContext().leaves(); | ||
Map<String, Object> fields = new HashMap<>(); | ||
|
||
int currentReader = 0; | ||
int endDoc = 0; | ||
LeafReaderContext readerContext = null; | ||
|
||
for (int hitIndex = 0; hitIndex < sortedHits.length; hitIndex++) { | ||
ScoreDoc hit = sortedHits[hitIndex]; | ||
int docId = hit.doc; | ||
|
||
// get the context for this docId | ||
while (docId >= endDoc) { | ||
readerContext = leaves.get(currentReader); | ||
currentReader++; | ||
endDoc = readerContext.docBase + readerContext.reader().maxDoc(); | ||
} | ||
|
||
for (String field : fieldsToRead) { | ||
SortedNumericDocValues docValuesIter = DocValues.getSortedNumeric(readerContext.reader(), field); | ||
SortedNumericDoubleValues doubles = FieldData.sortableLongBitsToDoubles(docValuesIter); | ||
if (doubles.advanceExact(hit.doc)) { | ||
double val = doubles.nextValue(); | ||
fields.put(fieldMap.getOrDefault(field, field), val); | ||
} else if (docValuesIter.docID() == DocIdSetIterator.NO_MORE_DOCS) { | ||
logger.warn("No more docs for field {}, doc {}", field, hit.doc); | ||
fields.remove(field); | ||
} else { | ||
logger.warn("no value for field {}, doc {}", field, hit.doc); | ||
fields.remove(field); | ||
} | ||
} | ||
|
||
InferenceResults infer = model.infer(fields, inferenceConfig); | ||
if (infer instanceof WarningInferenceResults) { | ||
String message = ((WarningInferenceResults) infer).getWarning(); | ||
logger.warn("inference error: " + message); | ||
throw new ElasticsearchException(message); | ||
} else { | ||
SingleValueInferenceResults regressionResult = (SingleValueInferenceResults) infer; | ||
|
||
float combinedScore = scoreModeSettings.scoreMode.combine( | ||
hit.score * scoreModeSettings.queryWeight, | ||
regressionResult.value().floatValue() * scoreModeSettings.modelWeight | ||
); | ||
|
||
sortedHits[hitIndex] = new ScoreDoc(hit.doc, combinedScore); | ||
} | ||
} | ||
|
||
return new TopDocs(topDocs.totalHits, sortedHits); | ||
} | ||
|
||
@Override | ||
public Explanation explain(int topLevelDocId, IndexSearcher searcher, RescoreContext rescoreContext, Explanation sourceExplanation) { | ||
return Explanation.match(1.0, "because"); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is the same problem we have with the FetchSubPhase PR, we have make a blocking call somewhere