forked from apache/mxnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Clojure] Clojure BERT QA example (apache#14691)
* Initial working example for bert qa * add RAT rename core to infer add integration test * add rat for project.clj * Couldn’t resist adding a qa about Clojure * rat for readme * feedback from @kedarbellare
- Loading branch information
Showing
7 changed files
with
400 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
/target | ||
/classes | ||
/checkouts | ||
profiles.clj | ||
pom.xml | ||
pom.xml.asc | ||
*.jar | ||
*.class | ||
/.lein-* | ||
/.nrepl-port | ||
.hgignore | ||
.hg/ |
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,91 @@ | ||
<!--- Licensed to the Apache Software Foundation (ASF) under one --> | ||
<!--- or more contributor license agreements. See the NOTICE file --> | ||
<!--- distributed with this work for additional information --> | ||
<!--- regarding copyright ownership. The ASF licenses this file --> | ||
<!--- to you under the Apache License, Version 2.0 (the --> | ||
<!--- "License"); you may not use this file except in compliance --> | ||
<!--- with the License. You may obtain a copy of the License at --> | ||
|
||
<!--- http://www.apache.org/licenses/LICENSE-2.0 --> | ||
|
||
<!--- Unless required by applicable law or agreed to in writing, --> | ||
<!--- software distributed under the License is distributed on an --> | ||
<!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY --> | ||
<!--- KIND, either express or implied. See the License for the --> | ||
<!--- specific language governing permissions and limitations --> | ||
<!--- under the License. --> | ||
|
||
|
||
# bert-qa | ||
|
||
**This example was based off of the Java API one. It shows how to do inference with a pre-trained BERT network that is trained on Questions and Answers using the [SQuAD Dataset](https://rajpurkar.github.io/SQuAD-explorer/)** | ||
|
||
The pretrained model was created using GluonNLP and then exported to the MXNet symbol format. You can find more information in the background section below. | ||
|
||
In this tutorial, we will walk through the BERT QA model trained by MXNet. | ||
Users can provide a question with a paragraph contains answer to the model and | ||
the model will be able to find the best answer from the answer paragraph. | ||
|
||
Example: | ||
|
||
``` | ||
{:input-answer "Steam engines are external combustion engines, where the working fluid is separate from the combustion products. Non-combustion heat sources such as solar power, nuclear power or geothermal energy may be used. The ideal thermodynamic cycle used to analyze this process is called the Rankine cycle. In the cycle, water is heated and transforms into steam within a boiler operating at a high pressure. When expanded through pistons or turbines, mechanical work is done. The reduced-pressure steam is then condensed and pumped back into the boiler." | ||
:input-question "Along with geothermal and nuclear, what is a notable non-combustion heat source?" | ||
:ground-truth-answers ["solar" | ||
"solar power" | ||
"solar power, nuclear power or geothermal energysolar"]} | ||
``` | ||
|
||
The prediction in this case would be `solar power` | ||
|
||
## Setup Guide | ||
|
||
### Step 1: Download the model | ||
|
||
For this tutorial, you can get the model and vocabulary by running following bash file. This script will use `wget` to download these artifacts from AWS S3. | ||
|
||
From the example directory: | ||
|
||
```bash | ||
./get_bert_data.sh | ||
``` | ||
|
||
Some sample questions and answers are provide in the `squad-sample.edn` file. Some are taken directly from the SQuAD dataset and one was just made up. Feel free to edit the file and add your own! | ||
|
||
|
||
## To run | ||
|
||
* `lein install` in the root of the main project directory | ||
* cd into this project directory and do `lein run`. This will execute the cpu version. | ||
|
||
`lein run :cpu` - to run with cpu | ||
`lein run :gpu` - to run with gpu | ||
|
||
## Background | ||
|
||
To learn more about how BERT works in MXNet, please follow this [MXNet Gluon tutorial on NLP using BERT](https://medium.com/apache-mxnet/gluon-nlp-bert-6a489bdd3340). | ||
|
||
The model was extracted from MXNet GluonNLP with static length settings. | ||
|
||
[Download link for the script](https://gluon-nlp.mxnet.io/_downloads/bert.zip) | ||
|
||
The original description can be found in the [MXNet GluonNLP model zoo](https://gluon-nlp.mxnet.io/model_zoo/bert/index.html#bert-base-on-squad-1-1). | ||
```bash | ||
python static_finetune_squad.py --optimizer adam --accumulate 2 --batch_size 6 --lr 3e-5 --epochs 2 --gpu 0 --export | ||
|
||
``` | ||
This script will generate `json` and `param` fles that are the standard MXNet model files. | ||
By default, this model are using `bert_12_768_12` model with extra layers for QA jobs. | ||
|
||
After that, to be able to use it in Java, we need to export the dictionary from the script to parse the text | ||
to actual indexes. Please add the following lines after [this line](https://github.com/dmlc/gluon-nlp/blob/master/scripts/bert/staticbert/static_finetune_squad.py#L262). | ||
```python | ||
import json | ||
json_str = vocab.to_json() | ||
f = open("vocab.json", "w") | ||
f.write(json_str) | ||
f.close() | ||
``` | ||
This would export the token vocabulary in json format. | ||
Once you have these three files, you will be able to run this example without problems. | ||
|
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,29 @@ | ||
#!/bin/bash | ||
|
||
# Licensed to the Apache Software Foundation (ASF) under one | ||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you under the Apache License, Version 2.0 (the | ||
# "License"); you may not use this file except in compliance | ||
# with the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, | ||
# software distributed under the License is distributed on an | ||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
# KIND, either express or implied. See the License for the | ||
# specific language governing permissions and limitations | ||
# under the License. | ||
|
||
set -e | ||
|
||
data_path=model | ||
|
||
if [ ! -d "$data_path" ]; then | ||
mkdir -p "$data_path" | ||
curl https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci/BertQA/vocab.json -o $data_path/vocab.json | ||
curl https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci/BertQA/static_bert_qa-0002.params -o $data_path/static_bert_qa-0002.params | ||
curl https://s3.us-east-2.amazonaws.com/mxnet-scala/scala-example-ci/BertQA/static_bert_qa-symbol.json -o $data_path/static_bert_qa-symbol.json | ||
fi |
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,28 @@ | ||
;; | ||
;; Licensed to the Apache Software Foundation (ASF) under one or more | ||
;; contributor license agreements. See the NOTICE file distributed with | ||
;; this work for additional information regarding copyright ownership. | ||
;; The ASF licenses this file to You under the Apache License, Version 2.0 | ||
;; (the "License"); you may not use this file except in compliance with | ||
;; the License. You may obtain a copy of the License at | ||
;; | ||
;; http://www.apache.org/licenses/LICENSE-2.0 | ||
;; | ||
;; Unless required by applicable law or agreed to in writing, software | ||
;; distributed under the License is distributed on an "AS IS" BASIS, | ||
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
;; See the License for the specific language governing permissions and | ||
;; limitations under the License. | ||
;; | ||
|
||
|
||
(defproject bert-qa "0.1.0-SNAPSHOT" | ||
:description "BERT QA Example" | ||
:plugins [[lein-cljfmt "0.5.7"]] | ||
:dependencies [[org.clojure/clojure "1.9.0"] | ||
[org.apache.mxnet.contrib.clojure/clojure-mxnet "1.5.0-SNAPSHOT"] | ||
[cheshire "5.8.1"]] | ||
:pedantic? :skip | ||
:java-source-paths ["src/java"] | ||
:main bert-qa.infer | ||
:repl-options {:init-ns bert-qa.infer}) |
39 changes: 39 additions & 0 deletions
39
contrib/clojure-package/examples/bert-qa/squad-samples.edn
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,39 @@ | ||
;; | ||
;; Licensed to the Apache Software Foundation (ASF) under one or more | ||
;; contributor license agreements. See the NOTICE file distributed with | ||
;; this work for additional information regarding copyright ownership. | ||
;; The ASF licenses this file to You under the Apache License, Version 2.0 | ||
;; (the "License"); you may not use this file except in compliance with | ||
;; the License. You may obtain a copy of the License at | ||
;; | ||
;; http://www.apache.org/licenses/LICENSE-2.0 | ||
;; | ||
;; Unless required by applicable law or agreed to in writing, software | ||
;; distributed under the License is distributed on an "AS IS" BASIS, | ||
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
;; See the License for the specific language governing permissions and | ||
;; limitations under the License. | ||
;; | ||
|
||
|
||
[{:input-answer "Computational complexity theory is a branch of the theory of computation in theoretical computer science that focuses on classifying computational problems according to their inherent difficulty, and relating those classes to each other. A computational problem is understood to be a task that is in principle amenable to being solved by a computer, which is equivalent to stating that the problem may be solved by mechanical application of mathematical steps, such as an algorithm." | ||
:input-question "By what main attribute are computational problems classified utilizing computational complexity theory?" | ||
:ground-truth-answers ["Computational complexity theory" | ||
"Computational complexity theory" | ||
"complexity theory"]} | ||
{:input-answer "Steam engines are external combustion engines, where the working fluid is separate from the combustion products. Non-combustion heat sources such as solar power, nuclear power or geothermal energy may be used. The ideal thermodynamic cycle used to analyze this process is called the Rankine cycle. In the cycle, water is heated and transforms into steam within a boiler operating at a high pressure. When expanded through pistons or turbines, mechanical work is done. The reduced-pressure steam is then condensed and pumped back into the boiler." | ||
:input-question "Along with geothermal and nuclear, what is a notable non-combustion heat source?" | ||
:ground-truth-answers ["solar" | ||
"solar power" | ||
"solar power, nuclear power or geothermal energysolar"]} | ||
{:input-answer "In the 1960s, a series of discoveries, the most important of which was seafloor spreading, showed that the Earth's lithosphere, which includes the crust and rigid uppermost portion of the upper mantle, is separated into a number of tectonic plates that move across the plastically deforming, solid, upper mantle, which is called the asthenosphere. There is an intimate coupling between the movement of the plates on the surface and the convection of the mantle: oceanic plate motions and mantle convection currents always move in the same direction, because the oceanic lithosphere is the rigid upper thermal boundary layer of the convecting mantle. This coupling between rigid plates moving on the surface of the Earth and the convecting mantle is called plate tectonics." | ||
:input-question "What was the most important discovery that led to the understanding that Earth's lithosphere is separated into tectonic plates?" | ||
:ground-truth-answers ["seafloor spreading"]} | ||
;;; totally made up | ||
{:input-answer "Susan had a cat named Sammy when she lived in the green house." | ||
:input-question "What was Susan's cat named?" | ||
:ground-truth-answers ["Sammy" "sammy"]} | ||
;;; more or less from wikipedia on clojure | ||
{:input-answer "Rich Hickey is the creator of the Clojure language. Before Clojure, he developed dotLisp, a similar project based on the .NET platform, and three earlier attempts to provide interoperability between Lisp and Java: a Java foreign language interface for Common Lisp, A Foreign Object Interface for Lisp, and a Lisp-friendly interface to Java Servlets." | ||
:input-question "Who created Clojure?" | ||
:ground-truth-answers ["rich" "hickey"]}] |
159 changes: 159 additions & 0 deletions
159
contrib/clojure-package/examples/bert-qa/src/bert_qa/infer.clj
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,159 @@ | ||
;; | ||
;; Licensed to the Apache Software Foundation (ASF) under one or more | ||
;; contributor license agreements. See the NOTICE file distributed with | ||
;; this work for additional information regarding copyright ownership. | ||
;; The ASF licenses this file to You under the Apache License, Version 2.0 | ||
;; (the "License"); you may not use this file except in compliance with | ||
;; the License. You may obtain a copy of the License at | ||
;; | ||
;; http://www.apache.org/licenses/LICENSE-2.0 | ||
;; | ||
;; Unless required by applicable law or agreed to in writing, software | ||
;; distributed under the License is distributed on an "AS IS" BASIS, | ||
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
;; See the License for the specific language governing permissions and | ||
;; limitations under the License. | ||
;; | ||
|
||
|
||
(ns bert-qa.infer | ||
(:require [clojure.string :as string] | ||
[clojure.reflect :as r] | ||
[cheshire.core :as json] | ||
[clojure.java.io :as io] | ||
[clojure.set :as set] | ||
[org.apache.clojure-mxnet.dtype :as dtype] | ||
[org.apache.clojure-mxnet.context :as context] | ||
[org.apache.clojure-mxnet.layout :as layout] | ||
[org.apache.clojure-mxnet.ndarray :as ndarray] | ||
[org.apache.clojure-mxnet.infer :as infer] | ||
[clojure.pprint :as pprint])) | ||
|
||
(def model-path-prefix "model/static_bert_qa") | ||
;; epoch number of the model | ||
(def epoch 2) | ||
;; the vocabulary used in the model | ||
(def model-vocab "model/vocab.json") | ||
;; the input question | ||
;; the maximum length of the sequence | ||
(def seq-length 384) | ||
|
||
;;; data helpers | ||
|
||
(defn break-out-punctuation [s str-match] | ||
(->> (string/split (str s "<punc>") (re-pattern (str "\\" str-match))) | ||
(map #(string/replace % "<punc>" str-match)))) | ||
|
||
(defn break-out-punctuations [s] | ||
(if-let [target-char (first (re-seq #"[.,?!]" s))] | ||
(break-out-punctuation s target-char) | ||
[s])) | ||
|
||
(defn tokenize [s] | ||
(->> (string/split s #"\s+") | ||
(mapcat break-out-punctuations) | ||
(into []))) | ||
|
||
(defn pad [tokens pad-item num] | ||
(if (>= (count tokens) num) | ||
tokens | ||
(into tokens (repeat (- num (count tokens)) pad-item)))) | ||
|
||
(defn get-vocab [] | ||
(let [vocab (json/parse-stream (clojure.java.io/reader "model/vocab.json"))] | ||
{:idx->token (get vocab "idx_to_token") | ||
:token->idx (get vocab "token_to_idx")})) | ||
|
||
(defn tokens->idxs [token->idx tokens] | ||
(let [unk-idx (get token->idx "[UNK]")] | ||
(mapv #(get token->idx % unk-idx) tokens))) | ||
|
||
(defn idxs->tokens [idx->token idxs] | ||
(mapv #(get idx->token %) idxs)) | ||
|
||
(defn post-processing [result tokens] | ||
(let [output1 (ndarray/slice-axis result 2 0 1) | ||
output2 (ndarray/slice-axis result 2 1 2) | ||
;;; get the formatted logits result | ||
start-logits (ndarray/reshape output1 [0 -3]) | ||
end-logits (ndarray/reshape output2 [0 -3]) | ||
start-prob (ndarray/softmax start-logits) | ||
end-prob (ndarray/softmax end-logits) | ||
start-idx (-> (ndarray/argmax start-prob 1) | ||
(ndarray/->vec) | ||
(first)) | ||
end-idx (-> (ndarray/argmax end-prob 1) | ||
(ndarray/->vec) | ||
(first))] | ||
(if (> end-idx start-idx) | ||
(subvec tokens start-idx (inc end-idx)) | ||
(subvec tokens end-idx (inc end-idx))))) | ||
|
||
(defn make-predictor [ctx] | ||
(let [input-descs [{:name "data0" | ||
:shape [1 seq-length] | ||
:dtype dtype/FLOAT32 | ||
:layout layout/NT} | ||
{:name "data1" | ||
:shape [1 seq-length] | ||
:dtype dtype/FLOAT32 | ||
:layout layout/NT} | ||
{:name "data2" | ||
:shape [1] | ||
:dtype dtype/FLOAT32 | ||
:layout layout/N}] | ||
factory (infer/model-factory model-path-prefix input-descs)] | ||
(infer/create-predictor | ||
factory | ||
{:contexts [ctx] | ||
:epoch 2}))) | ||
|
||
(defn pre-processing [ctx idx->token token->idx qa-map] | ||
(let [{:keys [input-question input-answer ground-truth-answers]} qa-map | ||
;;; pre-processing tokenize sentence | ||
token-q (tokenize (string/lower-case input-question)) | ||
token-a (tokenize (string/lower-case input-answer)) | ||
valid-length (+ (count token-q) (count token-a)) | ||
;;; generate token types [0000...1111...0000] | ||
qa-embedded (into (pad [] 0 (count token-q)) | ||
(pad [] 1 (count token-a))) | ||
token-types (pad qa-embedded 0 seq-length) | ||
;;; make BERT pre-processing standard | ||
token-a (conj token-a "[SEP]") | ||
token-q (into [] (concat ["[CLS]"] token-q ["[SEP]"] token-a)) | ||
tokens (pad token-q "[PAD]" seq-length) | ||
;;; pre-processing - token to index translation | ||
|
||
indexes (tokens->idxs token->idx tokens)] | ||
{:input-batch [(ndarray/array indexes [1 seq-length] {:context ctx}) | ||
(ndarray/array token-types [1 seq-length] {:context ctx}) | ||
(ndarray/array [valid-length] [1] {:context ctx})] | ||
:tokens tokens | ||
:qa-map qa-map})) | ||
|
||
(defn infer [ctx] | ||
(let [ctx (context/default-context) | ||
predictor (make-predictor ctx) | ||
{:keys [idx->token token->idx]} (get-vocab) | ||
;;; samples taken from https://rajpurkar.github.io/SQuAD-explorer/explore/v2.0/dev/ | ||
question-answers (clojure.edn/read-string (slurp "squad-samples.edn"))] | ||
(doseq [qa-map question-answers] | ||
(let [{:keys [input-batch tokens qa-map]} (pre-processing ctx idx->token token->idx qa-map) | ||
result (first (infer/predict-with-ndarray predictor input-batch)) | ||
answer (post-processing result tokens)] | ||
(println "===============================") | ||
(println " Question Answer Data") | ||
(pprint/pprint qa-map) | ||
(println) | ||
(println " Predicted Answer: " answer) | ||
(println "==============================="))))) | ||
|
||
(defn -main [& args] | ||
(let [[dev] args] | ||
(if (= dev ":gpu") | ||
(infer (context/gpu)) | ||
(infer (context/cpu))))) | ||
|
||
(comment | ||
|
||
(infer :cpu)) |
Oops, something went wrong.