Skip to content

Commit

Permalink
[ML] add support for distilbert pytorch models (#76679)
Browse files Browse the repository at this point in the history
This commit adds support for distilbert pytorch models.

While the tokenization itself is exactly the same as bert, the parameters sent to the model are different. 

DistilBERT does not require the segment mask or positional IDs to be sent. Only the input mask and token ids. 

But, since the effective output of the tokenization sent to the model is different, I opted to consider it as a unique
tokenizer, inheriting from our bert implementation.

The API now looks like:
for BERT models
```js
"inference_config": {
  "ner": {
    "vocabulary": {/*...*/},
    "tokenization": {
      "bert": {/*...*/}
    }
  }
}
```
For DistilBERT models
```js
"inference_config": {
  "ner": {
    "vocabulary": {/*...*/},
    "tokenization": {
      "distil_bert": {/*...*/}
    }
  }
}
```
  • Loading branch information
benwtrent committed Aug 24, 2021
1 parent 98bf4eb commit f913aae
Show file tree
Hide file tree
Showing 36 changed files with 820 additions and 269 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
import org.elasticsearch.xpack.core.ml.inference.results.RegressionInferenceResults;
import org.elasticsearch.xpack.core.ml.inference.results.SentimentAnalysisResults;
import org.elasticsearch.xpack.core.ml.inference.results.WarningInferenceResults;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.DistilBertTokenization;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.BertPassThroughConfig;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.BertTokenization;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.ClassificationConfig;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.ClassificationConfigUpdate;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.EmptyConfigUpdate;
Expand All @@ -46,6 +48,7 @@
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.StrictlyParsedInferenceConfig;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.StrictlyParsedTrainedModel;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.StrictlyParsedTrainedModelLocation;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.Tokenization;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.TrainedModel;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.TrainedModelLocation;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.ensemble.Ensemble;
Expand Down Expand Up @@ -189,6 +192,22 @@ public List<NamedXContentRegistry.Entry> getNamedXContentParsers() {
LangIdentNeuralNetwork.NAME,
LangIdentNeuralNetwork::fromXContentLenient));

// Tokenization
namedXContent.add(
new NamedXContentRegistry.Entry(
Tokenization.class,
BertTokenization.NAME,
(p, c) -> BertTokenization.fromXContent(p, (boolean) c)
)
);
namedXContent.add(
new NamedXContentRegistry.Entry(
Tokenization.class,
DistilBertTokenization.NAME,
(p, c) -> DistilBertTokenization.fromXContent(p, (boolean) c)
)
);

return namedXContent;
}

Expand Down Expand Up @@ -280,6 +299,22 @@ public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
namedWriteables.add(new NamedWriteableRegistry.Entry(TrainedModelLocation.class,
IndexLocation.INDEX.getPreferredName(), IndexLocation::new));

// Tokenization
namedWriteables.add(
new NamedWriteableRegistry.Entry(
Tokenization.class,
BertTokenization.NAME.getPreferredName(),
BertTokenization::new
)
);
namedWriteables.add(
new NamedWriteableRegistry.Entry(
Tokenization.class,
DistilBertTokenization.NAME.getPreferredName(),
DistilBertTokenization::new
)
);

return namedWriteables;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.ml.utils.NamedXContentObjectHelper;

import java.io.IOException;
import java.util.Objects;
Expand All @@ -36,31 +37,33 @@ public static BertPassThroughConfig fromXContentLenient(XContentParser parser) {

private static ConstructingObjectParser<BertPassThroughConfig, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<BertPassThroughConfig, Void> parser = new ConstructingObjectParser<>(NAME, ignoreUnknownFields,
a -> new BertPassThroughConfig((VocabularyConfig) a[0], (TokenizationParams) a[1]));
a -> new BertPassThroughConfig((VocabularyConfig) a[0], (Tokenization) a[1]));
parser.declareObject(ConstructingObjectParser.constructorArg(), VocabularyConfig.createParser(ignoreUnknownFields), VOCABULARY);
parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), TokenizationParams.createParser(ignoreUnknownFields),
TOKENIZATION_PARAMS);
parser.declareNamedObject(
ConstructingObjectParser.optionalConstructorArg(), (p, c, n) -> p.namedObject(Tokenization.class, n, ignoreUnknownFields),
TOKENIZATION
);
return parser;
}

private final VocabularyConfig vocabularyConfig;
private final TokenizationParams tokenizationParams;
private final Tokenization tokenization;

