python训练的模型,转换为onnx模型后,用python代码可以方便进行推理,但是java代码如何实现呢?
首先ONNX 推理,可以使用onnxruntime
<dependency>
<groupId>com.microsoft.onnxruntime</groupId>
<artifactId>onnxruntime</artifactId>
<version>1.15.1</version>
</dependency>
另外,训练的模型需要用到bert分词器,将单词和字变成token id, github上有 https://github.com/ankiteciitkgp/bertTokenizer,我们基于这个库简单改造下,来适配bert onnx模型的输入,改造后代码见: https://github.com/jadepeng/bertTokenizer
主要新增了tokenizeOnnxTensor
方法,返回适配bert模型输入的onnx tensor
完整demo代码:
代码语言:javascript复制public class OnnxTests {
public static void main(String[] args) throws IOException, OrtException {
BertTokenizer bertTokenizer = new BertTokenizer("D:\model\vocab.txt");
var env = OrtEnvironment.getEnvironment();
var session = env.createSession("D:\model\output\onnx\fp16_model.onnx",
new OrtSession.SessionOptions());
var inputMap = bertTokenizer.tokenizeOnnxTensor(Arrays.asList("hello world 你好", "肿瘤治疗未来发展趋势"));
try (var results = session.run(inputMap)) {
System.out.println(results);
var embeddings = (float[][])results.get(0).getValue();
for (var embedding : embeddings) {
System.out.println(JSON.toJSONString(embedding));
}
}
}
}