public BertPassThroughConfig(VocabularyConfig vocabularyConfig, @Nullable TokenizationParams tokenizationParams) {
public BertPassThroughConfig(VocabularyConfig vocabularyConfig, @Nullable Tokenization tokenization) {
this.vocabularyConfig = ExceptionsHelper.requireNonNull(vocabularyConfig, VOCABULARY);
this.tokenizationParams = tokenizationParams == null ? TokenizationParams.createDefault() : tokenizationParams;
this.tokenization = tokenization == null ? Tokenization.createDefault() : tokenization;
}

public BertPassThroughConfig(StreamInput in) throws IOException {
vocabularyConfig = new VocabularyConfig(in);
tokenizationParams = new TokenizationParams(in);
tokenization = in.readNamedWriteable(Tokenization.class);
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(VOCABULARY.getPreferredName(), vocabularyConfig);
builder.field(TOKENIZATION_PARAMS.getPreferredName(), tokenizationParams);
NamedXContentObjectHelper.writeNamedObject(builder, params, TOKENIZATION.getPreferredName(), tokenization);
builder.endObject();
return builder;
}
Expand All @@ -73,7 +76,7 @@ public String getWriteableName() {
@Override
public void writeTo(StreamOutput out) throws IOException {
vocabularyConfig.writeTo(out);
tokenizationParams.writeTo(out);
out.writeNamedWriteable(tokenization);
}

@Override
Expand Down Expand Up @@ -103,12 +106,12 @@ public boolean equals(Object o) {

BertPassThroughConfig that = (BertPassThroughConfig) o;
return Objects.equals(vocabularyConfig, that.vocabularyConfig)
&& Objects.equals(tokenizationParams, that.tokenizationParams);
&& Objects.equals(tokenization, that.tokenization);
}

@Override
public int hashCode() {
return Objects.hash(vocabularyConfig, tokenizationParams);
return Objects.hash(vocabularyConfig, tokenization);
}

@Override
Expand All @@ -117,7 +120,7 @@ public VocabularyConfig getVocabularyConfig() {
}

@Override
public TokenizationParams getTokenizationParams() {
return tokenizationParams;
public Tokenization getTokenization() {
return tokenization;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.core.ml.inference.trainedmodel;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ParseField;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.core.Nullable;

import java.io.IOException;

public class BertTokenization extends Tokenization {

public static final ParseField NAME = new ParseField("bert");

public static ConstructingObjectParser<BertTokenization, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<BertTokenization, Void> parser = new ConstructingObjectParser<>(
"bert_tokenization",
ignoreUnknownFields,
a -> new BertTokenization((Boolean) a[0], (Boolean) a[1], (Integer) a[2])
);
Tokenization.declareCommonFields(parser);
return parser;
}

private static final ConstructingObjectParser<BertTokenization, Void> LENIENT_PARSER = createParser(true);
private static final ConstructingObjectParser<BertTokenization, Void> STRICT_PARSER = createParser(false);

public static BertTokenization fromXContent(XContentParser parser, boolean lenient) {
return lenient ? LENIENT_PARSER.apply(parser, null) : STRICT_PARSER.apply(parser, null);
}

public BertTokenization(@Nullable Boolean doLowerCase, @Nullable Boolean withSpecialTokens, @Nullable Integer maxSequenceLength) {
super(doLowerCase, withSpecialTokens, maxSequenceLength);
}

public BertTokenization(StreamInput in) throws IOException {
super(in);
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}

XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
return builder;
}

@Override
public String getWriteableName() {
return NAME.getPreferredName();
}

@Override
public String getName() {
return NAME.getPreferredName();
}

@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
return super.equals(o);
}

@Override
public int hashCode() {
return super.hashCode();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.core.ml.inference.trainedmodel;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ParseField;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.core.Nullable;

import java.io.IOException;

public class DistilBertTokenization extends Tokenization {

public static final ParseField NAME = new ParseField("distil_bert");

public static ConstructingObjectParser<DistilBertTokenization, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<DistilBertTokenization, Void> parser = new ConstructingObjectParser<>(
"distil_bert_tokenization",
ignoreUnknownFields,
a -> new DistilBertTokenization((Boolean) a[0], (Boolean) a[1], (Integer) a[2])
);
Tokenization.declareCommonFields(parser);
return parser;
}

private static final ConstructingObjectParser<DistilBertTokenization, Void> LENIENT_PARSER = createParser(true);
private static final ConstructingObjectParser<DistilBertTokenization, Void> STRICT_PARSER = createParser(false);

public static DistilBertTokenization fromXContent(XContentParser parser, boolean lenient) {
return lenient ? LENIENT_PARSER.apply(parser, null) : STRICT_PARSER.apply(parser, null);
}

public DistilBertTokenization(
@Nullable Boolean doLowerCase,
@Nullable Boolean withSpecialTokens,
@Nullable Integer maxSequenceLength
) {
super(doLowerCase, withSpecialTokens, maxSequenceLength);
}

public DistilBertTokenization(StreamInput in) throws IOException {
super(in);
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}

XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
return builder;
}

@Override
public String getWriteableName() {
return NAME.getPreferredName();
}

@Override
public String getName() {
return NAME.getPreferredName();
}

@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
return super.equals(o);
}

@Override
public int hashCode() {
return super.hashCode();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.ml.utils.NamedXContentObjectHelper;

import java.io.IOException;
import java.util.Objects;
Expand All @@ -36,31 +37,33 @@ public static FillMaskConfig fromXContentLenient(XContentParser parser) {

private static ConstructingObjectParser<FillMaskConfig, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<FillMaskConfig, Void> parser = new ConstructingObjectParser<>(NAME, ignoreUnknownFields,
a -> new FillMaskConfig((VocabularyConfig) a[0], (TokenizationParams) a[1]));
a -> new FillMaskConfig((VocabularyConfig) a[0], (Tokenization) a[1]));
parser.declareObject(ConstructingObjectParser.constructorArg(), VocabularyConfig.createParser(ignoreUnknownFields), VOCABULARY);
parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), TokenizationParams.createParser(ignoreUnknownFields),
TOKENIZATION_PARAMS);
parser.declareNamedObject(
ConstructingObjectParser.optionalConstructorArg(), (p, c, n) -> p.namedObject(Tokenization.class, n, ignoreUnknownFields),
TOKENIZATION
);
return parser;
}

private final VocabularyConfig vocabularyConfig;
private final TokenizationParams tokenizationParams;
private final Tokenization tokenization;

public FillMaskConfig(VocabularyConfig vocabularyConfig, @Nullable TokenizationParams tokenizationParams) {
public FillMaskConfig(VocabularyConfig vocabularyConfig, @Nullable Tokenization tokenization) {
this.vocabularyConfig = ExceptionsHelper.requireNonNull(vocabularyConfig, VOCABULARY);
this.tokenizationParams = tokenizationParams == null ? TokenizationParams.createDefault() : tokenizationParams;
this.tokenization = tokenization == null ? Tokenization.createDefault() : tokenization;
}

public FillMaskConfig(StreamInput in) throws IOException {
vocabularyConfig = new VocabularyConfig(in);
tokenizationParams = new TokenizationParams(in);
tokenization = in.readNamedWriteable(Tokenization.class);
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(VOCABULARY.getPreferredName(), vocabularyConfig);
builder.field(TOKENIZATION_PARAMS.getPreferredName(), tokenizationParams);
NamedXContentObjectHelper.writeNamedObject(builder, params, TOKENIZATION.getPreferredName(), tokenization);
builder.endObject();
return builder;
}
Expand All @@ -73,7 +76,7 @@ public String getWriteableName() {
@Override
public void writeTo(StreamOutput out) throws IOException {
vocabularyConfig.writeTo(out);
tokenizationParams.writeTo(out);
out.writeNamedWriteable(tokenization);
}

@Override
Expand All @@ -98,12 +101,12 @@ public boolean equals(Object o) {

FillMaskConfig that = (FillMaskConfig) o;
return Objects.equals(vocabularyConfig, that.vocabularyConfig)
&& Objects.equals(tokenizationParams, that.tokenizationParams);
&& Objects.equals(tokenization, that.tokenization);
}

@Override
public int hashCode() {
return Objects.hash(vocabularyConfig, tokenizationParams);
return Objects.hash(vocabularyConfig, tokenization);
}

@Override
Expand All @@ -112,8 +115,8 @@ public VocabularyConfig getVocabularyConfig() {
}

@Override
public TokenizationParams getTokenizationParams() {
return tokenizationParams;
public Tokenization getTokenization() {
return tokenization;
}

@Override
Expand Down

0 comments on commit f913aae

Please sign in to comment.