├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .prettierrc.json ├── CHANGELOG.md ├── DistilBERT_to_SavedModel.ipynb ├── LICENSE ├── README.md ├── jest.config.js ├── package-lock.json ├── package.json ├── scripts ├── benchmark.js ├── build.js ├── cli.js └── example.js ├── src ├── index.ts ├── models │ ├── bert.model.ts │ ├── distilbert.model.ts │ ├── index.ts │ ├── model.factory.ts │ ├── model.ts │ └── roberta.model.ts ├── qa-options.ts ├── qa.test.ts ├── qa.ts ├── runtimes │ ├── index.ts │ ├── remote.runtime.ts │ ├── runtime.ts │ ├── saved-model.runtime.ts │ ├── saved-model.worker-thread.ts │ ├── saved-model.worker.ts │ ├── tfjs.runtime.ts │ └── worker-message.ts ├── tokenizers │ ├── bert.tokenizer.ts │ ├── index.ts │ ├── roberta.tokenizer.ts │ ├── tokenizer.factory.ts │ └── tokenizer.ts └── utils.ts ├── tsconfig.json └── tsconfig.prod.json /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | build 4 | coverage 5 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "env": { 4 | "es6": true, 5 | "node": true 6 | }, 7 | "extends": [ 8 | "eslint:recommended", 9 | "plugin:prettier/recommended" 10 | ], 11 | "globals": { 12 | "Atomics": "readonly", 13 | "SharedArrayBuffer": "readonly" 14 | }, 15 | "parser": "@typescript-eslint/parser", 16 | "parserOptions": { 17 | "ecmaVersion": 2019, 18 | "sourceType": "module" 19 | }, 20 | "plugins": ["@typescript-eslint", "jest", "prettier", "simple-import-sort"], 21 | "rules": { 22 | "prettier/prettier": "warn", 23 | "simple-import-sort/sort": "warn", 24 | "@typescript-eslint/no-use-before-define": ["error", { "functions": false }] 25 | // "sort-imports": "warn", 26 | }, 27 | "overrides": [ 28 | { 29 | "files": "src/**", 30 | "extends": [ 31 | "plugin:@typescript-eslint/eslint-recommended", 32 | "plugin:@typescript-eslint/recommended", 33 | "plugin:jest/recommended", 34 | "plugin:jest/style", 35 | "prettier/@typescript-eslint" 36 | ], 37 | "rules": { 38 | "@typescript-eslint/no-var-requires": "off", 39 | "@typescript-eslint/camelcase": "warn" 40 | } 41 | } 42 | ] 43 | } 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | assets 3 | .models 4 | .vscode 5 | .yalc 6 | 7 | *.DS_Store 8 | 9 | # Logs 10 | logs 11 | *.log 12 | npm-debug.log* 13 | yarn-debug.log* 14 | yarn-error.log* 15 | lerna-debug.log* 16 | 17 | # Diagnostic reports (https://nodejs.org/api/report.html) 18 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 19 | 20 | # Runtime data 21 | pids 22 | *.pid 23 | *.seed 24 | *.pid.lock 25 | 26 | # Directory for instrumented libs generated by jscoverage/JSCover 27 | lib-cov 28 | 29 | # Coverage directory used by tools like istanbul 30 | coverage 31 | *.lcov 32 | 33 | # nyc test coverage 34 | .nyc_output 35 | 36 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 37 | .grunt 38 | 39 | # Bower dependency directory (https://bower.io/) 40 | bower_components 41 | 42 | # node-waf configuration 43 | .lock-wscript 44 | 45 | # Compiled binary addons (https://nodejs.org/api/addons.html) 46 | build/Release 47 | 48 | # Dependency directories 49 | node_modules/ 50 | jspm_packages/ 51 | 52 | # TypeScript v1 declaration files 53 | typings/ 54 | 55 | # TypeScript cache 56 | *.tsbuildinfo 57 | 58 | # Optional npm cache directory 59 | .npm 60 | 61 | # Optional eslint cache 62 | .eslintcache 63 | 64 | # Microbundle cache 65 | .rpt2_cache/ 66 | .rts2_cache_cjs/ 67 | .rts2_cache_es/ 68 | .rts2_cache_umd/ 69 | 70 | # Optional REPL history 71 | .node_repl_history 72 | 73 | # Output of 'npm pack' 74 | *.tgz 75 | 76 | # Yarn Integrity file 77 | .yarn-integrity 78 | 79 | # dotenv environment variables file 80 | .env 81 | .env.test 82 | 83 | # parcel-bundler cache (https://parceljs.org/) 84 | .cache 85 | 86 | # Next.js build output 87 | .next 88 | 89 | # Nuxt.js build / generate output 90 | .nuxt 91 | dist 92 | 93 | # Gatsby files 94 | .cache/ 95 | # Comment in the public line in if your project uses Gatsby and not Next.js 96 | # https://nextjs.org/blog/next-9-1#public-directory-support 97 | # public 98 | 99 | # vuepress build output 100 | .vuepress/dist 101 | 102 | # Serverless directories 103 | .serverless/ 104 | 105 | # FuseBox cache 106 | .fusebox/ 107 | 108 | # DynamoDB Local files 109 | .dynamodb/ 110 | 111 | # TernJS port file 112 | .tern-port 113 | 114 | # Stores VSCode versions used for testing VSCode extensions 115 | .vscode-test 116 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/prettierrc", 3 | "printWidth": 90 4 | } 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [3.0.0](https://github.com/huggingface/node-question-answering/compare/v2.0.0...v3.0.0) (2020-07-02) 2 | 3 | This version introduces full support for any DistilBERT/BERT/RoBERTa based models from the [Hugging Face model hub](https://huggingface.co/models). It also simplifies the model instantiation by introducing a single `initModel` factory method (and its equivalent `initTokenizer` if needed). 4 | 5 | ### BREAKING CHANGES 6 | 7 | * Nodejs v12 is now the minimum required version if using SavedModel format: for this model format, the library now makes use of a [worker thread](https://nodejs.org/docs/latest-v12.x/api/worker_threads.html) internally to provide full non-blocking processing of prediction requests, a feature that is only supported fully starting in version 12. 8 | * The model-specific instantiation methods are removed and replaced by a single `initModel` method paired with a `runtime` field which can either be `tfjs`, `saved_model` or `remote`. 9 | * When passing a tokenizer to `QAClient.fromOptions`, the tokenizer now needs to extends the abstract [`Tokenizer`](./src/tokenizers/tokenizer.ts) class, which itself is a wrapper around [🤗Tokenizers](https://github.com/huggingface/tokenizers). 10 | * The `cased` option is moved from the model instantiation to the `QAClient.fromOptions` method. 11 | 12 | ### Features 13 | 14 | * Added compatibility with BERT/RoBERTa based models 15 | * [15 new additional models](./README.md#models) available thanks to the [Hugging Face model hub](https://huggingface.co/models) and the NLP community 16 | * The model doesn't need to be downloaded through the CLI before running the code for the first time: if it's not present in the default (or specified) model directory, it will be automatically downloaded at runtime during initialization, along with vocabulary / tokenizer files. 17 | * [🤗Tokenizers](https://github.com/huggingface/tokenizers) now requires version `0.7.0`. 18 | 19 | ### How to migrate 20 | 21 | #### When using SavedModel format 22 | 23 | Before: 24 | ```typescript 25 | const model = await SavedModel.fromOptions({ path: "distilbert-uncased", cased: false }); 26 | const qaClient = await QAClient.fromOptions({ model }); 27 | ``` 28 | 29 | After: 30 | ```typescript 31 | const model = await initModel({ name: "distilbert-uncased" }); 32 | const qaClient = await QAClient.fromOptions({ model, cased: false }); 33 | // `cased` can be omitted: it will be based on the tokenizer configuration if possible, otherwise inferred from the model name 34 | ``` 35 | 36 | > ⚠️ Warning: due to a [bug in TFJS](https://github.com/tensorflow/tfjs/issues/3463), the use of `@tensorflow/tfjs-node` to load or execute SavedModel models independently from the library is not recommended for now, since it could overwrite the TF backend used internally by the library. In the case where you would have to do so, make sure to require _both_ `question-answering` _and_ `@tensorflow/tfjs-node` in your code __before making any use of either of them__. 37 | 38 | #### When using TFJS format 39 | 40 | Before: 41 | ```typescript 42 | const model = await TFJS.fromOptions({ path: "distilbert-uncased", cased: false }); 43 | const qaClient = await QAClient.fromOptions({ model }); 44 | ``` 45 | 46 | After: 47 | ```typescript 48 | const model = await initModel({ name: "distilbert-uncased", runtime: RuntimeType.TFJS }); 49 | const qaClient = await QAClient.fromOptions({ model }); // `cased` can be omitted (see SavedModel migration) 50 | ``` 51 | 52 | #### When using a remote model 53 | 54 | Before: 55 | ```typescript 56 | const model = await RemoteModel.fromOptions({ path: "http://localhost:8501/v1/models/cased" cased: false }); 57 | const qaClient = await QAClient.fromOptions({ model }); 58 | ``` 59 | 60 | After: 61 | ```typescript 62 | const model = await initModel({ 63 | name: "distilbert-uncased", 64 | path: "http://localhost:8501/v1/models/cased", 65 | runtime: RuntimeType.Remote 66 | }); 67 | const qaClient = await QAClient.fromOptions({ model }); // `cased` can be omitted (see SavedModel migration) 68 | ``` 69 | 70 | # [2.0.0](https://github.com/huggingface/node-question-answering/compare/v1.4.0...v2.0.0) (2020-03-10) 71 | 72 | This version introduces support for models in TFJS format. 73 | 74 | ### BREAKING CHANGES 75 | 76 | - 3 new classes implementing an abstract `Model` are introduced: `SavedModel`, `TFJSModel` and `RemoteModel`. They can be instanciated using a `.fromOptions` method. 77 | - The `model` field of the `QAClient.fromOptions` methods now expects a `Model` (sub)class instance. 78 | 79 | ### Features 80 | 81 | - Upgrade [🤗Tokenizers](https://github.com/huggingface/tokenizers) to `0.6.0` 82 | 83 | ### How to migrate 84 | 85 | #### When using a local SavedModel 86 | 87 | Before: 88 | ```typescript 89 | const qaClient = await QAClient.fromOptions({ 90 | model: { path: "distilbert-uncased", cased: false } 91 | }); 92 | ``` 93 | 94 | After: 95 | ```typescript 96 | const model = await SavedModel.fromOptions({ path: "distilbert-uncased", cased: false }); 97 | const qaClient = await QAClient.fromOptions({ model }); 98 | ``` 99 | 100 | #### When using a remote model server 101 | 102 | Before: 103 | ```typescript 104 | const qaClient = await QAClient.fromOptions({ 105 | model: { path: "distilbert-uncased", cased: false, remote: true } 106 | }); 107 | ``` 108 | 109 | After: 110 | ```typescript 111 | const model = await RemoteModel.fromOptions({ path: "http://localhost:8501/v1/models/cased", cased: false }); 112 | const qaClient = await QAClient.fromOptions({ model }); 113 | ``` 114 | -------------------------------------------------------------------------------- /DistilBERT_to_SavedModel.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "DistilBERT to SavedModel.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "widgets": { 15 | "application/vnd.jupyter.widget-state+json": { 16 | "ec868030d2ab43b186feb9afadc85c0e": { 17 | "model_module": "@jupyter-widgets/controls", 18 | "model_name": "HBoxModel", 19 | "state": { 20 | "_view_name": "HBoxView", 21 | "_dom_classes": [], 22 | "_model_name": "HBoxModel", 23 | "_view_module": "@jupyter-widgets/controls", 24 | "_model_module_version": "1.5.0", 25 | "_view_count": null, 26 | "_view_module_version": "1.5.0", 27 | "box_style": "", 28 | "layout": "IPY_MODEL_fe4a21c15a214825a1786fa2993a510f", 29 | "_model_module": "@jupyter-widgets/controls", 30 | "children": [ 31 | "IPY_MODEL_280516a510124392bebabbbb9b298074", 32 | "IPY_MODEL_8a02642bfe6a4bd3b2ad01cbd4e2db1e" 33 | ] 34 | } 35 | }, 36 | "fe4a21c15a214825a1786fa2993a510f": { 37 | "model_module": "@jupyter-widgets/base", 38 | "model_name": "LayoutModel", 39 | "state": { 40 | "_view_name": "LayoutView", 41 | "grid_template_rows": null, 42 | "right": null, 43 | "justify_content": null, 44 | "_view_module": "@jupyter-widgets/base", 45 | "overflow": null, 46 | "_model_module_version": "1.2.0", 47 | "_view_count": null, 48 | "flex_flow": null, 49 | "width": null, 50 | "min_width": null, 51 | "border": null, 52 | "align_items": null, 53 | "bottom": null, 54 | "_model_module": "@jupyter-widgets/base", 55 | "top": null, 56 | "grid_column": null, 57 | "overflow_y": null, 58 | "overflow_x": null, 59 | "grid_auto_flow": null, 60 | "grid_area": null, 61 | "grid_template_columns": null, 62 | "flex": null, 63 | "_model_name": "LayoutModel", 64 | "justify_items": null, 65 | "grid_row": null, 66 | "max_height": null, 67 | "align_content": null, 68 | "visibility": null, 69 | "align_self": null, 70 | "height": null, 71 | "min_height": null, 72 | "padding": null, 73 | "grid_auto_rows": null, 74 | "grid_gap": null, 75 | "max_width": null, 76 | "order": null, 77 | "_view_module_version": "1.2.0", 78 | "grid_template_areas": null, 79 | "object_position": null, 80 | "object_fit": null, 81 | "grid_auto_columns": null, 82 | "margin": null, 83 | "display": null, 84 | "left": null 85 | } 86 | }, 87 | "280516a510124392bebabbbb9b298074": { 88 | "model_module": "@jupyter-widgets/controls", 89 | "model_name": "IntProgressModel", 90 | "state": { 91 | "_view_name": "ProgressView", 92 | "style": "IPY_MODEL_dc2d6295f9c94375ac9f6303c47ffd8e", 93 | "_dom_classes": [], 94 | "description": "Downloading", 95 | "_model_name": "IntProgressModel", 96 | "bar_style": "success", 97 | "max": 1031, 98 | "_view_module": "@jupyter-widgets/controls", 99 | "_model_module_version": "1.5.0", 100 | "value": 1031, 101 | "_view_count": null, 102 | "_view_module_version": "1.5.0", 103 | "orientation": "horizontal", 104 | "min": 0, 105 | "description_tooltip": null, 106 | "_model_module": "@jupyter-widgets/controls", 107 | "layout": "IPY_MODEL_e21ee54a0ed3470da5bf411d5ed361ff" 108 | } 109 | }, 110 | "8a02642bfe6a4bd3b2ad01cbd4e2db1e": { 111 | "model_module": "@jupyter-widgets/controls", 112 | "model_name": "HTMLModel", 113 | "state": { 114 | "_view_name": "HTMLView", 115 | "style": "IPY_MODEL_0a8659f61de740ba873a8d99cbd452b2", 116 | "_dom_classes": [], 117 | "description": "", 118 | "_model_name": "HTMLModel", 119 | "placeholder": "​", 120 | "_view_module": "@jupyter-widgets/controls", 121 | "_model_module_version": "1.5.0", 122 | "value": "100% 1.03k/1.03k [00:00<00:00, 27.7kB/s]", 123 | "_view_count": null, 124 | "_view_module_version": "1.5.0", 125 | "description_tooltip": null, 126 | "_model_module": "@jupyter-widgets/controls", 127 | "layout": "IPY_MODEL_968d75363433455f966c346728fad87e" 128 | } 129 | }, 130 | "dc2d6295f9c94375ac9f6303c47ffd8e": { 131 | "model_module": "@jupyter-widgets/controls", 132 | "model_name": "ProgressStyleModel", 133 | "state": { 134 | "_view_name": "StyleView", 135 | "_model_name": "ProgressStyleModel", 136 | "description_width": "initial", 137 | "_view_module": "@jupyter-widgets/base", 138 | "_model_module_version": "1.5.0", 139 | "_view_count": null, 140 | "_view_module_version": "1.2.0", 141 | "bar_color": null, 142 | "_model_module": "@jupyter-widgets/controls" 143 | } 144 | }, 145 | "e21ee54a0ed3470da5bf411d5ed361ff": { 146 | "model_module": "@jupyter-widgets/base", 147 | "model_name": "LayoutModel", 148 | "state": { 149 | "_view_name": "LayoutView", 150 | "grid_template_rows": null, 151 | "right": null, 152 | "justify_content": null, 153 | "_view_module": "@jupyter-widgets/base", 154 | "overflow": null, 155 | "_model_module_version": "1.2.0", 156 | "_view_count": null, 157 | "flex_flow": null, 158 | "width": null, 159 | "min_width": null, 160 | "border": null, 161 | "align_items": null, 162 | "bottom": null, 163 | "_model_module": "@jupyter-widgets/base", 164 | "top": null, 165 | "grid_column": null, 166 | "overflow_y": null, 167 | "overflow_x": null, 168 | "grid_auto_flow": null, 169 | "grid_area": null, 170 | "grid_template_columns": null, 171 | "flex": null, 172 | "_model_name": "LayoutModel", 173 | "justify_items": null, 174 | "grid_row": null, 175 | "max_height": null, 176 | "align_content": null, 177 | "visibility": null, 178 | "align_self": null, 179 | "height": null, 180 | "min_height": null, 181 | "padding": null, 182 | "grid_auto_rows": null, 183 | "grid_gap": null, 184 | "max_width": null, 185 | "order": null, 186 | "_view_module_version": "1.2.0", 187 | "grid_template_areas": null, 188 | "object_position": null, 189 | "object_fit": null, 190 | "grid_auto_columns": null, 191 | "margin": null, 192 | "display": null, 193 | "left": null 194 | } 195 | }, 196 | "0a8659f61de740ba873a8d99cbd452b2": { 197 | "model_module": "@jupyter-widgets/controls", 198 | "model_name": "DescriptionStyleModel", 199 | "state": { 200 | "_view_name": "StyleView", 201 | "_model_name": "DescriptionStyleModel", 202 | "description_width": "", 203 | "_view_module": "@jupyter-widgets/base", 204 | "_model_module_version": "1.5.0", 205 | "_view_count": null, 206 | "_view_module_version": "1.2.0", 207 | "_model_module": "@jupyter-widgets/controls" 208 | } 209 | }, 210 | "968d75363433455f966c346728fad87e": { 211 | "model_module": "@jupyter-widgets/base", 212 | "model_name": "LayoutModel", 213 | "state": { 214 | "_view_name": "LayoutView", 215 | "grid_template_rows": null, 216 | "right": null, 217 | "justify_content": null, 218 | "_view_module": "@jupyter-widgets/base", 219 | "overflow": null, 220 | "_model_module_version": "1.2.0", 221 | "_view_count": null, 222 | "flex_flow": null, 223 | "width": null, 224 | "min_width": null, 225 | "border": null, 226 | "align_items": null, 227 | "bottom": null, 228 | "_model_module": "@jupyter-widgets/base", 229 | "top": null, 230 | "grid_column": null, 231 | "overflow_y": null, 232 | "overflow_x": null, 233 | "grid_auto_flow": null, 234 | "grid_area": null, 235 | "grid_template_columns": null, 236 | "flex": null, 237 | "_model_name": "LayoutModel", 238 | "justify_items": null, 239 | "grid_row": null, 240 | "max_height": null, 241 | "align_content": null, 242 | "visibility": null, 243 | "align_self": null, 244 | "height": null, 245 | "min_height": null, 246 | "padding": null, 247 | "grid_auto_rows": null, 248 | "grid_gap": null, 249 | "max_width": null, 250 | "order": null, 251 | "_view_module_version": "1.2.0", 252 | "grid_template_areas": null, 253 | "object_position": null, 254 | "object_fit": null, 255 | "grid_auto_columns": null, 256 | "margin": null, 257 | "display": null, 258 | "left": null 259 | } 260 | }, 261 | "f28831652abf44d094b780b26665158a": { 262 | "model_module": "@jupyter-widgets/controls", 263 | "model_name": "HBoxModel", 264 | "state": { 265 | "_view_name": "HBoxView", 266 | "_dom_classes": [], 267 | "_model_name": "HBoxModel", 268 | "_view_module": "@jupyter-widgets/controls", 269 | "_model_module_version": "1.5.0", 270 | "_view_count": null, 271 | "_view_module_version": "1.5.0", 272 | "box_style": "", 273 | "layout": "IPY_MODEL_3ae21229b7054c65b68963e00bed8e32", 274 | "_model_module": "@jupyter-widgets/controls", 275 | "children": [ 276 | "IPY_MODEL_755240ae4e2d45ebac9a66ba56326572", 277 | "IPY_MODEL_97752941239946a0b05d6721599848d7" 278 | ] 279 | } 280 | }, 281 | "3ae21229b7054c65b68963e00bed8e32": { 282 | "model_module": "@jupyter-widgets/base", 283 | "model_name": "LayoutModel", 284 | "state": { 285 | "_view_name": "LayoutView", 286 | "grid_template_rows": null, 287 | "right": null, 288 | "justify_content": null, 289 | "_view_module": "@jupyter-widgets/base", 290 | "overflow": null, 291 | "_model_module_version": "1.2.0", 292 | "_view_count": null, 293 | "flex_flow": null, 294 | "width": null, 295 | "min_width": null, 296 | "border": null, 297 | "align_items": null, 298 | "bottom": null, 299 | "_model_module": "@jupyter-widgets/base", 300 | "top": null, 301 | "grid_column": null, 302 | "overflow_y": null, 303 | "overflow_x": null, 304 | "grid_auto_flow": null, 305 | "grid_area": null, 306 | "grid_template_columns": null, 307 | "flex": null, 308 | "_model_name": "LayoutModel", 309 | "justify_items": null, 310 | "grid_row": null, 311 | "max_height": null, 312 | "align_content": null, 313 | "visibility": null, 314 | "align_self": null, 315 | "height": null, 316 | "min_height": null, 317 | "padding": null, 318 | "grid_auto_rows": null, 319 | "grid_gap": null, 320 | "max_width": null, 321 | "order": null, 322 | "_view_module_version": "1.2.0", 323 | "grid_template_areas": null, 324 | "object_position": null, 325 | "object_fit": null, 326 | "grid_auto_columns": null, 327 | "margin": null, 328 | "display": null, 329 | "left": null 330 | } 331 | }, 332 | "755240ae4e2d45ebac9a66ba56326572": { 333 | "model_module": "@jupyter-widgets/controls", 334 | "model_name": "IntProgressModel", 335 | "state": { 336 | "_view_name": "ProgressView", 337 | "style": "IPY_MODEL_a9d56b1b902b419395534a8023edce30", 338 | "_dom_classes": [], 339 | "description": "Downloading", 340 | "_model_name": "IntProgressModel", 341 | "bar_style": "success", 342 | "max": 260894952, 343 | "_view_module": "@jupyter-widgets/controls", 344 | "_model_module_version": "1.5.0", 345 | "value": 260894952, 346 | "_view_count": null, 347 | "_view_module_version": "1.5.0", 348 | "orientation": "horizontal", 349 | "min": 0, 350 | "description_tooltip": null, 351 | "_model_module": "@jupyter-widgets/controls", 352 | "layout": "IPY_MODEL_e25bf809fb7943b3ad26b0d21c02ee25" 353 | } 354 | }, 355 | "97752941239946a0b05d6721599848d7": { 356 | "model_module": "@jupyter-widgets/controls", 357 | "model_name": "HTMLModel", 358 | "state": { 359 | "_view_name": "HTMLView", 360 | "style": "IPY_MODEL_e30299b12fd64b009130b95965ab3642", 361 | "_dom_classes": [], 362 | "description": "", 363 | "_model_name": "HTMLModel", 364 | "placeholder": "​", 365 | "_view_module": "@jupyter-widgets/controls", 366 | "_model_module_version": "1.5.0", 367 | "value": "100% 261M/261M [00:04<00:00, 59.6MB/s]", 368 | "_view_count": null, 369 | "_view_module_version": "1.5.0", 370 | "description_tooltip": null, 371 | "_model_module": "@jupyter-widgets/controls", 372 | "layout": "IPY_MODEL_ec86b15ce977413ab5a4d3ae1152b352" 373 | } 374 | }, 375 | "a9d56b1b902b419395534a8023edce30": { 376 | "model_module": "@jupyter-widgets/controls", 377 | "model_name": "ProgressStyleModel", 378 | "state": { 379 | "_view_name": "StyleView", 380 | "_model_name": "ProgressStyleModel", 381 | "description_width": "initial", 382 | "_view_module": "@jupyter-widgets/base", 383 | "_model_module_version": "1.5.0", 384 | "_view_count": null, 385 | "_view_module_version": "1.2.0", 386 | "bar_color": null, 387 | "_model_module": "@jupyter-widgets/controls" 388 | } 389 | }, 390 | "e25bf809fb7943b3ad26b0d21c02ee25": { 391 | "model_module": "@jupyter-widgets/base", 392 | "model_name": "LayoutModel", 393 | "state": { 394 | "_view_name": "LayoutView", 395 | "grid_template_rows": null, 396 | "right": null, 397 | "justify_content": null, 398 | "_view_module": "@jupyter-widgets/base", 399 | "overflow": null, 400 | "_model_module_version": "1.2.0", 401 | "_view_count": null, 402 | "flex_flow": null, 403 | "width": null, 404 | "min_width": null, 405 | "border": null, 406 | "align_items": null, 407 | "bottom": null, 408 | "_model_module": "@jupyter-widgets/base", 409 | "top": null, 410 | "grid_column": null, 411 | "overflow_y": null, 412 | "overflow_x": null, 413 | "grid_auto_flow": null, 414 | "grid_area": null, 415 | "grid_template_columns": null, 416 | "flex": null, 417 | "_model_name": "LayoutModel", 418 | "justify_items": null, 419 | "grid_row": null, 420 | "max_height": null, 421 | "align_content": null, 422 | "visibility": null, 423 | "align_self": null, 424 | "height": null, 425 | "min_height": null, 426 | "padding": null, 427 | "grid_auto_rows": null, 428 | "grid_gap": null, 429 | "max_width": null, 430 | "order": null, 431 | "_view_module_version": "1.2.0", 432 | "grid_template_areas": null, 433 | "object_position": null, 434 | "object_fit": null, 435 | "grid_auto_columns": null, 436 | "margin": null, 437 | "display": null, 438 | "left": null 439 | } 440 | }, 441 | "e30299b12fd64b009130b95965ab3642": { 442 | "model_module": "@jupyter-widgets/controls", 443 | "model_name": "DescriptionStyleModel", 444 | "state": { 445 | "_view_name": "StyleView", 446 | "_model_name": "DescriptionStyleModel", 447 | "description_width": "", 448 | "_view_module": "@jupyter-widgets/base", 449 | "_model_module_version": "1.5.0", 450 | "_view_count": null, 451 | "_view_module_version": "1.2.0", 452 | "_model_module": "@jupyter-widgets/controls" 453 | } 454 | }, 455 | "ec86b15ce977413ab5a4d3ae1152b352": { 456 | "model_module": "@jupyter-widgets/base", 457 | "model_name": "LayoutModel", 458 | "state": { 459 | "_view_name": "LayoutView", 460 | "grid_template_rows": null, 461 | "right": null, 462 | "justify_content": null, 463 | "_view_module": "@jupyter-widgets/base", 464 | "overflow": null, 465 | "_model_module_version": "1.2.0", 466 | "_view_count": null, 467 | "flex_flow": null, 468 | "width": null, 469 | "min_width": null, 470 | "border": null, 471 | "align_items": null, 472 | "bottom": null, 473 | "_model_module": "@jupyter-widgets/base", 474 | "top": null, 475 | "grid_column": null, 476 | "overflow_y": null, 477 | "overflow_x": null, 478 | "grid_auto_flow": null, 479 | "grid_area": null, 480 | "grid_template_columns": null, 481 | "flex": null, 482 | "_model_name": "LayoutModel", 483 | "justify_items": null, 484 | "grid_row": null, 485 | "max_height": null, 486 | "align_content": null, 487 | "visibility": null, 488 | "align_self": null, 489 | "height": null, 490 | "min_height": null, 491 | "padding": null, 492 | "grid_auto_rows": null, 493 | "grid_gap": null, 494 | "max_width": null, 495 | "order": null, 496 | "_view_module_version": "1.2.0", 497 | "grid_template_areas": null, 498 | "object_position": null, 499 | "object_fit": null, 500 | "grid_auto_columns": null, 501 | "margin": null, 502 | "display": null, 503 | "left": null 504 | } 505 | } 506 | } 507 | } 508 | }, 509 | "cells": [ 510 | { 511 | "cell_type": "code", 512 | "metadata": { 513 | "id": "Lh0AAq89bdOb", 514 | "colab_type": "code", 515 | "outputId": "78480ae4-f3da-496f-9b3c-3bb46a3c38d6", 516 | "colab": { 517 | "base_uri": "https://localhost:8080/", 518 | "height": 712 519 | } 520 | }, 521 | "source": [ 522 | "!pip install git+https://github.com/huggingface/transformers" 523 | ], 524 | "execution_count": 1, 525 | "outputs": [ 526 | { 527 | "output_type": "stream", 528 | "text": [ 529 | "Collecting git+https://github.com/huggingface/transformers\n", 530 | " Cloning https://github.com/huggingface/transformers to /tmp/pip-req-build-ngv47fn_\n", 531 | " Running command git clone -q https://github.com/huggingface/transformers /tmp/pip-req-build-ngv47fn_\n", 532 | "Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from transformers==2.4.1) (1.17.5)\n", 533 | "Collecting tokenizers==0.0.11\n", 534 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/5e/36/7af38d572c935f8e0462ec7b4f7a46d73a2b3b1a938f50a5e8132d5b2dc5/tokenizers-0.0.11-cp36-cp36m-manylinux1_x86_64.whl (3.1MB)\n", 535 | "\u001b[K |████████████████████████████████| 3.1MB 3.4MB/s \n", 536 | "\u001b[?25hRequirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from transformers==2.4.1) (1.11.15)\n", 537 | "Requirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers==2.4.1) (3.0.12)\n", 538 | "Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers==2.4.1) (2.21.0)\n", 539 | "Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers==2.4.1) (4.28.1)\n", 540 | "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers==2.4.1) (2019.12.20)\n", 541 | "Collecting sentencepiece\n", 542 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/74/f4/2d5214cbf13d06e7cb2c20d84115ca25b53ea76fa1f0ade0e3c9749de214/sentencepiece-0.1.85-cp36-cp36m-manylinux1_x86_64.whl (1.0MB)\n", 543 | "\u001b[K |████████████████████████████████| 1.0MB 21.6MB/s \n", 544 | "\u001b[?25hCollecting sacremoses\n", 545 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/a6/b4/7a41d630547a4afd58143597d5a49e07bfd4c42914d8335b2a5657efc14b/sacremoses-0.0.38.tar.gz (860kB)\n", 546 | "\u001b[K |████████████████████████████████| 870kB 40.6MB/s \n", 547 | "\u001b[?25hRequirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.4.1) (0.3.3)\n", 548 | "Requirement already satisfied: botocore<1.15.0,>=1.14.15 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.4.1) (1.14.15)\n", 549 | "Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers==2.4.1) (0.9.4)\n", 550 | "Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.4.1) (2.8)\n", 551 | "Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.4.1) (3.0.4)\n", 552 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.4.1) (2019.11.28)\n", 553 | "Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers==2.4.1) (1.24.3)\n", 554 | "Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==2.4.1) (1.12.0)\n", 555 | "Requirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==2.4.1) (7.0)\n", 556 | "Requirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers==2.4.1) (0.14.1)\n", 557 | "Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.6/dist-packages (from botocore<1.15.0,>=1.14.15->boto3->transformers==2.4.1) (2.6.1)\n", 558 | "Requirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.15.0,>=1.14.15->boto3->transformers==2.4.1) (0.15.2)\n", 559 | "Building wheels for collected packages: transformers, sacremoses\n", 560 | " Building wheel for transformers (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 561 | " Created wheel for transformers: filename=transformers-2.4.1-cp36-none-any.whl size=477390 sha256=4a368cbe1c744dea99ca54647a214bb2b6f48b7f7acbf8e7ad9eefefcabdfeab\n", 562 | " Stored in directory: /tmp/pip-ephem-wheel-cache-xlrbobtu/wheels/70/d3/52/b3fa4f8b8ef04167ac62e5bb2accb62ae764db2a378247490e\n", 563 | " Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 564 | " Created wheel for sacremoses: filename=sacremoses-0.0.38-cp36-none-any.whl size=884628 sha256=999c7eaae21951a5369b2a1eaf3573df02f628d41298ba3b6104a379c50ad17a\n", 565 | " Stored in directory: /root/.cache/pip/wheels/6d/ec/1a/21b8912e35e02741306f35f66c785f3afe94de754a0eaf1422\n", 566 | "Successfully built transformers sacremoses\n", 567 | "Installing collected packages: tokenizers, sentencepiece, sacremoses, transformers\n", 568 | "Successfully installed sacremoses-0.0.38 sentencepiece-0.1.85 tokenizers-0.0.11 transformers-2.4.1\n" 569 | ], 570 | "name": "stdout" 571 | } 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "metadata": { 577 | "id": "9Uuqcd74Dzw8", 578 | "colab_type": "code", 579 | "outputId": "ef5d62ca-3f3e-4050-9fb4-ee955b311053", 580 | "colab": { 581 | "base_uri": "https://localhost:8080/", 582 | "height": 937 583 | } 584 | }, 585 | "source": [ 586 | "!pip install tf-nightly" 587 | ], 588 | "execution_count": 2, 589 | "outputs": [ 590 | { 591 | "output_type": "stream", 592 | "text": [ 593 | "Collecting tf-nightly\n", 594 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/6e/01/9325e4adad76b8c5fff0691107942d5728392261b1c6b7c9e89dd74d366f/tf_nightly-2.2.0.dev20200212-cp36-cp36m-manylinux2010_x86_64.whl (467.6MB)\n", 595 | "\u001b[K |████████████████████████████████| 467.6MB 32kB/s \n", 596 | "\u001b[?25hCollecting gast==0.3.3\n", 597 | " Downloading https://files.pythonhosted.org/packages/d6/84/759f5dd23fec8ba71952d97bcc7e2c9d7d63bdc582421f3cd4be845f0c98/gast-0.3.3-py2.py3-none-any.whl\n", 598 | "Requirement already satisfied: scipy==1.4.1; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (1.4.1)\n", 599 | "Collecting astunparse==1.6.3\n", 600 | " Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl\n", 601 | "Collecting tf-estimator-nightly\n", 602 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/2e/03/bacd7ee541e0e6be015651d2a6054b01cd21728e7ce1d4263b27c2f9fa16/tf_estimator_nightly-2.1.0.dev2020012309-py2.py3-none-any.whl (453kB)\n", 603 | "\u001b[K |████████████████████████████████| 460kB 41.8MB/s \n", 604 | "\u001b[?25hRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (1.1.0)\n", 605 | "Requirement already satisfied: six>=1.12.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (1.12.0)\n", 606 | "Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (1.27.1)\n", 607 | "Requirement already satisfied: wheel>=0.26; python_version >= \"3\" in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (0.34.2)\n", 608 | "Collecting tb-nightly<2.3.0a0,>=2.2.0a0\n", 609 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/46/72/b7b6d7c64a8c923b969f8a62a9a24dffcae69c1b86e86b0f4303173d443a/tb_nightly-2.2.0a20200214-py3-none-any.whl (3.9MB)\n", 610 | "\u001b[K |████████████████████████████████| 3.9MB 38.5MB/s \n", 611 | "\u001b[?25hCollecting h5py<2.11.0,>=2.10.0\n", 612 | "\u001b[?25l Downloading https://files.pythonhosted.org/packages/60/06/cafdd44889200e5438b897388f3075b52a8ef01f28a17366d91de0fa2d05/h5py-2.10.0-cp36-cp36m-manylinux1_x86_64.whl (2.9MB)\n", 613 | "\u001b[K |████████████████████████████████| 2.9MB 47.1MB/s \n", 614 | "\u001b[?25hRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (0.9.0)\n", 615 | "Requirement already satisfied: keras-preprocessing>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (1.1.0)\n", 616 | "Requirement already satisfied: protobuf>=3.8.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (3.10.0)\n", 617 | "Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (1.11.2)\n", 618 | "Requirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (0.1.8)\n", 619 | "Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (3.1.0)\n", 620 | "Requirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly) (1.17.5)\n", 621 | "Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (0.4.1)\n", 622 | "Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (1.7.2)\n", 623 | "Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (45.1.0)\n", 624 | "Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (1.0.0)\n", 625 | "Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (2.21.0)\n", 626 | "Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (3.2.1)\n", 627 | "Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (1.3.0)\n", 628 | "Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (0.2.8)\n", 629 | "Requirement already satisfied: rsa<4.1,>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (4.0)\n", 630 | "Requirement already satisfied: cachetools<3.2,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (3.1.1)\n", 631 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (2019.11.28)\n", 632 | "Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (3.0.4)\n", 633 | "Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (1.24.3)\n", 634 | "Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3,>=2.21.0->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (2.8)\n", 635 | "Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (3.1.0)\n", 636 | "Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.6/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tb-nightly<2.3.0a0,>=2.2.0a0->tf-nightly) (0.4.8)\n", 637 | "\u001b[31mERROR: tensorflow 1.15.0 has requirement gast==0.2.2, but you'll have gast 0.3.3 which is incompatible.\u001b[0m\n", 638 | "Installing collected packages: gast, astunparse, tf-estimator-nightly, tb-nightly, h5py, tf-nightly\n", 639 | " Found existing installation: gast 0.2.2\n", 640 | " Uninstalling gast-0.2.2:\n", 641 | " Successfully uninstalled gast-0.2.2\n", 642 | " Found existing installation: h5py 2.8.0\n", 643 | " Uninstalling h5py-2.8.0:\n", 644 | " Successfully uninstalled h5py-2.8.0\n", 645 | "Successfully installed astunparse-1.6.3 gast-0.3.3 h5py-2.10.0 tb-nightly-2.2.0a20200214 tf-estimator-nightly-2.1.0.dev2020012309 tf-nightly-2.2.0.dev20200212\n" 646 | ], 647 | "name": "stdout" 648 | } 649 | ] 650 | }, 651 | { 652 | "cell_type": "code", 653 | "metadata": { 654 | "id": "5ddCYWg9D3M_", 655 | "colab_type": "code", 656 | "outputId": "5308b979-046c-4e83-ba74-fdeb431c2ffa", 657 | "colab": { 658 | "base_uri": "https://localhost:8080/", 659 | "height": 116, 660 | "referenced_widgets": [ 661 | "ec868030d2ab43b186feb9afadc85c0e", 662 | "fe4a21c15a214825a1786fa2993a510f", 663 | "280516a510124392bebabbbb9b298074", 664 | "8a02642bfe6a4bd3b2ad01cbd4e2db1e", 665 | "dc2d6295f9c94375ac9f6303c47ffd8e", 666 | "e21ee54a0ed3470da5bf411d5ed361ff", 667 | "0a8659f61de740ba873a8d99cbd452b2", 668 | "968d75363433455f966c346728fad87e", 669 | "f28831652abf44d094b780b26665158a", 670 | "3ae21229b7054c65b68963e00bed8e32", 671 | "755240ae4e2d45ebac9a66ba56326572", 672 | "97752941239946a0b05d6721599848d7", 673 | "a9d56b1b902b419395534a8023edce30", 674 | "e25bf809fb7943b3ad26b0d21c02ee25", 675 | "e30299b12fd64b009130b95965ab3642", 676 | "ec86b15ce977413ab5a4d3ae1152b352" 677 | ] 678 | } 679 | }, 680 | "source": [ 681 | "import tensorflow as tf\n", 682 | "from transformers import TFDistilBertForQuestionAnswering\n", 683 | "\n", 684 | "distilbert = TFDistilBertForQuestionAnswering.from_pretrained('distilbert-base-cased-distilled-squad')" 685 | ], 686 | "execution_count": 3, 687 | "outputs": [ 688 | { 689 | "output_type": "display_data", 690 | "data": { 691 | "application/vnd.jupyter.widget-view+json": { 692 | "model_id": "ec868030d2ab43b186feb9afadc85c0e", 693 | "version_minor": 0, 694 | "version_major": 2 695 | }, 696 | "text/plain": [ 697 | "HBox(children=(IntProgress(value=0, description='Downloading', max=1031, style=ProgressStyle(description_width…" 698 | ] 699 | }, 700 | "metadata": { 701 | "tags": [] 702 | } 703 | }, 704 | { 705 | "output_type": "stream", 706 | "text": [ 707 | "\n" 708 | ], 709 | "name": "stdout" 710 | }, 711 | { 712 | "output_type": "display_data", 713 | "data": { 714 | "application/vnd.jupyter.widget-view+json": { 715 | "model_id": "f28831652abf44d094b780b26665158a", 716 | "version_minor": 0, 717 | "version_major": 2 718 | }, 719 | "text/plain": [ 720 | "HBox(children=(IntProgress(value=0, description='Downloading', max=260894952, style=ProgressStyle(description_…" 721 | ] 722 | }, 723 | "metadata": { 724 | "tags": [] 725 | } 726 | }, 727 | { 728 | "output_type": "stream", 729 | "text": [ 730 | "\n" 731 | ], 732 | "name": "stdout" 733 | } 734 | ] 735 | }, 736 | { 737 | "cell_type": "code", 738 | "metadata": { 739 | "id": "Y-3Io24fEI26", 740 | "colab_type": "code", 741 | "outputId": "da73cf5e-f2c0-454f-8a37-bf01eb4a9018", 742 | "colab": { 743 | "base_uri": "https://localhost:8080/", 744 | "height": 208 745 | } 746 | }, 747 | "source": [ 748 | "concrete_function = tf.function(distilbert.call).get_concrete_function([tf.TensorSpec([None, 384], tf.int32, name=\"input_ids\"), tf.TensorSpec([None, 384], tf.int32, name=\"attention_mask\")])\n", 749 | "tf.saved_model.save(distilbert, 'distilbert_cased_savedmodel', signatures=concrete_function)" 750 | ], 751 | "execution_count": 4, 752 | "outputs": [ 753 | { 754 | "output_type": "stream", 755 | "text": [ 756 | "WARNING:tensorflow:Skipping full serialization of Keras model , because its inputs are not defined.\n", 757 | "WARNING:tensorflow:Skipping full serialization of Keras layer , because it is not built.\n", 758 | "WARNING:tensorflow:Skipping full serialization of Keras layer , because it is not built.\n", 759 | "WARNING:tensorflow:Skipping full serialization of Keras layer , because it is not built.\n", 760 | "WARNING:tensorflow:Skipping full serialization of Keras layer , because it is not built.\n", 761 | "WARNING:tensorflow:Skipping full serialization of Keras layer , because it is not built.\n", 762 | "WARNING:tensorflow:Skipping full serialization of Keras layer , because it is not built.\n", 763 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1809: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n", 764 | "Instructions for updating:\n", 765 | "If using Keras pass *_constraint arguments to layers.\n", 766 | "INFO:tensorflow:Assets written to: distilbert_cased_savedmodel/assets\n" 767 | ], 768 | "name": "stdout" 769 | } 770 | ] 771 | }, 772 | { 773 | "cell_type": "code", 774 | "metadata": { 775 | "id": "LrprRSPB8uFG", 776 | "colab_type": "code", 777 | "outputId": "436c9e7a-78ce-403b-f003-e1e0d78a332d", 778 | "colab": { 779 | "base_uri": "https://localhost:8080/", 780 | "height": 347 781 | } 782 | }, 783 | "source": [ 784 | "!saved_model_cli show --dir distilbert_cased_savedmodel --tag_set serve --signature_def serving_default" 785 | ], 786 | "execution_count": 5, 787 | "outputs": [ 788 | { 789 | "output_type": "stream", 790 | "text": [ 791 | "The given SavedModel SignatureDef contains the following input(s):\n", 792 | " inputs['attention_mask'] tensor_info:\n", 793 | " dtype: DT_INT32\n", 794 | " shape: (-1, 384)\n", 795 | " name: serving_default_attention_mask:0\n", 796 | " inputs['input_ids'] tensor_info:\n", 797 | " dtype: DT_INT32\n", 798 | " shape: (-1, 384)\n", 799 | " name: serving_default_input_ids:0\n", 800 | "The given SavedModel SignatureDef contains the following output(s):\n", 801 | " outputs['output_0'] tensor_info:\n", 802 | " dtype: DT_FLOAT\n", 803 | " shape: (-1, 384)\n", 804 | " name: StatefulPartitionedCall:0\n", 805 | " outputs['output_1'] tensor_info:\n", 806 | " dtype: DT_FLOAT\n", 807 | " shape: (-1, 384)\n", 808 | " name: StatefulPartitionedCall:1\n", 809 | "Method name is: tensorflow/serving/predict\n" 810 | ], 811 | "name": "stdout" 812 | } 813 | ] 814 | } 815 | ] 816 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Question Answering for Node.js 2 | 3 | [![npm version](https://badge.fury.io/js/question-answering.svg)](https://www.npmjs.com/package/question-answering) 4 | 5 | #### Production-ready Question Answering directly in Node.js, with only 3 lines of code! 6 | 7 | This package leverages the power of the [🤗Tokenizers](https://github.com/huggingface/tokenizers) library (built with Rust) to process the input text. It then uses [TensorFlow.js](https://www.tensorflow.org/js) to run the [DistilBERT](https://arxiv.org/abs/1910.01108)-cased model fine-tuned for Question Answering (87.1 F1 score on SQuAD v1.1 dev set, compared to 88.7 for BERT-base-cased). DistilBERT is used by default, but you can use [other models](#models) available in the [🤗Transformers](https://github.com/huggingface/transformers) library in one additional line of code! 8 | 9 | It can run models in SavedModel and TFJS formats locally, as well as [remote models](#remote-model) thanks to TensorFlow Serving. 10 | 11 | ## Installation 12 | 13 | ```bash 14 | npm install question-answering@latest 15 | ``` 16 | 17 | ## Quickstart 18 | 19 | The following example will automatically download the default DistilBERT model in SavedModel format if not already present, along with the required vocabulary / tokenizer files. It will then run the model and return the answer to the `question`. 20 | 21 | ```typescript 22 | import { QAClient } from "question-answering"; // When using Typescript or Babel 23 | // const { QAClient } = require("question-answering"); // When using vanilla JS 24 | 25 | const text = ` 26 | Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. 27 | The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. 28 | As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50. 29 | `; 30 | 31 | const question = "Who won the Super Bowl?"; 32 | 33 | const qaClient = await QAClient.fromOptions(); 34 | const answer = await qaClient.predict(question, text); 35 | 36 | console.log(answer); // { text: 'Denver Broncos', score: 0.3 } 37 | ``` 38 | 39 | > You can also download the model and vocabulary / tokenizer files separately by [using the CLI](#cli). 40 | 41 | ## Advanced 42 | 43 | 44 | ### Using another model 45 | 46 | The above example internally makes use of the default DistilBERT-cased model in the SavedModel format. The library is also compatible with any other __DistilBERT__-based model, as well as any __BERT__-based and __RoBERTa__-based models, both in SavedModel and TFJS formats. The following models are available in SavedModel format from the [Hugging Face model hub](https://huggingface.co/models) thanks to the amazing NLP community 🤗: 47 | 48 | * [`a-ware/mobilebert-squadv2`](https://huggingface.co/a-ware/mobilebert-squadv2) 49 | * [`a-ware/roberta-large-squadv2`](https://huggingface.co/a-ware/roberta-large-squadv2) 50 | * [`bert-large-cased-whole-word-masking-finetuned-squad`](https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad) 51 | * [`bert-large-uncased-whole-word-masking-finetuned-squad`](https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad) 52 | * [`deepset/bert-base-cased-squad2`](https://huggingface.co/deepset/bert-base-cased-squad2) 53 | * [`deepset/bert-large-uncased-whole-word-masking-squad2`](https://huggingface.co/deepset/bert-large-uncased-whole-word-masking-squad2) 54 | * [`deepset/roberta-base-squad2`](https://huggingface.co/deepset/roberta-base-squad2) 55 | * [`distilbert-base-cased-distilled-squad`](https://huggingface.co/distilbert-base-cased-distilled-squad) (default) (also available in TFJS format) 56 | * [`distilbert-base-uncased-distilled-squad`](https://huggingface.co/distilbert-base-uncased-distilled-squad) 57 | * [`henryk/bert-base-multilingual-cased-finetuned-dutch-squad2`](https://huggingface.co/henryk/bert-base-multilingual-cased-finetuned-dutch-squad2) 58 | * [`ktrapeznikov/biobert_v1.1_pubmed_squad_v2`](https://huggingface.co/ktrapeznikov/biobert_v1.1_pubmed_squad_v2) 59 | * [`ktrapeznikov/scibert_scivocab_uncased_squad_v2`](https://huggingface.co/ktrapeznikov/scibert_scivocab_uncased_squad_v2) 60 | * [`mrm8488/bert-base-spanish-wwm-cased-finetuned-spa-squad2-es`](https://huggingface.co/mrm8488/bert-base-spanish-wwm-cased-finetuned-spa-squad2-es) 61 | * [`mrm8488/distill-bert-base-spanish-wwm-cased-finetuned-spa-squad2-es`](https://huggingface.co/mrm8488/distill-bert-base-spanish-wwm-cased-finetuned-spa-squad2-es) 62 | * [`mrm8488/spanbert-finetuned-squadv2`](https://huggingface.co/mrm8488/spanbert-finetuned-squadv2) 63 | * [`NeuML/bert-small-cord19qa`](https://huggingface.co/NeuML/bert-small-cord19qa) 64 | * [`twmkn9/bert-base-uncased-squad2`](https://huggingface.co/twmkn9/bert-base-uncased-squad2) 65 | 66 | To specify a model to use with the library, you need to instantiate a model class that you'll then pass to the `QAClient`: 67 | 68 | ```typescript 69 | import { initModel, QAClient } from "question-answering"; // When using Typescript or Babel 70 | // const { initModel, QAClient } = require("question-answering"); // When using vanilla JS 71 | 72 | const text = ... 73 | const question = ... 74 | 75 | const model = await initModel({ name: "deepset/roberta-base-squad2" }); 76 | const qaClient = await QAClient.fromOptions({ model }); 77 | const answer = await qaClient.predict(question, text); 78 | 79 | console.log(answer); // { text: 'Denver Broncos', score: 0.46 } 80 | ``` 81 | 82 | > Note that using a model [hosted on Hugging Face](https://huggingface.co/models) is not a requirement: you can use any compatible model (including any from the HF hub not already available in SavedModel or TFJS format that you converted yourself) by passing the correct local path for the model and vocabulary files in the options. 83 | 84 | #### Using models in TFJS format 85 | 86 | To use a TFJS model, you simply need to pass `tfjs` to the `runtime` param of `initModel` (defaults to `saved_model`): 87 | 88 | ```typescript 89 | const model = await initModel({ name: "distilbert-base-cased-distilled-squad", runtime: RuntimeType.TFJS }); 90 | ``` 91 | 92 | As with any SavedModel hosted in the HF model hub, the required files for the TFJS models will be automatically downloaded the first time. You can also download them manually [using the CLI](#cli). 93 | 94 | 95 | #### Using remote models with [TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving) 96 | 97 | If your model is in the SavedModel format, you may prefer to host it on a dedicated server. Here is a simple example using [Docker](https://www.tensorflow.org/tfx/serving/docker) locally: 98 | 99 | ```bash 100 | # Inside our project root, download DistilBERT-cased to its default `.models` location 101 | npx question-answering download 102 | 103 | # Download the TensorFlow Serving Docker image 104 | docker pull tensorflow/serving 105 | 106 | # Start TensorFlow Serving container and open the REST API port. 107 | # Notice that in the `target` path we add a `/1`: 108 | # this is required by TFX which is expecting the models to be "versioned" 109 | docker run -t --rm -p 8501:8501 \ 110 | --mount type=bind,source="$(pwd)/.models/distilbert-cased/",target="/models/cased/1" \ 111 | -e MODEL_NAME=cased \ 112 | tensorflow/serving & 113 | ``` 114 | 115 | In the code, you just have to pass `remote` as `runtime` and the server endpoint as `path`: 116 | 117 | ```typescript 118 | const model = await initModel({ 119 | name: "distilbert-base-cased-distilled-squad", 120 | path: "http://localhost:8501/v1/models/cased", 121 | runtime: RuntimeType.Remote 122 | }); 123 | const qaClient = await QAClient.fromOptions({ model }); 124 | ``` 125 | 126 | 127 | ### Downloading models with the CLI 128 | 129 | You can choose to download the model and associated vocab file(s) manually using the CLI. For example to download the `deepset/roberta-base-squad2` model: 130 | ```bash 131 | npx question-answering download deepset/roberta-base-squad2 132 | ``` 133 | 134 | > By default, the files are downloaded inside a `.models` directory at the root of your project; you can provide a custom directory by using the `--dir` option of the CLI. You can also use `--format tfjs` to download a model in TFJS format (if available). To check all the options of the CLI: `npx question-answering download --help`. 135 | 136 | ### Using a custom tokenizer 137 | 138 | The `QAClient.fromOptions` params object has a `tokenizer` field which can either be a set of options relative to the tokenizer files, or an instance of a class extending the abstract [`Tokenizer`](./src/tokenizers/tokenizer.ts) class. To extend this class, you can create your own or, if you simply need to adjust some options, you can import and use the provided `initTokenizer` method, which will instantiate such a class for you. 139 | 140 | ## Performances 141 | 142 | Thanks to [the native execution of SavedModel format](https://groups.google.com/a/tensorflow.org/d/msg/tfjs/Xtf6s1Bpkr0/7-Eqn8soAwAJ) in TFJS, the performance of such models is similar to the one using TensorFlow in Python. 143 | 144 | Specifically, here are the results of a benchmark using `question-answering` with the default DistilBERT-cased model: 145 | 146 | * Running entirely locally (both SavedModel and TFJS formats) 147 | * Using a (pseudo) remote model server (i.e. local Docker with TensorFlow Serving running the SavedModel format) 148 | * Using the Question Answering pipeline in the [🤗Transformers](https://github.com/huggingface/transformers) library. 149 | 150 | ![QA benchmark chart](https://docs.google.com/spreadsheets/d/e/2PACX-1vRCprbDB9T8nwdOpRv2pmlOXWKw3vVOx5P2jbn7hipjCyaGRuQS3u5KWpE7ux5Q0jbqT9HFVMivkI4x/pubchart?oid=2051609279&format=image) 151 | _Shorts texts are texts between 500 and 1000 characters, long texts are between 4000 and 5000 characters. You can check the `question-answering` benchmark script [here](./scripts/benchmark.js) (the `transformers` one is equivalent). Benchmark run on a standard 2019 MacBook Pro running on macOS 10.15.2._ 152 | 153 | ## Troubleshooting 154 | 155 | ### Errors when using Typescript 156 | 157 | There is a known incompatibility in the TFJS library with some types. If you encounter errors when building your project, make sure to pass the `--skipLibCheck` flag when using the Typescript CLI, or to add `skipLibCheck: true` to your `tsconfig.json` file under `compilerOptions`. See [here](https://github.com/tensorflow/tfjs/issues/2007) for more information. 158 | 159 | ### `Tensor not referenced` when running SavedModel 160 | 161 | Due to a [bug in TFJS](https://github.com/tensorflow/tfjs/issues/3463), the use of `@tensorflow/tfjs-node` to load or execute SavedModel models independently from the library is not recommended for now, since it could overwrite the TF backend used internally by the library. In the case where you would have to do so, make sure to require _both_ `question-answering` _and_ `@tensorflow/tfjs-node` in your code __before making any use of either of them__. 162 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // For a detailed explanation regarding each configuration property, visit: 2 | // https://jestjs.io/docs/en/configuration.html 3 | 4 | module.exports = { 5 | // All imported modules in your tests should be mocked automatically 6 | // automock: false, 7 | 8 | // Stop running tests after `n` failures 9 | // bail: 0, 10 | 11 | // Respect "browser" field in package.json when resolving modules 12 | // browser: false, 13 | 14 | // The directory where Jest should store its cached dependency information 15 | // cacheDirectory: "/private/var/folders/y_/n6h0fkqn3m57bg_ktk25j7rm0000gn/T/jest_dx", 16 | 17 | // Automatically clear mock calls and instances between every test 18 | // clearMocks: false, 19 | 20 | // Indicates whether the coverage information should be collected while executing the test 21 | // collectCoverage: false, 22 | 23 | // An array of glob patterns indicating a set of files for which coverage information should be collected 24 | // collectCoverageFrom: null, 25 | 26 | // The directory where Jest should output its coverage files 27 | // coverageDirectory: null, 28 | 29 | // An array of regexp pattern strings used to skip coverage collection 30 | // coveragePathIgnorePatterns: [ 31 | // "/node_modules/" 32 | // ], 33 | 34 | // A list of reporter names that Jest uses when writing coverage reports 35 | // coverageReporters: [ 36 | // "json", 37 | // "text", 38 | // "lcov", 39 | // "clover" 40 | // ], 41 | 42 | // An object that configures minimum threshold enforcement for coverage results 43 | // coverageThreshold: null, 44 | 45 | // A path to a custom dependency extractor 46 | // dependencyExtractor: null, 47 | 48 | // Make calling deprecated APIs throw helpful error messages 49 | // errorOnDeprecated: false, 50 | 51 | // Force coverage collection from ignored files using an array of glob patterns 52 | // forceCoverageMatch: [], 53 | 54 | // A path to a module which exports an async function that is triggered once before all test suites 55 | // globalSetup: null, 56 | 57 | // A path to a module which exports an async function that is triggered once after all test suites 58 | // globalTeardown: null, 59 | 60 | // A set of global variables that need to be available in all test environments 61 | // globals: {}, 62 | 63 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 64 | // maxWorkers: "50%", 65 | 66 | // An array of directory names to be searched recursively up from the requiring module's location 67 | // moduleDirectories: [ 68 | // "node_modules" 69 | // ], 70 | 71 | // An array of file extensions your modules use 72 | // moduleFileExtensions: [ 73 | // "js", 74 | // "json", 75 | // "jsx", 76 | // "ts", 77 | // "tsx", 78 | // "node" 79 | // ], 80 | 81 | // A map from regular expressions to module names that allow to stub out resources with a single module 82 | // moduleNameMapper: {}, 83 | 84 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 85 | // modulePathIgnorePatterns: [], 86 | 87 | // Activates notifications for test results 88 | // notify: false, 89 | 90 | // An enum that specifies notification mode. Requires { notify: true } 91 | // notifyMode: "failure-change", 92 | 93 | // A preset that is used as a base for Jest's configuration 94 | preset: "ts-jest", 95 | 96 | // Run tests from one or more projects 97 | // projects: null, 98 | 99 | // Use this configuration option to add custom reporters to Jest 100 | // reporters: undefined, 101 | 102 | // Automatically reset mock state between every test 103 | // resetMocks: false, 104 | 105 | // Reset the module registry before running each individual test 106 | // resetModules: false, 107 | 108 | // A path to a custom resolver 109 | // resolver: null, 110 | 111 | // Automatically restore mock state between every test 112 | // restoreMocks: false, 113 | 114 | // The root directory that Jest should scan for tests and modules within 115 | // rootDir: null, 116 | 117 | // A list of paths to directories that Jest should use to search for files in 118 | // roots: [ 119 | // "" 120 | // ], 121 | 122 | // Allows you to use a custom runner instead of Jest's default test runner 123 | // runner: "jest-runner", 124 | 125 | // The paths to modules that run some code to configure or set up the testing environment before each test 126 | // setupFiles: [], 127 | 128 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 129 | // setupFilesAfterEnv: [], 130 | 131 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 132 | // snapshotSerializers: [], 133 | 134 | // The test environment that will be used for testing 135 | testEnvironment: "node", 136 | 137 | // Options that will be passed to the testEnvironment 138 | // testEnvironmentOptions: {}, 139 | 140 | // Adds a location field to test results 141 | // testLocationInResults: false, 142 | 143 | // The glob patterns Jest uses to detect test files 144 | testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"] 145 | 146 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 147 | // testPathIgnorePatterns: [ 148 | // "/node_modules/" 149 | // ], 150 | 151 | // The regexp pattern or array of patterns that Jest uses to detect test files 152 | // testRegex: [], 153 | 154 | // This option allows the use of a custom results processor 155 | // testResultsProcessor: null, 156 | 157 | // This option allows use of a custom test runner 158 | // testRunner: "jasmine2", 159 | 160 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 161 | // testURL: "http://localhost", 162 | 163 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 164 | // timers: "real", 165 | 166 | // A map from regular expressions to paths to transformers 167 | // transform: null, 168 | 169 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 170 | // transformIgnorePatterns: [ 171 | // "/node_modules/" 172 | // ], 173 | 174 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 175 | // unmockedModulePathPatterns: undefined, 176 | 177 | // Indicates whether each individual test should be reported during the run 178 | // verbose: null, 179 | 180 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 181 | // watchPathIgnorePatterns: [], 182 | 183 | // Whether to use watchman for file crawling 184 | // watchman: true, 185 | }; 186 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "question-answering", 3 | "version": "3.0.0", 4 | "description": "Production-ready Question Answering directly in Node.js", 5 | "keywords": [ 6 | "nlp", 7 | "question answering", 8 | "tensorflow", 9 | "distilbert" 10 | ], 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/huggingface/node-question-answering.git" 14 | }, 15 | "bugs": { 16 | "url": "https://github.com/huggingface/node-question-answering/issues" 17 | }, 18 | "main": "./dist/index.js", 19 | "types": "./dist/index.d.ts", 20 | "bin": "./cli.js", 21 | "dependencies": { 22 | "@tensorflow/tfjs-node": "^2.0.1", 23 | "@types/node": "^13.5.0", 24 | "@types/node-fetch": "^2.5.4", 25 | "@types/progress": "^2.0.3", 26 | "@types/shelljs": "^0.8.7", 27 | "@types/tar": "^4.0.3", 28 | "node-fetch": "^2.6.0", 29 | "progress": "^2.0.3", 30 | "shelljs": "^0.8.3", 31 | "tar": "^5.0.5", 32 | "tokenizers": "^0.7.0", 33 | "yargs": "^15.1.0" 34 | }, 35 | "devDependencies": { 36 | "@types/jest": "^26.0.3", 37 | "@typescript-eslint/eslint-plugin": "^2.23.0", 38 | "@typescript-eslint/parser": "^2.23.0", 39 | "eslint": "^6.8.0", 40 | "eslint-config-prettier": "^6.10.0", 41 | "eslint-plugin-jest": "^23.6.0", 42 | "eslint-plugin-prettier": "^3.1.2", 43 | "eslint-plugin-simple-import-sort": "^5.0.0", 44 | "jest": "^26.1.0", 45 | "prettier": "^1.19.1", 46 | "ts-jest": "^26.1.1", 47 | "typescript": "^3.9.6", 48 | "yargs-interactive": "^3.0.0" 49 | }, 50 | "scripts": { 51 | "dev": "rm -rf dist && npx tsc", 52 | "test": "jest", 53 | "lint": "eslint --fix --ext .js,.ts src scripts", 54 | "lint-check": "eslint --ext .js,.ts src scripts" 55 | }, 56 | "engines": { 57 | "node": ">=10 < 11 || >=12 <14" 58 | }, 59 | "author": "Pierric Cistac ", 60 | "license": "Apache-2.0" 61 | } 62 | -------------------------------------------------------------------------------- /scripts/benchmark.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | //@ts-check 3 | 4 | const QAClient = require("../dist/qa").QAClient; 5 | 6 | const DATA = [ 7 | { 8 | context: ` 9 | Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. 10 | The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. 11 | As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50. 12 | `, 13 | type: "short", 14 | questions: [ 15 | "Who won the Super Bowl?", 16 | "What was the final score?", 17 | "What day was the game played?" 18 | ] 19 | }, 20 | { 21 | context: ` 22 | One of the most famous people born in Warsaw was Maria Skłodowska-Curie, who achieved international recognition for her research on radioactivity and was the first female recipient of the Nobel Prize. Famous musicians include Władysław Szpilman and Frédéric Chopin. Though Chopin was born in the village of Żelazowa Wola, about 60 km (37 mi) from Warsaw, he moved to the city with his family when he was seven months old. Casimir Pulaski, a Polish general and hero of the American Revolutionary War, was born here in 1745. 23 | `, 24 | type: "short", 25 | questions: [ 26 | "Where was Chopin born?", 27 | "Who was Casimir Pulaski?", 28 | "For what did Maria Skłodowska-Curie achieved international recognition?" 29 | ] 30 | }, 31 | { 32 | context: ` 33 | At his father's death on 16 September 1380, Charles VI inherited the throne of France. His coronation took place on 4 November 1380, at Reims Cathedral. Charles VI was only 11 years old when he was crowned King of France. During his minority, France was ruled by Charles' uncles, as regents. Although the royal age of majority was 14 (the "age of accountability" under Roman Catholic canon law), Charles terminated the regency only at the age of 21. 34 | 35 | The regents were Philip the Bold, Duke of Burgundy, Louis I, Duke of Anjou, and John, Duke of Berry – all brothers of Charles V – along with Louis II, Duke of Bourbon, Charles VI's maternal uncle. Philip took the dominant role during the regency. Louis of Anjou was fighting for his claim to the Kingdom of Naples after 1382, dying in 1384; John of Berry was interested mainly in the Languedoc, and not particularly interested in politics; and Louis of Bourbon was a largely unimportant figure, owing to his personality (showing signs of mental instability) and status (since he was not the son of a king). 36 | 37 | During the rule of his uncles, the financial resources of the kingdom, painstakingly built up by his father, were squandered for the personal profit of the dukes, whose interests were frequently divergent or even opposing. During that time, the power of the royal administration was strengthened and taxes re-established. The latter policy represented a reversal of the deathbed decision of the king's father Charles V to repeal taxes, and led to tax revolts, known as the Harelle. Increased tax revenues were needed to support the self-serving policies of the king's uncles, whose interests were frequently in conflict with those of the crown and with each other. The Battle of Roosebeke (1382), for example, brilliantly won by the royal troops, was prosecuted solely for the benefit of Philip of Burgundy. The treasury surplus carefully accumulated by Charles V was quickly squandered. 38 | 39 | Charles VI brought the regency to an end in 1388, taking up personal rule. He restored to power the highly competent advisors of Charles V, known as the Marmousets, who ushered in a new period of high esteem for the crown. Charles VI was widely referred to as Charles the Beloved by his subjects. 40 | 41 | He married Isabeau of Bavaria on 17 July 1385, when he was 17 and she 14 (and considered an adult at the time). Isabeau had 12 children, most of whom died young. Isabeau's first child, named Charles, was born in 1386, and was Dauphin of Viennois (heir apparent), but survived only 3 months. Her second child, Joan, was born on 14 June 1388, but died in 1390. Her third child, Isabella, was born in 1389. She was married to Richard II, King of England in 1396, at the age of 6, and became Queen of England. Richard died in 1400 and they had no children. Richard's successor, Henry IV, wanted Isabella then to marry his son, 14-year-old future king Henry V, but she refused. She was married again in 1406, this time to her cousin, Charles, Duke of Orléans, at the age of 17. She died in childbirth at the age of 19. 42 | 43 | Isabeau's fourth child, Joan, was born in 1391, and was married to John VI, Duke of Brittany in 1396, at an age of 5; they had children. Isabeau's fifth child born in 1392 was also named Charles, and was Dauphin. The young Charles was betrothed to Margaret of Burgundy in 1396, but died at the age of 9. Isabeau's sixth child, Mary, was born in 1393. She was never married, and had no children. Isabeau's seventh child, Michelle, was born in 1395. She was engaged to Philip, son of John the Fearless, Duke of Burgundy, in 1404 (both were then aged 8) and they were married in 1409, aged 14. She had one child who died in infancy, before she died in 1422, aged 27. 44 | 45 | Isabeau's eighth child, Louis, was born in 1397, and was also Dauphin. He married Margaret of Burgundy, who had previously been betrothed to his brother Charles. The marriage produced no children by the time of Louis's death in 1415, aged 18. 46 | 47 | Isabeau's ninth child, John, was born in 1398, and was also Dauphin from 1415, after the death of his brother Louis. He was married to Jacqueline, Countess of Hainaut in 1415, then aged 17, but they did not have any children before he died in 1417, aged 19. Isabeau's tenth child, Catherine, was born in 1401. She was married firstly to Henry V, King of England in 1420, and they had one child, who became Henry VI of England. Henry V died suddenly in 1422. Catherine may then have secretly married Owen Tudor in 1429 and had additional children, including Edmund Tudor, the father of Henry VII. She died in 1437, aged 36. 48 | `, 49 | type: "long", 50 | questions: [ 51 | "When did his father die?", 52 | "Who did Charles VI marry?", 53 | "What was the name of Isabeau's eighth child?" 54 | ] 55 | } 56 | ]; 57 | 58 | (async () => { 59 | const qaClient = await QAClient.fromOptions({ 60 | // model: { path: "http://localhost:8501/v1/models/cased", cased: true, remote: true }, 61 | // model: { 62 | // path: "distilbert-cased", 63 | // cased: true, 64 | // outputsNames: { startLogits: "Identity", endLogits: "Identity_1" } 65 | // }, 66 | timeIt: true 67 | }); 68 | 69 | await qaClient.predict("dummy", "dummy"); 70 | 71 | const times = { 72 | short: { 73 | inference: [], 74 | total: [] 75 | }, 76 | long: { 77 | inference: [], 78 | total: [] 79 | } 80 | }; 81 | 82 | for (let i = 0; i < 20; i++) { 83 | console.log(`Run ${i + 1}...`); 84 | for (const data of DATA) { 85 | for (const question of data.questions) { 86 | const answer = await qaClient.predict(question, data.context); 87 | // @ts-ignore 88 | times[data.type].inference.push(answer.inferenceTime); 89 | // @ts-ignore 90 | times[data.type].total.push(answer.totalTime); 91 | } 92 | } 93 | } 94 | 95 | for (const type of Object.keys(times)) { 96 | console.log( 97 | `average inference time (${type} texts):`, 98 | average(times[type].inference) 99 | ); 100 | console.log(`average total time (${type} texts):`, average(times[type].total)); 101 | } 102 | })(); 103 | 104 | /** 105 | * @param {number[]} numbers 106 | */ 107 | function average(numbers) { 108 | const raw = numbers.reduce((acc, val) => acc + val, 0) / numbers.length; 109 | return Math.round((raw + Number.EPSILON) * 100) / 100; 110 | } 111 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | //@ts-check 3 | 4 | const path = require("path"); 5 | const shell = require("shelljs"); 6 | const fs = require("fs"); 7 | const promisify = require("util").promisify; 8 | 9 | const distPath = "./dist"; 10 | const buildPath = "./build"; 11 | 12 | // Fail this script if any of these commands fail 13 | shell.set("-e"); 14 | 15 | // Ensure that our directory is set to the root of the repo 16 | const rootDirectory = path.join(path.dirname(process.argv[1]), "../"); 17 | shell.cd(rootDirectory); 18 | 19 | const arg = process.argv.slice(2)[0]; 20 | 21 | run(arg) 22 | // Prevent "unhandledRejection" events, allowing to actually exit with error 23 | .catch(() => process.exit(1)); 24 | 25 | /**************************************/ 26 | 27 | async function run(arg) { 28 | switch (arg) { 29 | case "--typescript": 30 | await buildTs(); 31 | break; 32 | 33 | case "--npm-publish": 34 | await buildTs(); 35 | await npmPublish(); 36 | break; 37 | 38 | default: 39 | shell.echo("No arg provided, doing nothing..."); 40 | break; 41 | } 42 | } 43 | 44 | async function buildTs() { 45 | shell.echo("BUILDING TS..."); 46 | 47 | // Cleanup the previous build, if it exists 48 | shell.rm("-rf", distPath); 49 | 50 | shell.exec("npm ci --ignore-scripts"); 51 | await ensureDir(distPath); 52 | shell.exec("npx tsc -p tsconfig.prod.json"); 53 | 54 | shell.echo("BUILDING TS COMPLETE..."); 55 | } 56 | 57 | async function npmPublish() { 58 | shell.echo("PUBLISHING ON NPM..."); 59 | 60 | shell.rm("-rf", buildPath); 61 | await ensureDir(buildPath); 62 | shell.cp( 63 | "-r", 64 | [distPath, "package.json", "README.md", "LICENSE", "./scripts/cli.js"], 65 | buildPath 66 | ); 67 | 68 | // shell.exec(`npm pack ${buildPath}`); 69 | shell.exec(`npm publish ${buildPath} --access public`); 70 | 71 | shell.echo("PUBLISHING ON NPM COMPLETE..."); 72 | } 73 | 74 | /** 75 | * Ensures a directory exists, creates as needed. 76 | */ 77 | async function ensureDir(dirPath, recursive = true) { 78 | if (!(await promisify(fs.exists)(dirPath))) { 79 | recursive ? shell.mkdir("-p", dirPath) : shell.mkdir(dirPath); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /scripts/cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | //@ts-check 3 | 4 | const shell = require("shelljs"); 5 | const yargs = require("yargs"); 6 | 7 | const utils = require("../dist/utils"); 8 | 9 | // Fail this script if any of these commands fail 10 | shell.set("-e"); 11 | 12 | yargs 13 | .command( 14 | "download [model]", 15 | "Download a model (defaults to distilbert-base-cased-distilled-squad)", 16 | yargs => { 17 | yargs 18 | .positional("model", { 19 | default: "distilbert-base-cased-distilled-squad", 20 | type: "string" 21 | }) 22 | .option("dir", { 23 | default: "./.models", 24 | type: "string", 25 | description: "The target directory to which download the model", 26 | requiresArg: true, 27 | normalize: true 28 | }) 29 | .option("format", { 30 | type: "string", 31 | default: "saved_model", 32 | options: ["saved_model", "tfjs"], 33 | requiresArg: true, 34 | description: "Format to download" 35 | }) 36 | .option("force", { 37 | type: "boolean", 38 | alias: "f", 39 | description: 40 | "Force download of model and vocab, erasing existing if already present" 41 | }); 42 | }, 43 | utils.downloadModelWithVocab 44 | ) 45 | .demandCommand() 46 | .help().argv; 47 | -------------------------------------------------------------------------------- /scripts/example.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | //@ts-check 3 | 4 | const yargsInteractive = require("yargs-interactive"); 5 | 6 | const QAClient = require("../dist/qa").QAClient; 7 | 8 | const texts = { 9 | "Charles VI": ` 10 | At his father's death on 16 September 1380, Charles VI inherited the throne of France. His coronation took place on 4 November 1380, at Reims Cathedral. Charles VI was only 11 years old when he was crowned King of France. During his minority, France was ruled by Charles' uncles, as regents. Although the royal age of majority was 14 (the "age of accountability" under Roman Catholic canon law), Charles terminated the regency only at the age of 21. 11 | 12 | The regents were Philip the Bold, Duke of Burgundy, Louis I, Duke of Anjou, and John, Duke of Berry – all brothers of Charles V – along with Louis II, Duke of Bourbon, Charles VI's maternal uncle. Philip took the dominant role during the regency. Louis of Anjou was fighting for his claim to the Kingdom of Naples after 1382, dying in 1384; John of Berry was interested mainly in the Languedoc, and not particularly interested in politics; and Louis of Bourbon was a largely unimportant figure, owing to his personality (showing signs of mental instability) and status (since he was not the son of a king). 13 | 14 | During the rule of his uncles, the financial resources of the kingdom, painstakingly built up by his father, were squandered for the personal profit of the dukes, whose interests were frequently divergent or even opposing. During that time, the power of the royal administration was strengthened and taxes re-established. The latter policy represented a reversal of the deathbed decision of the king's father Charles V to repeal taxes, and led to tax revolts, known as the Harelle. Increased tax revenues were needed to support the self-serving policies of the king's uncles, whose interests were frequently in conflict with those of the crown and with each other. The Battle of Roosebeke (1382), for example, brilliantly won by the royal troops, was prosecuted solely for the benefit of Philip of Burgundy. The treasury surplus carefully accumulated by Charles V was quickly squandered. 15 | 16 | Charles VI brought the regency to an end in 1388, taking up personal rule. He restored to power the highly competent advisors of Charles V, known as the Marmousets, who ushered in a new period of high esteem for the crown. Charles VI was widely referred to as Charles the Beloved by his subjects. 17 | 18 | He married Isabeau of Bavaria on 17 July 1385, when he was 17 and she 14 (and considered an adult at the time). Isabeau had 12 children, most of whom died young. Isabeau's first child, named Charles, was born in 1386, and was Dauphin of Viennois (heir apparent), but survived only 3 months. Her second child, Joan, was born on 14 June 1388, but died in 1390. Her third child, Isabella, was born in 1389. She was married to Richard II, King of England in 1396, at the age of 6, and became Queen of England. Richard died in 1400 and they had no children. Richard's successor, Henry IV, wanted Isabella then to marry his son, 14-year-old future king Henry V, but she refused. She was married again in 1406, this time to her cousin, Charles, Duke of Orléans, at the age of 17. She died in childbirth at the age of 19. 19 | 20 | Isabeau's fourth child, Joan, was born in 1391, and was married to John VI, Duke of Brittany in 1396, at an age of 5; they had children. Isabeau's fifth child born in 1392 was also named Charles, and was Dauphin. The young Charles was betrothed to Margaret of Burgundy in 1396, but died at the age of 9. Isabeau's sixth child, Mary, was born in 1393. She was never married, and had no children. Isabeau's seventh child, Michelle, was born in 1395. She was engaged to Philip, son of John the Fearless, Duke of Burgundy, in 1404 (both were then aged 8) and they were married in 1409, aged 14. She had one child who died in infancy, before she died in 1422, aged 27. 21 | 22 | Isabeau's eighth child, Louis, was born in 1397, and was also Dauphin. He married Margaret of Burgundy, who had previously been betrothed to his brother Charles. The marriage produced no children by the time of Louis's death in 1415, aged 18. 23 | 24 | Isabeau's ninth child, John, was born in 1398, and was also Dauphin from 1415, after the death of his brother Louis. He was married to Jacqueline, Countess of Hainaut in 1415, then aged 17, but they did not have any children before he died in 1417, aged 19. Isabeau's tenth child, Catherine, was born in 1401. She was married firstly to Henry V, King of England in 1420, and they had one child, who became Henry VI of England. Henry V died suddenly in 1422. Catherine may then have secretly married Owen Tudor in 1429 and had additional children, including Edmund Tudor, the father of Henry VII. She died in 1437, aged 36. 25 | `, 26 | "Super Bowl 50": ` 27 | Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. 28 | The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. 29 | As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50. 30 | ` 31 | }; 32 | 33 | const options = { 34 | interactive: { default: true }, 35 | subject: { 36 | type: "list", 37 | describe: "Choose your subject", 38 | choices: Object.keys(texts) 39 | }, 40 | question: { 41 | type: "input", 42 | describe: "Write your question" 43 | } 44 | }; 45 | 46 | (async () => { 47 | const qa = await QAClient.fromOptions(); 48 | 49 | yargsInteractive() 50 | .usage("$0 [args]") 51 | // @ts-ignore 52 | .interactive(options) 53 | .then(async result => { 54 | const context = texts[result.subject]; 55 | console.log(cyan("\nLooking for an answer in the following text:\n"), context); 56 | 57 | const answer = await qa.predict(result.question, context); 58 | console.log(cyan("Predicted answer:"), answer.text); 59 | }); 60 | })(); 61 | 62 | function cyan(text) { 63 | return `\u001b[36m${text}\u001b[0m`; 64 | } 65 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./qa"; 2 | export * from "./models"; 3 | export { QAOptions } from "./qa-options"; 4 | export * from "./runtimes"; 5 | export * from "./tokenizers"; 6 | -------------------------------------------------------------------------------- /src/models/bert.model.ts: -------------------------------------------------------------------------------- 1 | import { Encoding } from "tokenizers"; 2 | 3 | import { Logits, Model, ModelInput, ModelType } from "./model"; 4 | 5 | export class BertModel extends Model { 6 | public static readonly inputs: ReadonlyArray = [ 7 | ModelInput.AttentionMask, 8 | ModelInput.Ids, 9 | ModelInput.TokenTypeIds 10 | ]; 11 | 12 | public readonly type = ModelType.Bert; 13 | 14 | runInference(encodings: Encoding[]): Promise<[Logits, Logits]> { 15 | return this.runtime.runInference( 16 | encodings.map(e => e.ids), 17 | encodings.map(e => e.attentionMask), 18 | encodings.map(e => e.typeIds) 19 | ); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/models/distilbert.model.ts: -------------------------------------------------------------------------------- 1 | import { Encoding } from "tokenizers"; 2 | 3 | import { Logits, Model, ModelInput, ModelType } from "./model"; 4 | 5 | export class DistilbertModel extends Model { 6 | public static readonly inputs: ReadonlyArray = [ 7 | ModelInput.AttentionMask, 8 | ModelInput.Ids 9 | ]; 10 | 11 | public readonly type = ModelType.Distilbert; 12 | 13 | runInference(encodings: Encoding[]): Promise<[Logits, Logits]> { 14 | return this.runtime.runInference( 15 | encodings.map(e => e.ids), 16 | encodings.map(e => e.attentionMask) 17 | ); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/models/index.ts: -------------------------------------------------------------------------------- 1 | export { ModelInput, ModelInputsNames, ModelOutputNames, ModelType } from "./model"; 2 | export { initModel, ModelFactoryOptions } from "./model.factory"; 3 | -------------------------------------------------------------------------------- /src/models/model.factory.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | 3 | import { DEFAULT_ASSETS_DIR } from "../qa-options"; 4 | import { Remote } from "../runtimes/remote.runtime"; 5 | import { LocalRuntime, Runtime, RuntimeOptions, RuntimeType } from "../runtimes/runtime"; 6 | import { SavedModel } from "../runtimes/saved-model.runtime"; 7 | import { TFJS } from "../runtimes/tfjs.runtime"; 8 | import { downloadModel, getAbsolutePath } from "../utils"; 9 | import { BertModel } from "./bert.model"; 10 | import { DistilbertModel } from "./distilbert.model"; 11 | import { 12 | getModelType, 13 | Model, 14 | ModelInputsNames, 15 | ModelOutputNames, 16 | ModelType 17 | } from "./model"; 18 | import { RobertaModel } from "./roberta.model"; 19 | 20 | interface CommonModelOptions { 21 | inputsNames?: ModelInputsNames; 22 | /** 23 | * Fully qualified name of the model (including the author if applicable) 24 | * @example "distilbert-base-uncased-distilled-squad" 25 | * @example "deepset/bert-base-cased-squad2" 26 | */ 27 | name: string; 28 | outputsNames?: ModelOutputNames; 29 | /** 30 | * Type of "runtime" to use for model inference: SavedModel, TFJS or remote. 31 | * @default RuntimeType.SavedModel 32 | */ 33 | runtime?: RuntimeType; 34 | /** 35 | * @default "serving_default" 36 | */ 37 | signatureName?: string; 38 | /** 39 | * Type of the model (inferred from model name by default) 40 | */ 41 | type?: ModelType; 42 | } 43 | 44 | export interface RemoteModelOptions extends CommonModelOptions { 45 | /** 46 | * - If `runtime` is `Runtime.Remote` it must be the url at which the model is exposed. 47 | */ 48 | path: string; 49 | runtime: RuntimeType.Remote; 50 | } 51 | 52 | export interface LocalModelOptions extends CommonModelOptions { 53 | /** 54 | * - For local SavedModel and TFJS, corresponds to the path of the location at which the models are located. 55 | * It can be absolute or relative to the root of the project. 56 | * Defaults to a `.models` directory at the root of the project (created if needed). 57 | */ 58 | path?: string; 59 | runtime?: LocalRuntime; 60 | } 61 | 62 | export type ModelFactoryOptions = LocalModelOptions | RemoteModelOptions; 63 | 64 | export async function initModel(options: ModelFactoryOptions): Promise { 65 | const runtimeType = options.runtime ?? RuntimeType.SavedModel; 66 | 67 | let modelDir: string; 68 | if (options.runtime !== RuntimeType.Remote) { 69 | const assetsDir = getAbsolutePath(options.path, DEFAULT_ASSETS_DIR); 70 | modelDir = path.join(assetsDir, options.name); 71 | if (runtimeType !== RuntimeType.Remote) { 72 | await downloadModel({ 73 | dir: modelDir, 74 | format: runtimeType, 75 | name: options.name 76 | }); 77 | } 78 | } else { 79 | modelDir = options.path; 80 | } 81 | 82 | const modelType = options.type ?? getModelType(options.name); 83 | let ModelClass: typeof BertModel | typeof DistilbertModel | typeof RobertaModel; 84 | switch (modelType) { 85 | case ModelType.Roberta: 86 | ModelClass = RobertaModel; 87 | break; 88 | 89 | case ModelType.Bert: 90 | ModelClass = BertModel; 91 | break; 92 | 93 | default: 94 | ModelClass = DistilbertModel; 95 | } 96 | 97 | const runtimeOptions: RuntimeOptions = { 98 | inputs: ModelClass.inputs, 99 | inputsNames: options.inputsNames, 100 | outputsNames: options.outputsNames, 101 | path: modelDir, 102 | signatureName: options.signatureName 103 | }; 104 | 105 | let runtime: Runtime; 106 | switch (runtimeType) { 107 | case RuntimeType.Remote: 108 | runtime = await Remote.fromOptions(runtimeOptions); 109 | break; 110 | 111 | case RuntimeType.TFJS: 112 | runtime = await TFJS.fromOptions(runtimeOptions); 113 | break; 114 | 115 | default: 116 | runtime = await SavedModel.fromOptions(runtimeOptions); 117 | } 118 | 119 | return new ModelClass(options.name, modelDir, runtime); 120 | } 121 | -------------------------------------------------------------------------------- /src/models/model.ts: -------------------------------------------------------------------------------- 1 | import { Encoding } from "tokenizers"; 2 | 3 | import { Runtime } from "../runtimes/runtime"; 4 | 5 | export enum ModelInput { 6 | AttentionMask = "attentionMask", 7 | Ids = "inputIds", 8 | TokenTypeIds = "tokenTypeIds" 9 | } 10 | 11 | export enum ModelType { 12 | Distilbert = "distilbert", 13 | Roberta = "roberta", 14 | Bert = "bert" // AFTER roberta, to be sure model type inference works 15 | } 16 | 17 | export type Logits = number[][]; 18 | 19 | export abstract class Model { 20 | public readonly inputLength: number; 21 | public abstract readonly type: ModelType; 22 | 23 | constructor( 24 | public readonly name: string, 25 | public readonly path: string, 26 | protected runtime: Runtime 27 | ) { 28 | this.inputLength = runtime.params.shape[1]; 29 | this.path = path; 30 | } 31 | 32 | abstract runInference(encodings: Encoding[]): Promise<[Logits, Logits]>; 33 | } 34 | 35 | /** 36 | * Infer model type from model path 37 | * @param modelName Model name 38 | * @throws If no model type inferred 39 | */ 40 | export function getModelType(modelName: string): ModelType { 41 | const types = Object.entries(ModelType); 42 | for (const [name, type] of types) { 43 | if (modelName.toLowerCase().includes(name.toLowerCase())) { 44 | return type; 45 | } 46 | } 47 | 48 | throw new Error( 49 | "Impossible to determine the type of the model. You can specify it manually by providing the `type` in the options" 50 | ); 51 | } 52 | 53 | export interface ModelInputsNames { 54 | /** 55 | * @default "inputs_ids" 56 | */ 57 | [ModelInput.Ids]?: string; 58 | /** 59 | * @default "attention_mask" 60 | */ 61 | [ModelInput.AttentionMask]?: string; 62 | /** 63 | * @default "token_type_ids" 64 | */ 65 | [ModelInput.TokenTypeIds]?: string; 66 | } 67 | 68 | export interface ModelOutputNames { 69 | /** 70 | * @default "output_0" 71 | */ 72 | startLogits?: string; 73 | /** 74 | * @default "output_1" 75 | */ 76 | endLogits?: string; 77 | } 78 | -------------------------------------------------------------------------------- /src/models/roberta.model.ts: -------------------------------------------------------------------------------- 1 | import { Encoding } from "tokenizers"; 2 | 3 | import { Logits, Model, ModelInput, ModelType } from "./model"; 4 | 5 | export class RobertaModel extends Model { 6 | public static readonly inputs: ReadonlyArray = [ 7 | ModelInput.AttentionMask, 8 | ModelInput.Ids 9 | ]; 10 | 11 | public readonly type = ModelType.Roberta; 12 | 13 | runInference(encodings: Encoding[]): Promise<[Logits, Logits]> { 14 | return this.runtime.runInference( 15 | encodings.map(e => e.ids), 16 | encodings.map(e => e.attentionMask) 17 | ); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/qa-options.ts: -------------------------------------------------------------------------------- 1 | import * as path from "path"; 2 | 3 | import { Model } from "./models/model"; 4 | import { Tokenizer } from "./tokenizers"; 5 | 6 | export const ROOT_DIR = process.cwd(); 7 | export const DEFAULT_ASSETS_DIR = path.join(ROOT_DIR, "./.models"); 8 | export const DEFAULT_MODEL_NAME = "distilbert-base-cased-distilled-squad"; 9 | export const DEFAULT_VOCAB_PATH = path.join(DEFAULT_MODEL_NAME, "vocab.txt"); 10 | 11 | export interface QAOptions { 12 | /** 13 | * Inferred from the associated tokenizer configuration by default. 14 | * Ignore this setting if you use your own tokenizer in `tokenizer`. 15 | */ 16 | cased?: boolean; 17 | /** 18 | * Model to use, defaults to a SavedModel Distilbert-base-cased finetuned on SQuAD 19 | */ 20 | model?: Model; 21 | /** 22 | * Wether to time inference 23 | * @default false 24 | */ 25 | timeIt?: boolean; 26 | /** 27 | * Custom tokenizer to use with the model, or tokenizer options 28 | * (in this case, defaults to the standard tokenizer associated with the model) 29 | */ 30 | tokenizer?: Tokenizer | TokenizerOptions; 31 | } 32 | 33 | export interface TokenizerOptions { 34 | /** 35 | * Name of the merges file (if applicable to the tokenizer). 36 | * @default "merges.txt" 37 | */ 38 | mergesFile?: string; 39 | /** 40 | * Directory under which the files needed by the tokenizer are located. 41 | * Can be absolute or relative to the root of the project. 42 | * Defaults to the model dir. 43 | */ 44 | filesDir?: string; 45 | /** 46 | * Name of the vocab file (if applicable to the tokenizer). 47 | * @default "vocab.txt" | "vocab.json" 48 | */ 49 | vocabFile?: string; 50 | } 51 | -------------------------------------------------------------------------------- /src/qa.test.ts: -------------------------------------------------------------------------------- 1 | import { mocked } from "ts-jest"; 2 | 3 | import { QAClient } from "./"; 4 | import { initModel } from "./models"; 5 | import { RuntimeType } from "./runtimes"; 6 | import { Tokenizer } from "./tokenizers"; 7 | 8 | const basicQuestion = "What was the final score?"; 9 | const basicContext = ` 10 | Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. 11 | The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. 12 | As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50. 13 | `; 14 | 15 | describe("QAClient", () => { 16 | describe("fromOptions", () => { 17 | // eslint-disable-next-line jest/no-disabled-tests 18 | it.skip("instantiates a QAClient with custom tokenizer when provided", async () => { 19 | const tokenizer = jest.fn(); 20 | const qaClient = await QAClient.fromOptions({ 21 | tokenizer: (tokenizer as unknown) as Tokenizer 22 | }); 23 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 24 | expect((qaClient as any).tokenizer).toBe(tokenizer); 25 | }); 26 | 27 | it("leads to answer without inference time by default", async () => { 28 | const qaClient = await QAClient.fromOptions(); 29 | const predOne = await qaClient.predict(basicQuestion, basicContext); 30 | expect(predOne?.inferenceTime).toBeUndefined(); 31 | }); 32 | 33 | it("leads to answer with inference time when `timeIt` is `true`", async () => { 34 | const qaClient = await QAClient.fromOptions({ timeIt: true }); 35 | const predOne = await qaClient.predict(basicQuestion, basicContext); 36 | expect(typeof predOne?.inferenceTime).toBe("number"); 37 | }); 38 | }); 39 | 40 | describe("predict", () => { 41 | let qa: QAClient; 42 | 43 | const shorts = [ 44 | { 45 | context: ` 46 | Super Bowl 50 was an American football game to determine the champion of the National Football League (NFL) for the 2015 season. 47 | The American Football Conference (AFC) champion Denver Broncos defeated the National Football Conference (NFC) champion Carolina Panthers 24–10 to earn their third Super Bowl title. The game was played on February 7, 2016, at Levi's Stadium in the San Francisco Bay Area at Santa Clara, California. 48 | As this was the 50th Super Bowl, the league emphasized the "golden anniversary" with various gold-themed initiatives, as well as temporarily suspending the tradition of naming each Super Bowl game with Roman numerals (under which the game would have been known as "Super Bowl L"), so that the logo could prominently feature the Arabic numerals 50. 49 | `, 50 | question: ["Who won the Super Bowl?", "Denver Broncos"] 51 | }, 52 | { 53 | context: ` 54 | One of the most famous people born in Warsaw was Maria Skłodowska-Curie, who achieved international recognition for her research on radioactivity and was the first female recipient of the Nobel Prize. Famous musicians include Władysław Szpilman and Frédéric Chopin. Though Chopin was born in the village of Żelazowa Wola, about 60 km (37 mi) from Warsaw, he moved to the city with his family when he was seven months old. Casimir Pulaski, a Polish general and hero of the American Revolutionary War, was born here in 1745. 55 | `, 56 | question: ["Where was Chopin born?", "Żelazowa Wola"] 57 | } 58 | ]; 59 | 60 | const long = { 61 | context: ` 62 | At his father's death on 16 September 1380, Charles VI inherited the throne of France. His coronation took place on 4 November 1380, at Reims Cathedral. Charles VI was only 11 years old when he was crowned King of France. During his minority, France was ruled by Charles' uncles, as regents. Although the royal age of majority was 14 (the "age of accountability" under Roman Catholic canon law), Charles terminated the regency only at the age of 21. 63 | 64 | The regents were Philip the Bold, Duke of Burgundy, Louis I, Duke of Anjou, and John, Duke of Berry – all brothers of Charles V – along with Louis II, Duke of Bourbon, Charles VI's maternal uncle. Philip took the dominant role during the regency. Louis of Anjou was fighting for his claim to the Kingdom of Naples after 1382, dying in 1384; John of Berry was interested mainly in the Languedoc, and not particularly interested in politics; and Louis of Bourbon was a largely unimportant figure, owing to his personality (showing signs of mental instability) and status (since he was not the son of a king). 65 | 66 | During the rule of his uncles, the financial resources of the kingdom, painstakingly built up by his father, were squandered for the personal profit of the dukes, whose interests were frequently divergent or even opposing. During that time, the power of the royal administration was strengthened and taxes re-established. The latter policy represented a reversal of the deathbed decision of the king's father Charles V to repeal taxes, and led to tax revolts, known as the Harelle. Increased tax revenues were needed to support the self-serving policies of the king's uncles, whose interests were frequently in conflict with those of the crown and with each other. The Battle of Roosebeke (1382), for example, brilliantly won by the royal troops, was prosecuted solely for the benefit of Philip of Burgundy. The treasury surplus carefully accumulated by Charles V was quickly squandered. 67 | 68 | Charles VI brought the regency to an end in 1388, taking up personal rule. He restored to power the highly competent advisors of Charles V, known as the Marmousets, who ushered in a new period of high esteem for the crown. Charles VI was widely referred to as Charles the Beloved by his subjects. 69 | 70 | He married Isabeau of Bavaria on 17 July 1385, when he was 17 and she 14 (and considered an adult at the time). Isabeau had 12 children, most of whom died young. Isabeau's first child, named Charles, was born in 1386, and was Dauphin of Viennois (heir apparent), but survived only 3 months. Her second child, Joan, was born on 14 June 1388, but died in 1390. Her third child, Isabella, was born in 1389. She was married to Richard II, King of England in 1396, at the age of 6, and became Queen of England. Richard died in 1400 and they had no children. Richard's successor, Henry IV, wanted Isabella then to marry his son, 14-year-old future king Henry V, but she refused. She was married again in 1406, this time to her cousin, Charles, Duke of Orléans, at the age of 17. She died in childbirth at the age of 19. 71 | 72 | Isabeau's fourth child, Joan, was born in 1391, and was married to John VI, Duke of Brittany in 1396, at an age of 5; they had children. Isabeau's fifth child born in 1392 was also named Charles, and was Dauphin. The young Charles was betrothed to Margaret of Burgundy in 1396, but died at the age of 9. Isabeau's sixth child, Mary, was born in 1393. She was never married, and had no children. Isabeau's seventh child, Michelle, was born in 1395. She was engaged to Philip, son of John the Fearless, Duke of Burgundy, in 1404 (both were then aged 8) and they were married in 1409, aged 14. She had one child who died in infancy, before she died in 1422, aged 27. 73 | 74 | Isabeau's eighth child, Louis, was born in 1397, and was also Dauphin. He married Margaret of Burgundy, who had previously been betrothed to his brother Charles. The marriage produced no children by the time of Louis's death in 1415, aged 18. 75 | 76 | Isabeau's ninth child, John, was born in 1398, and was also Dauphin from 1415, after the death of his brother Louis. He was married to Jacqueline, Countess of Hainaut in 1415, then aged 17, but they did not have any children before he died in 1417, aged 19. Isabeau's tenth child, Catherine, was born in 1401. She was married firstly to Henry V, King of England in 1420, and they had one child, who became Henry VI of England. Henry V died suddenly in 1422. Catherine may then have secretly married Owen Tudor in 1429 and had additional children, including Edmund Tudor, the father of Henry VII. She died in 1437, aged 36. 77 | `, 78 | questions: [ 79 | ["When did his father die?", "16 September 1380"], 80 | ["Who did Charles VI marry?", "Isabeau of Bavaria"], 81 | ["What was the name of Isabeau's tenth child?", "Catherine"] 82 | ] 83 | }; 84 | 85 | describe("using SavedModel format", () => { 86 | beforeAll(async () => { 87 | qa = await QAClient.fromOptions(); 88 | }, 100000000); 89 | 90 | it.each(shorts)("gives the correct answer with short contexts", async short => { 91 | const result = await qa.predict(short.question[0], short.context); 92 | expect(result?.text).toEqual(short.question[1]); 93 | }); 94 | 95 | for (const question of long.questions) { 96 | it("gives the correct answer with long contexts", async () => { 97 | const result = await qa.predict(question[0], long.context); 98 | expect(result?.text).toEqual(question[1]); 99 | }); 100 | } 101 | 102 | it("is non-blocking", async () => { 103 | const mockCb = jest.fn(); 104 | qa.predict(basicQuestion, basicContext).then(mockCb); 105 | await new Promise(r => setTimeout(r, 0)); 106 | expect(mockCb).not.toHaveBeenCalled(); 107 | }); 108 | }); 109 | 110 | describe("using TFJS format", () => { 111 | beforeAll(async () => { 112 | const model = await initModel({ 113 | name: "distilbert-base-cased-distilled-squad", 114 | runtime: RuntimeType.TFJS 115 | }); 116 | 117 | qa = await QAClient.fromOptions({ model }); 118 | }, 100000000); 119 | 120 | it.each(shorts)("gives the correct answer with short contexts", async short => { 121 | const result = await qa.predict(short.question[0], short.context); 122 | expect(result?.text).toEqual(short.question[1]); 123 | }); 124 | 125 | for (const question of long.questions) { 126 | it("gives the correct answer with long contexts", async () => { 127 | const result = await qa.predict(question[0], long.context); 128 | expect(result?.text).toEqual(question[1]); 129 | }); 130 | } 131 | }); 132 | }); 133 | }); 134 | 135 | it("supports big charge", async done => { 136 | const qaClientOne = await QAClient.fromOptions(); 137 | const model = await initModel({ name: "deepset/roberta-base-squad2" }); 138 | const qaClientTwo = await QAClient.fromOptions({ model }); 139 | 140 | await qaClientOne.predict(basicQuestion, basicContext); 141 | await qaClientTwo.predict(basicQuestion, basicContext); 142 | 143 | let cbCount = 0; 144 | function callback(): void { 145 | if (++cbCount === 120) { 146 | done(); 147 | } 148 | } 149 | 150 | for (let index = 0; index < 20; index++) { 151 | for (const qaClient of [qaClientOne, qaClientTwo]) { 152 | qaClient.predict(basicQuestion, basicContext).then(callback); 153 | qaClient.predict("What was the final score?", basicContext).then(callback); 154 | qaClient.predict("When was the game played?", basicContext).then(callback); 155 | } 156 | } 157 | 158 | const beforePromise = Date.now(); 159 | await new Promise(r => setTimeout(r, 3000)); 160 | const afterPromise = Date.now(); 161 | 162 | expect(afterPromise - beforePromise).toBeLessThan(3100); 163 | }, 60000); 164 | -------------------------------------------------------------------------------- /src/qa.ts: -------------------------------------------------------------------------------- 1 | import { Encoding, slice, TruncationStrategy } from "tokenizers"; 2 | 3 | import { Logits, Model } from "./models/model"; 4 | import { initModel } from "./models/model.factory"; 5 | import { DEFAULT_MODEL_NAME, QAOptions } from "./qa-options"; 6 | import { Tokenizer } from "./tokenizers/tokenizer"; 7 | import { initTokenizer, TokenizerFactoryOptions } from "./tokenizers/tokenizer.factory"; 8 | 9 | interface Feature { 10 | contextStartIndex: number; 11 | encoding: Encoding; 12 | maxContextMap: ReadonlyMap; 13 | } 14 | 15 | interface Span { 16 | length: number; 17 | startIndex: number; 18 | } 19 | 20 | export interface Answer { 21 | /** 22 | * Only provided if `timeIt` option was true when creating the QAClient 23 | */ 24 | inferenceTime?: number; 25 | /** 26 | * Only provided if answer found 27 | */ 28 | score?: number; 29 | /** 30 | * Only provided if answer found 31 | */ 32 | text?: string; 33 | /** 34 | * Only provided if `timeIt` option was true when creating the QAClient 35 | */ 36 | totalTime?: number; 37 | } 38 | 39 | export class QAClient { 40 | public modelName: string; 41 | 42 | private constructor( 43 | private readonly model: Model, 44 | private readonly tokenizer: Tokenizer, 45 | private readonly timeIt?: boolean 46 | ) { 47 | this.modelName = model.name; 48 | } 49 | 50 | static async fromOptions(options?: QAOptions): Promise { 51 | const model = options?.model ?? (await initModel({ name: DEFAULT_MODEL_NAME })); 52 | 53 | let tokenizer: Tokenizer; 54 | if (options?.tokenizer instanceof Tokenizer) { 55 | tokenizer = options.tokenizer; 56 | } else { 57 | const tokenizerOptions: TokenizerFactoryOptions = { 58 | filesDir: options?.tokenizer?.filesDir ?? model.path, 59 | modelName: model.name, 60 | modelType: model.type, 61 | mergesFile: options?.tokenizer?.mergesFile, 62 | vocabFile: options?.tokenizer?.vocabFile 63 | }; 64 | 65 | if (typeof options?.cased !== "undefined") { 66 | tokenizerOptions.lowercase = !options.cased; 67 | } 68 | 69 | tokenizer = await initTokenizer(tokenizerOptions); 70 | } 71 | 72 | return new QAClient(model, tokenizer, options?.timeIt); 73 | } 74 | 75 | async predict( 76 | question: string, 77 | context: string, 78 | maxAnswerLength = 15 79 | ): Promise { 80 | const totalStartTime = Date.now(); 81 | const features = await this.getFeatures(question, context); 82 | 83 | const inferenceStartTime = Date.now(); 84 | const [startLogits, endLogits] = await this.model.runInference( 85 | features.map(f => f.encoding) 86 | ); 87 | const elapsedInferenceTime = Date.now() - inferenceStartTime; 88 | 89 | const answer = this.getAnswer( 90 | context, 91 | features, 92 | startLogits, 93 | endLogits, 94 | maxAnswerLength 95 | ); 96 | 97 | const totalElapsedTime = Date.now() - totalStartTime; 98 | if (this.timeIt) { 99 | return { 100 | ...answer, 101 | inferenceTime: elapsedInferenceTime, 102 | totalTime: totalElapsedTime 103 | }; 104 | } else { 105 | return { ...answer }; 106 | } 107 | } 108 | 109 | private async getFeatures( 110 | question: string, 111 | context: string, 112 | stride = 128 113 | ): Promise { 114 | this.tokenizer.setPadding(this.model.inputLength); 115 | this.tokenizer.setTruncation(this.model.inputLength, { 116 | strategy: TruncationStrategy.OnlySecond, 117 | stride 118 | }); 119 | 120 | const encoding = await this.tokenizer.encode(question, context); 121 | const encodings = [encoding, ...encoding.overflowing]; 122 | 123 | const spans: Span[] = encodings.map((e, i) => ({ 124 | startIndex: (this.model.inputLength - stride) * i, 125 | length: this.model.inputLength 126 | })); 127 | 128 | const contextStartIndex = this.tokenizer.getContextStartIndex(encoding); 129 | return spans.map((s, i) => { 130 | const maxContextMap = getMaxContextMap(spans, i, contextStartIndex); 131 | 132 | return { 133 | contextStartIndex, 134 | encoding: encodings[i], 135 | maxContextMap: maxContextMap 136 | }; 137 | }); 138 | } 139 | 140 | private getAnswer( 141 | context: string, 142 | features: Feature[], 143 | startLogits: Logits, 144 | endLogits: Logits, 145 | maxAnswerLength: number 146 | ): Answer | null { 147 | const answers: { 148 | feature: Feature; 149 | score: number; 150 | startIndex: number; 151 | endIndex: number; 152 | startLogits: number[]; 153 | endLogits: number[]; 154 | }[] = []; 155 | 156 | for (let i = 0; i < features.length; i++) { 157 | const feature = features[i]; 158 | const starts = startLogits[i]; 159 | const ends = endLogits[i]; 160 | 161 | const contextLastIndex = this.tokenizer.getContextEndIndex(feature.encoding); 162 | const [filteredStartLogits, filteredEndLogits] = [starts, ends].map(logits => 163 | logits 164 | .slice(feature.contextStartIndex, contextLastIndex + 1) 165 | .map<[number, number]>((val, i) => [i + feature.contextStartIndex, val]) 166 | ); 167 | 168 | filteredEndLogits.sort((a, b) => b[1] - a[1]); 169 | for (const startLogit of filteredStartLogits) { 170 | filteredEndLogits.some(endLogit => { 171 | if (endLogit[0] < startLogit[0]) { 172 | return; 173 | } 174 | 175 | if (endLogit[0] - startLogit[0] + 1 > maxAnswerLength) { 176 | return; 177 | } 178 | 179 | if (!feature.maxContextMap.get(startLogit[0])) { 180 | return; 181 | } 182 | 183 | answers.push({ 184 | feature, 185 | startIndex: startLogit[0], 186 | endIndex: endLogit[0], 187 | score: startLogit[1] + endLogit[1], 188 | startLogits: starts, 189 | endLogits: ends 190 | }); 191 | 192 | return true; 193 | }); 194 | } 195 | } 196 | 197 | if (!answers.length) { 198 | return null; 199 | } 200 | 201 | const answer = answers.sort((a, b) => b.score - a.score)[0]; 202 | const offsets = answer.feature.encoding.offsets; 203 | 204 | const answerText = slice( 205 | context, 206 | offsets[answer.startIndex][0], 207 | offsets[answer.endIndex][1] 208 | ); 209 | 210 | const startProbs = softMax(answer.startLogits); 211 | const endProbs = softMax(answer.endLogits); 212 | const probScore = startProbs[answer.startIndex] * endProbs[answer.endIndex]; 213 | 214 | return { 215 | text: answerText.trim(), 216 | score: Math.round((probScore + Number.EPSILON) * 100) / 100 217 | }; 218 | } 219 | } 220 | 221 | function getMaxContextMap( 222 | spans: Span[], 223 | spanIndex: number, 224 | contextStartIndex: number 225 | ): Map { 226 | const map = new Map(); 227 | const spanLength = spans[spanIndex].length; 228 | 229 | let i = 0; 230 | while (i < spanLength) { 231 | const position = spans[spanIndex].startIndex + i; 232 | let bestScore = -1; 233 | let bestIndex = -1; 234 | 235 | for (const [ispan, span] of spans.entries()) { 236 | const spanEndIndex = span.startIndex + span.length - 1; 237 | if (position < span.startIndex || position > spanEndIndex) { 238 | continue; 239 | } 240 | 241 | const leftContext = position - span.startIndex; 242 | const rightContext = spanEndIndex - position; 243 | const score = Math.min(leftContext, rightContext) + 0.01 * span.length; 244 | if (score > bestScore) { 245 | bestScore = score; 246 | bestIndex = ispan; 247 | } 248 | } 249 | 250 | map.set(contextStartIndex + i, bestIndex === spanIndex); 251 | i++; 252 | } 253 | 254 | return map; 255 | } 256 | 257 | function softMax(values: number[]): number[] { 258 | const max = Math.max(...values); 259 | const exps = values.map(x => Math.exp(x - max)); 260 | const expsSum = exps.reduce((a, b) => a + b); 261 | return exps.map(e => e / expsSum); 262 | } 263 | -------------------------------------------------------------------------------- /src/runtimes/index.ts: -------------------------------------------------------------------------------- 1 | export { RuntimeType } from "./runtime"; 2 | -------------------------------------------------------------------------------- /src/runtimes/remote.runtime.ts: -------------------------------------------------------------------------------- 1 | import fetch from "node-fetch"; 2 | 3 | import { Logits, ModelInput } from "../models/model"; 4 | import { 5 | FullParams, 6 | PartialMetaGraph, 7 | PartialModelTensorInfo, 8 | Runtime, 9 | RuntimeOptions 10 | } from "./runtime"; 11 | 12 | export class Remote extends Runtime { 13 | private constructor(public params: Readonly) { 14 | super(params); 15 | } 16 | 17 | async runInference( 18 | ids: number[][], 19 | attentionMask: number[][], 20 | tokenTypeIds?: number[][] 21 | ): Promise<[Logits, Logits]> { 22 | const modelInputs = { 23 | [this.params.inputsNames[ModelInput.Ids]]: ids, 24 | [this.params.inputsNames[ModelInput.AttentionMask]]: attentionMask 25 | }; 26 | 27 | if (tokenTypeIds && this.params.inputsNames[ModelInput.TokenTypeIds]) { 28 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 29 | modelInputs[this.params.inputsNames[ModelInput.TokenTypeIds]!] = tokenTypeIds; 30 | } 31 | 32 | const result = await fetch(`${this.params.path}:predict`, { 33 | method: "POST", 34 | headers: { "Content-Type": "application/json" }, 35 | body: JSON.stringify({ 36 | inputs: modelInputs, 37 | // eslint-disable-next-line @typescript-eslint/camelcase 38 | signature_name: this.params.signatureName 39 | }) 40 | }).then(r => r.json()); 41 | 42 | const startLogits = result.outputs[this.params.outputsNames.startLogits] as Logits; 43 | const endLogits = result.outputs[this.params.outputsNames.endLogits] as Logits; 44 | 45 | return [startLogits, endLogits]; 46 | } 47 | 48 | static async fromOptions(options: RuntimeOptions): Promise { 49 | const modelGraph = await this.getRemoteMetaGraph(options.path); 50 | const fullParams = this.computeParams(options, modelGraph); 51 | 52 | return new Remote(fullParams); 53 | } 54 | 55 | private static async getRemoteMetaGraph(url: string): Promise { 56 | const httpResult = await fetch(`${url}/metadata`).then(r => r.json()); 57 | 58 | const rawSignatureDef = httpResult.metadata.signature_def.signature_def; 59 | const signatures = Object.keys(rawSignatureDef).filter(k => !k.startsWith("__")); 60 | const parsedSignatures = signatures.map(k => { 61 | const signature = rawSignatureDef[k]; 62 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 63 | const parsedInputs = Object.entries(signature.inputs).map< 64 | Record 65 | >(([key, val]) => { 66 | return { 67 | [key]: { 68 | shape: val.tensor_shape.dim.reduce( 69 | ( 70 | acc: number[], 71 | val: { 72 | size: string; 73 | } 74 | ) => [...acc, parseInt(val.size)], 75 | [] 76 | ) 77 | } 78 | }; 79 | }); 80 | return { 81 | [k]: { 82 | inputs: Object.assign({}, ...parsedInputs), 83 | outputs: Object.assign( 84 | {}, 85 | ...Object.keys(signature.outputs).map(key => ({ [key]: {} })) 86 | ) 87 | } 88 | }; 89 | }); 90 | 91 | return { 92 | signatureDefs: Object.assign({}, ...parsedSignatures) 93 | }; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/runtimes/runtime.ts: -------------------------------------------------------------------------------- 1 | import { Logits, ModelInput, ModelInputsNames, ModelOutputNames } from "../models/model"; 2 | 3 | const MODEL_DEFAULTS: ModelDefaults = { 4 | inputsNames: { 5 | [ModelInput.AttentionMask]: "attention_mask", 6 | [ModelInput.Ids]: "input_ids", 7 | [ModelInput.TokenTypeIds]: "token_type_ids" 8 | }, 9 | outputsNames: { 10 | endLogits: "output_1", 11 | startLogits: "output_0" 12 | }, 13 | signatureName: "serving_default" 14 | }; 15 | 16 | export enum RuntimeType { 17 | Remote = "remote", 18 | SavedModel = "saved_model", 19 | TFJS = "tfjs" 20 | } 21 | 22 | export type LocalRuntime = RuntimeType.SavedModel | RuntimeType.TFJS; 23 | 24 | export abstract class Runtime { 25 | constructor(public params: Readonly) {} 26 | 27 | protected static get defaults(): Readonly { 28 | return MODEL_DEFAULTS; 29 | } 30 | 31 | abstract runInference( 32 | ids: number[][], 33 | attentionMask: number[][], 34 | tokenTypeIds?: number[][] 35 | ): Promise<[Logits, Logits]>; 36 | 37 | protected static computeParams( 38 | options: RuntimeOptions, 39 | graph: PartialMetaGraph, 40 | defaults: Readonly = this.defaults 41 | ): FullParams { 42 | const inputsNames = options.inputs.reduce( 43 | (obj, input) => ({ 44 | ...obj, 45 | [input]: options.inputsNames?.[input] ?? defaults.inputsNames[input] 46 | }), 47 | {} 48 | ); 49 | 50 | const partialParams: Omit = { 51 | inputsNames: inputsNames as RuntimeInputsNames, 52 | outputsNames: { 53 | endLogits: options.outputsNames?.endLogits ?? defaults.outputsNames.endLogits, 54 | startLogits: 55 | options.outputsNames?.startLogits ?? defaults.outputsNames.startLogits 56 | }, 57 | path: options.path, 58 | signatureName: options.signatureName ?? defaults.signatureName 59 | }; 60 | 61 | const signatureDef = graph.signatureDefs[partialParams.signatureName]; 62 | if (!signatureDef) { 63 | throw new Error(`No signature matching name "${partialParams.signatureName}"`); 64 | } 65 | 66 | for (const inputName of Object.values(partialParams.inputsNames)) { 67 | if (!signatureDef.inputs[inputName]) { 68 | throw new Error(`No input matching name "${inputName}"`); 69 | } 70 | } 71 | 72 | for (const outputName of Object.values(partialParams.outputsNames)) { 73 | if (!signatureDef.outputs[outputName]) { 74 | throw new Error(`No output matching name "${outputName}"`); 75 | } 76 | } 77 | 78 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 79 | const rawShape = signatureDef.inputs[partialParams.inputsNames[ModelInput.Ids]!] 80 | .shape as number[] | { array: [number] }[]; 81 | const shape = 82 | typeof rawShape[0] === "number" 83 | ? rawShape 84 | : (rawShape as { array: [number] }[]).map(s => s.array[0]); 85 | 86 | return { 87 | ...partialParams, 88 | shape: shape as [number, number] 89 | }; 90 | } 91 | } 92 | 93 | export interface ModelDefaults { 94 | inputsNames: Required; 95 | outputsNames: Required; 96 | signatureName: string; 97 | } 98 | 99 | export interface RuntimeOptions { 100 | inputs: ReadonlyArray; 101 | inputsNames?: ModelInputsNames; 102 | outputsNames?: ModelOutputNames; 103 | path: string; 104 | /** 105 | * @default "serving_default" 106 | */ 107 | signatureName?: string; 108 | } 109 | 110 | export interface RuntimeInputsNames { 111 | [ModelInput.Ids]: string; 112 | [ModelInput.AttentionMask]: string; 113 | [ModelInput.TokenTypeIds]?: string; 114 | } 115 | 116 | export interface FullParams { 117 | inputsNames: RuntimeInputsNames; 118 | outputsNames: Required; 119 | path: string; 120 | shape: [number, number]; 121 | signatureName: string; 122 | } 123 | 124 | export interface PartialMetaGraph { 125 | signatureDefs: { 126 | [key: string]: { 127 | inputs: { 128 | [key: string]: PartialModelTensorInfo; 129 | }; 130 | outputs: { 131 | [key: string]: {}; 132 | }; 133 | }; 134 | }; 135 | } 136 | 137 | export interface PartialModelTensorInfo { 138 | shape?: number[]; 139 | } 140 | -------------------------------------------------------------------------------- /src/runtimes/saved-model.runtime.ts: -------------------------------------------------------------------------------- 1 | import * as tf from "@tensorflow/tfjs-node"; 2 | 3 | import { Logits } from "../models/model"; 4 | import { FullParams, Runtime, RuntimeOptions } from "./runtime"; 5 | import { SavedModelWorker } from "./saved-model.worker"; 6 | 7 | export class SavedModel extends Runtime { 8 | private static worker = new SavedModelWorker(); 9 | 10 | private constructor(params: Readonly) { 11 | super(params); 12 | } 13 | 14 | async runInference( 15 | ids: number[][], 16 | attentionMask: number[][], 17 | tokenTypeIds?: number[][] 18 | ): Promise<[Logits, Logits]> { 19 | return SavedModel.worker.queueInference( 20 | this.params.path, 21 | ids, 22 | attentionMask, 23 | tokenTypeIds 24 | ); 25 | } 26 | 27 | static async fromOptions(options: RuntimeOptions): Promise { 28 | const modelGraph = (await tf.node.getMetaGraphsFromSavedModel(options.path))[0]; 29 | const fullParams = this.computeParams(options, modelGraph); 30 | 31 | await SavedModel.worker.loadModel(fullParams); 32 | return new SavedModel(fullParams); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/runtimes/saved-model.worker-thread.ts: -------------------------------------------------------------------------------- 1 | import * as tf from "@tensorflow/tfjs-node"; 2 | import { TFSavedModel } from "@tensorflow/tfjs-node/dist/saved_model"; 3 | import { MessagePort, parentPort } from "worker_threads"; 4 | 5 | import { Logits, ModelInput } from "../models/model"; 6 | import { isOneDimensional } from "../utils"; 7 | import { FullParams } from "./runtime"; 8 | import { InferenceMessage, Message } from "./worker-message"; 9 | 10 | let loadPort: MessagePort; 11 | let inferencePort: MessagePort; 12 | 13 | const modelsMap = new Map(); 14 | const modelParamsMap = new Map(); 15 | 16 | parentPort?.on("message", (value: Message) => { 17 | switch (value.type) { 18 | case "infer": 19 | runInference(value); 20 | break; 21 | 22 | case "init": 23 | loadPort = value.loadPort; 24 | inferencePort = value.inferencePort; 25 | value.initPort.close(); 26 | break; 27 | 28 | case "load": 29 | initModel(value.params); 30 | break; 31 | } 32 | }); 33 | 34 | async function initModel(params: FullParams): Promise { 35 | try { 36 | modelsMap.set(params.path, await tf.node.loadSavedModel(params.path)); 37 | modelParamsMap.set(params.path, params); 38 | loadPort.postMessage({ model: params.path }); 39 | } catch (error) { 40 | loadPort.postMessage({ model: params.path, error }); 41 | } 42 | } 43 | 44 | async function runInference(value: InferenceMessage): Promise { 45 | try { 46 | const { ids, attentionMask, tokenTypeIds } = value.inputs; 47 | const logits = await predict(value.model, ids, attentionMask, tokenTypeIds); 48 | inferencePort.postMessage({ logits, _id: value._id }); 49 | } catch (error) { 50 | inferencePort.postMessage({ error, _id: value._id }); 51 | } 52 | } 53 | 54 | async function predict( 55 | modelPath: string, 56 | ids: number[][], 57 | attentionMask: number[][], 58 | tokenTypeIds?: number[][] 59 | ): Promise<[Logits, Logits]> { 60 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 61 | const model = modelsMap.get(modelPath)!; 62 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 63 | const params = modelParamsMap.get(modelPath)!; 64 | 65 | const result = tf.tidy(() => { 66 | const inputTensor = tf.tensor(ids, undefined, "int32"); 67 | const maskTensor = tf.tensor(attentionMask, undefined, "int32"); 68 | 69 | const modelInputs = { 70 | [params.inputsNames[ModelInput.Ids]]: inputTensor, 71 | [params.inputsNames[ModelInput.AttentionMask]]: maskTensor 72 | }; 73 | 74 | if (tokenTypeIds && params.inputsNames[ModelInput.TokenTypeIds]) { 75 | const tokenTypesTensor = tf.tensor(tokenTypeIds, undefined, "int32"); 76 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 77 | modelInputs[params.inputsNames[ModelInput.TokenTypeIds]!] = tokenTypesTensor; 78 | } 79 | 80 | return model?.predict(modelInputs) as tf.NamedTensorMap; 81 | }); 82 | 83 | let [startLogits, endLogits] = await Promise.all([ 84 | result[params.outputsNames.startLogits].squeeze().array() as Promise< 85 | number[] | number[][] 86 | >, 87 | result[params.outputsNames.endLogits].squeeze().array() as Promise< 88 | number[] | number[][] 89 | > 90 | ]); 91 | 92 | tf.dispose(result); 93 | 94 | if (isOneDimensional(startLogits)) { 95 | startLogits = [startLogits]; 96 | } 97 | 98 | if (isOneDimensional(endLogits)) { 99 | endLogits = [endLogits]; 100 | } 101 | 102 | return [startLogits, endLogits]; 103 | } 104 | -------------------------------------------------------------------------------- /src/runtimes/saved-model.worker.ts: -------------------------------------------------------------------------------- 1 | import { join as joinPaths } from "path"; 2 | import { MessageChannel, MessagePort, SHARE_ENV, Worker } from "worker_threads"; 3 | 4 | import { Logits } from "../models/model"; 5 | import { FullParams } from "./runtime"; 6 | import { InferenceMessage, InitMessage } from "./worker-message"; 7 | 8 | interface InferenceTask { 9 | id: number; 10 | model: string; 11 | onsuccess: (value?: [Logits, Logits] | PromiseLike<[Logits, Logits]>) => void; 12 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 13 | onerror: (reason?: any) => void; 14 | inputs: { 15 | ids: number[][]; 16 | attentionMask: number[][]; 17 | tokenTypeIds?: number[][]; 18 | }; 19 | } 20 | 21 | interface ModelInfos { 22 | loaded: boolean; 23 | onloaded?: () => void; 24 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 25 | onloaderror?: (error: any) => void; 26 | } 27 | 28 | export class SavedModelWorker extends Worker { 29 | private inferencePort: MessagePort; 30 | private initPort: MessagePort; 31 | private loaded?: true; 32 | private loadPort: MessagePort; 33 | private models = new Map(); 34 | private queues = new Map(); 35 | private taskId = 0; 36 | 37 | constructor() { 38 | super(joinPaths(__filename, "../saved-model.worker-thread.js"), { 39 | env: SHARE_ENV 40 | }); 41 | 42 | const initChannel = new MessageChannel(); 43 | this.initPort = initChannel.port2; 44 | 45 | const loadChannel = new MessageChannel(); 46 | this.loadPort = loadChannel.port2; 47 | 48 | const inferenceChannel = new MessageChannel(); 49 | this.inferencePort = inferenceChannel.port2; 50 | this.inferencePort.setMaxListeners(1000000); 51 | 52 | this.once("online", () => { 53 | this.initPort.once("close", () => (this.loaded = true)); 54 | const message: InitMessage = { 55 | type: "init", 56 | initPort: initChannel.port1, 57 | loadPort: loadChannel.port1, 58 | inferencePort: inferenceChannel.port1 59 | }; 60 | 61 | this.postMessage(message, [ 62 | initChannel.port1, 63 | loadChannel.port1, 64 | inferenceChannel.port1 65 | ]); 66 | }); 67 | 68 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 69 | this.loadPort.on("message", (data: { model: string; error?: any }) => { 70 | const modelInfos = this.models.get(data.model); 71 | if (data.error) { 72 | modelInfos?.onloaderror?.(data.error); 73 | return; 74 | } 75 | 76 | modelInfos?.onloaded?.(); 77 | this.models.set(data.model, { loaded: true }); 78 | this.run(data.model); 79 | }); 80 | } 81 | 82 | loadModel(params: FullParams): Promise { 83 | return new Promise((resolve, reject) => { 84 | this.models.set(params.path, { 85 | loaded: false, 86 | onloaded: resolve, 87 | onloaderror: reject 88 | }); 89 | 90 | this.queues.set(params.path, []); 91 | 92 | if (this.loaded) { 93 | this.postMessage({ type: "load", params }); 94 | } else { 95 | this.initPort.once("close", () => { 96 | this.postMessage({ type: "load", params }); 97 | }); 98 | } 99 | }); 100 | } 101 | 102 | queueInference( 103 | modelPath: string, 104 | ids: number[][], 105 | attentionMask: number[][], 106 | tokenTypeIds?: number[][] 107 | ): Promise<[Logits, Logits]> { 108 | const taskId = this.taskId++; 109 | return new Promise<[Logits, Logits]>((resolve, reject) => { 110 | const inferenceTask: InferenceTask = { 111 | id: taskId, 112 | model: modelPath, 113 | onsuccess: resolve, 114 | onerror: reject, 115 | inputs: { ids, attentionMask, tokenTypeIds } 116 | }; 117 | 118 | const model = this.models.get(inferenceTask.model); 119 | if (!model?.loaded) { 120 | const queue = this.queues.get(inferenceTask.model); 121 | queue && queue.push(inferenceTask); 122 | } else { 123 | this.runTask(inferenceTask); 124 | } 125 | }); 126 | } 127 | 128 | private run(model: string): void { 129 | const queue = this.queues.get(model) ?? []; 130 | const queueLength = queue.length; 131 | for (let i = 0; i < queueLength; i++) { 132 | this.runTask(queue[i]); 133 | } 134 | 135 | queue.splice(0, queueLength); 136 | } 137 | 138 | private runTask(task: InferenceTask): void { 139 | const listener = (data: { 140 | _id: number; 141 | logits: [Logits, Logits]; 142 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 143 | error?: any; 144 | }): void => { 145 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 146 | if (data._id != task!.id) { 147 | return; 148 | } else { 149 | this.inferencePort.removeListener("message", listener); 150 | } 151 | 152 | if (data.logits) { 153 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 154 | task!.onsuccess(data.logits); 155 | } else { 156 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 157 | task!.onerror(data.error); 158 | } 159 | }; 160 | 161 | this.inferencePort.on("message", listener); 162 | const message: InferenceMessage = { 163 | _id: task.id, 164 | type: "infer", 165 | inputs: task.inputs, 166 | model: task.model 167 | }; 168 | 169 | this.postMessage(message); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/runtimes/tfjs.runtime.ts: -------------------------------------------------------------------------------- 1 | import * as tf from "@tensorflow/tfjs-node"; 2 | import * as path from "path"; 3 | 4 | import { Logits, ModelInput } from "../models/model"; 5 | import { isOneDimensional } from "../utils"; 6 | import { 7 | FullParams, 8 | ModelDefaults, 9 | PartialMetaGraph, 10 | Runtime, 11 | RuntimeOptions 12 | } from "./runtime"; 13 | 14 | export class TFJS extends Runtime { 15 | private constructor(private model: tf.GraphModel, params: Readonly) { 16 | super(params); 17 | } 18 | 19 | protected static get defaults(): Readonly { 20 | return { 21 | ...super.defaults, 22 | outputsNames: { 23 | endLogits: "Identity", 24 | startLogits: "Identity_1" 25 | } 26 | }; 27 | } 28 | 29 | async runInference( 30 | ids: number[][], 31 | attentionMask: number[][], 32 | tokenTypeIds?: number[][] 33 | ): Promise<[Logits, Logits]> { 34 | const result = tf.tidy(() => { 35 | const inputTensor = tf.tensor(ids, undefined, "int32"); 36 | const maskTensor = tf.tensor(attentionMask, undefined, "int32"); 37 | 38 | const modelInputs = { 39 | [this.params.inputsNames[ModelInput.Ids]]: inputTensor, 40 | [this.params.inputsNames[ModelInput.AttentionMask]]: maskTensor 41 | }; 42 | 43 | if (tokenTypeIds && this.params.inputsNames[ModelInput.TokenTypeIds]) { 44 | const tokenTypesTensor = tf.tensor(tokenTypeIds, undefined, "int32"); 45 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 46 | modelInputs[this.params.inputsNames[ModelInput.TokenTypeIds]!] = tokenTypesTensor; 47 | } 48 | 49 | return this.model.predict(modelInputs) as tf.Tensor[]; 50 | }); 51 | 52 | let [startLogits, endLogits] = await Promise.all([ 53 | result[0].squeeze().array() as Promise, 54 | result[1].squeeze().array() as Promise 55 | ]); 56 | 57 | tf.dispose(result); 58 | 59 | if (isOneDimensional(startLogits)) { 60 | startLogits = [startLogits]; 61 | } 62 | 63 | if (isOneDimensional(endLogits)) { 64 | endLogits = [endLogits]; 65 | } 66 | 67 | return [startLogits, endLogits]; 68 | } 69 | 70 | static async fromOptions(options: RuntimeOptions): Promise { 71 | const fullPath = path.join(options.path, "tfjs"); 72 | 73 | const model = await tf.loadGraphModel(`file:///${fullPath}/model.json`); 74 | const modelGraph: PartialMetaGraph = { 75 | signatureDefs: { 76 | [options.signatureName ?? "serving_default"]: { 77 | inputs: Object.assign( 78 | {}, 79 | ...model.inputs.map(i => ({ [i.name]: { shape: i.shape } })) 80 | ), 81 | outputs: Object.assign({}, ...model.outputs.map(o => ({ [o.name]: {} }))) 82 | } 83 | } 84 | }; 85 | 86 | const fullParams = this.computeParams({ ...options, path: fullPath }, modelGraph); 87 | return new TFJS(model, fullParams); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/runtimes/worker-message.ts: -------------------------------------------------------------------------------- 1 | import { MessagePort } from "worker_threads"; 2 | 3 | import { FullParams } from "./runtime"; 4 | 5 | export interface BaseMessage { 6 | type: "load" | "infer" | "init"; 7 | } 8 | 9 | export interface InferenceMessage extends BaseMessage { 10 | _id: number; 11 | inputs: { 12 | ids: number[][]; 13 | attentionMask: number[][]; 14 | tokenTypeIds?: number[][]; 15 | }; 16 | model: string; 17 | type: "infer"; 18 | } 19 | 20 | export interface LoadMessage extends BaseMessage { 21 | params: FullParams; 22 | type: "load"; 23 | } 24 | 25 | export interface InitMessage extends BaseMessage { 26 | inferencePort: MessagePort; 27 | initPort: MessagePort; 28 | loadPort: MessagePort; 29 | type: "init"; 30 | } 31 | 32 | export type Message = LoadMessage | InferenceMessage | InitMessage; 33 | -------------------------------------------------------------------------------- /src/tokenizers/bert.tokenizer.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { 3 | BertWordPieceOptions, 4 | BertWordPieceTokenizer, 5 | Encoding, 6 | getTokenContent, 7 | Token 8 | } from "tokenizers"; 9 | 10 | import { DEFAULT_VOCAB_PATH } from "../qa-options"; 11 | import { exists } from "../utils"; 12 | import { FullTokenizerOptions, Tokenizer } from "./tokenizer"; 13 | 14 | export interface BertTokenizerOptions { 15 | clsToken: Token; 16 | maskToken: Token; 17 | padToken: Token; 18 | sepToken: Token; 19 | unkToken: Token; 20 | } 21 | 22 | export class BertTokenizer extends Tokenizer { 23 | static async fromOptions( 24 | options: FullTokenizerOptions 25 | ): Promise { 26 | let vocabPath = options.vocabFile; 27 | if (!vocabPath) { 28 | const fullPath = path.join(options.filesDir, "vocab.txt"); 29 | if (await exists(fullPath)) { 30 | vocabPath = fullPath; 31 | } 32 | 33 | vocabPath = vocabPath ?? DEFAULT_VOCAB_PATH; 34 | } 35 | 36 | const tokenizerOptions: BertWordPieceOptions = { 37 | vocabFile: vocabPath, 38 | lowercase: options.lowercase 39 | }; 40 | 41 | const tokens: (keyof BertTokenizerOptions)[] = [ 42 | "clsToken", 43 | "maskToken", 44 | "padToken", 45 | "sepToken", 46 | "unkToken" 47 | ]; 48 | 49 | for (const token of tokens) { 50 | if (options[token]) { 51 | tokenizerOptions[token] = options[token]; 52 | } 53 | } 54 | 55 | const tokenizer = await BertWordPieceTokenizer.fromOptions(tokenizerOptions); 56 | return new BertTokenizer(tokenizer); 57 | } 58 | 59 | getQuestionLength(encoding: Encoding): number { 60 | return ( 61 | encoding.tokens.indexOf(getTokenContent(this.tokenizer.configuration.sepToken)) - 1 // Take cls token into account 62 | ); 63 | } 64 | 65 | getContextStartIndex(encoding: Encoding): number { 66 | return this.getQuestionLength(encoding) + 2; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/tokenizers/index.ts: -------------------------------------------------------------------------------- 1 | export { Tokenizer } from "./tokenizer"; 2 | export { 3 | initTokenizer, 4 | BertTokenizerFactoryOptions, 5 | RobertaTokenizerFactoryOptions, 6 | TokenizerFactoryOptions 7 | } from "./tokenizer.factory"; 8 | -------------------------------------------------------------------------------- /src/tokenizers/roberta.tokenizer.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import { 3 | AddedToken, 4 | ByteLevelBPETokenizer, 5 | Encoding, 6 | getTokenContent, 7 | PaddingConfiguration, 8 | Token 9 | } from "tokenizers"; 10 | import { robertaProcessing } from "tokenizers/bindings/post-processors"; 11 | 12 | import { exists } from "../utils"; 13 | import { FullTokenizerOptions, Tokenizer } from "./tokenizer"; 14 | 15 | export interface RobertaTokenizerOptions { 16 | clsToken: Token; 17 | eosToken: Token; 18 | maskToken: Token; 19 | padToken: Token; 20 | unkToken: Token; 21 | } 22 | 23 | export class RobertaTokenizer extends Tokenizer { 24 | private readonly clsToken: Token; 25 | private readonly eosToken: Token; 26 | private readonly maskToken: Token; 27 | private readonly padToken: Token; 28 | private readonly unkToken: Token; 29 | 30 | constructor(tokenizer: ByteLevelBPETokenizer, options: RobertaTokenizerOptions) { 31 | super(tokenizer); 32 | 33 | this.clsToken = options.clsToken; 34 | this.eosToken = options.eosToken; 35 | this.maskToken = options.maskToken; 36 | this.padToken = options.padToken; 37 | this.unkToken = options.unkToken; 38 | } 39 | 40 | static async fromOptions( 41 | options: FullTokenizerOptions 42 | ): Promise { 43 | let vocabFile = options.vocabFile; 44 | 45 | if (!vocabFile) { 46 | const fullPath = path.join(options.filesDir, "vocab.json"); 47 | if (await exists(fullPath)) { 48 | vocabFile = fullPath; 49 | } 50 | 51 | if (!vocabFile) { 52 | throw new Error( 53 | "Unable to find a vocab file. Make sure to provide its path in the options" 54 | ); 55 | } 56 | } 57 | 58 | let mergesFile = options.mergesFile; 59 | if (!mergesFile) { 60 | const fullPath = path.join(options.filesDir, "merges.txt"); 61 | if (await exists(fullPath)) { 62 | mergesFile = fullPath; 63 | } 64 | 65 | if (!mergesFile) { 66 | throw new Error( 67 | "Unable to find a merges file. Make sure to provide its path in the options" 68 | ); 69 | } 70 | } 71 | 72 | const tokenizer = await ByteLevelBPETokenizer.fromOptions({ 73 | addPrefixSpace: true, 74 | mergesFile, 75 | vocabFile 76 | }); 77 | 78 | const clsToken = options.clsToken ?? ""; 79 | const eosToken = options.eosToken ?? ""; 80 | const maskToken = 81 | options.maskToken ?? new AddedToken("", true, { leftStrip: true }); 82 | const padToken = options.padToken ?? ""; 83 | const unkToken = options.unkToken ?? ""; 84 | 85 | const eosString = getTokenContent(eosToken); 86 | const clsString = getTokenContent(clsToken); 87 | const postProcessor = robertaProcessing( 88 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 89 | [eosString, tokenizer.tokenToId(eosString)!], 90 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 91 | [clsString, tokenizer.tokenToId(clsString)!] 92 | ); 93 | 94 | tokenizer.setPostProcessor(postProcessor); 95 | tokenizer.addSpecialTokens([clsToken, eosToken, maskToken, padToken, unkToken]); 96 | 97 | return new RobertaTokenizer(tokenizer, { 98 | clsToken, 99 | eosToken, 100 | maskToken, 101 | padToken, 102 | unkToken 103 | }); 104 | } 105 | 106 | getQuestionLength(encoding: Encoding): number { 107 | return encoding.tokens.indexOf(getTokenContent(this.eosToken)) - 1; // Take cls token into account 108 | } 109 | 110 | getContextStartIndex(encoding: Encoding): number { 111 | return this.getQuestionLength(encoding) + 3; 112 | } 113 | 114 | /** 115 | * Enable/change padding with specified options 116 | * @param maxLength Padding length 117 | * @override 118 | */ 119 | setPadding(maxLength: number): Readonly { 120 | const padToken = getTokenContent(this.padToken); 121 | return this.tokenizer.setPadding({ 122 | maxLength, 123 | padToken: padToken, 124 | padId: this.tokenizer.tokenToId(padToken) 125 | }); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/tokenizers/tokenizer.factory.ts: -------------------------------------------------------------------------------- 1 | import { getModelType, ModelType } from "../models/model"; 2 | import { DEFAULT_ASSETS_DIR } from "../qa-options"; 3 | import { getAbsolutePath, getVocab, TokenMappingKey } from "../utils"; 4 | import { BertTokenizer, BertTokenizerOptions } from "./bert.tokenizer"; 5 | import { RobertaTokenizer, RobertaTokenizerOptions } from "./roberta.tokenizer"; 6 | import { FullTokenizerOptions, Tokenizer } from "./tokenizer"; 7 | 8 | interface TokenizerFactoryBaseOptions { 9 | lowercase?: boolean; 10 | /** 11 | * Name of the merges file (if applicable to the tokenizer) 12 | * @default "merges.txt" 13 | */ 14 | mergesFile?: string; 15 | /** 16 | * Directory under which the files needed by the tokenizer are located. 17 | * Can be absolute or relative to the root of the project. 18 | * If no corresponding files are found AND a `modelName` is provided, an attempt will be made to download them. 19 | */ 20 | filesDir: string; 21 | /** 22 | * Fully qualified name of the model (including the author if applicable) 23 | * @example "distilbert-base-uncased-distilled-squad" 24 | * @example "deepset/bert-base-cased-squad2" 25 | */ 26 | modelName?: string; 27 | /** 28 | * Type of the model (inferred from model name by default) 29 | */ 30 | modelType?: ModelType; 31 | /** 32 | * Name of the vocab file (if applicable to the tokenizer) 33 | * @default "vocab.txt" | "vocab.json" 34 | */ 35 | vocabFile?: string; 36 | } 37 | 38 | export interface RobertaTokenizerFactoryOptions 39 | extends TokenizerFactoryBaseOptions, 40 | Partial { 41 | modelType: ModelType.Roberta; 42 | } 43 | 44 | export interface BertTokenizerFactoryOptions 45 | extends TokenizerFactoryBaseOptions, 46 | Partial { 47 | modelType?: ModelType.Bert | ModelType.Distilbert; 48 | } 49 | 50 | export type TokenizerFactoryOptions = 51 | | RobertaTokenizerFactoryOptions 52 | | BertTokenizerFactoryOptions; 53 | 54 | const TOKEN_KEYS_MAPPING: Record< 55 | TokenMappingKey, 56 | keyof FullTokenizerOptions 57 | > = { 58 | // eslint-disable-next-line @typescript-eslint/camelcase 59 | cls_token: "clsToken", 60 | // eslint-disable-next-line @typescript-eslint/camelcase 61 | eos_token: "eosToken", 62 | // eslint-disable-next-line @typescript-eslint/camelcase 63 | mask_token: "maskToken", 64 | // eslint-disable-next-line @typescript-eslint/camelcase 65 | pad_token: "padToken", 66 | // eslint-disable-next-line @typescript-eslint/camelcase 67 | sep_token: "sepToken", 68 | // eslint-disable-next-line @typescript-eslint/camelcase 69 | unk_token: "unkToken" 70 | }; 71 | 72 | export async function initTokenizer( 73 | options: TokenizerFactoryOptions 74 | ): Promise { 75 | let modelType = options.modelType; 76 | if (!modelType) { 77 | if (!options.modelName) { 78 | throw new Error( 79 | "Either a model type or a model name must be provided to init a tokenizer" 80 | ); 81 | } 82 | 83 | modelType = getModelType(options.modelName); 84 | } 85 | 86 | const fullOptions: FullTokenizerOptions = { 88 | ...options, 89 | filesDir: getAbsolutePath(options.filesDir, DEFAULT_ASSETS_DIR), 90 | modelType 91 | }; 92 | 93 | if (options.modelName) { 94 | const vocabConfig = await getVocab( 95 | { 96 | dir: fullOptions.filesDir, 97 | modelName: options.modelName, 98 | mergesFile: options.mergesFile, 99 | vocabFile: options.vocabFile 100 | }, 101 | true 102 | ); 103 | 104 | if ( 105 | typeof fullOptions.lowercase === "undefined" && 106 | typeof vocabConfig.tokenizer.do_lower_case === "boolean" 107 | ) { 108 | fullOptions.lowercase = vocabConfig.tokenizer.do_lower_case; 109 | } 110 | 111 | for (const [key, mapping] of Object.entries(TOKEN_KEYS_MAPPING)) { 112 | if ( 113 | fullOptions[mapping] === undefined && 114 | typeof vocabConfig.tokensMapping[key as TokenMappingKey] === "string" 115 | ) { 116 | (fullOptions[mapping] as string) = vocabConfig.tokensMapping[ 117 | key as TokenMappingKey 118 | ] as string; 119 | } 120 | } 121 | } 122 | 123 | if (typeof fullOptions.lowercase === "undefined") { 124 | if (options.modelName?.toLocaleLowerCase().includes("uncased")) { 125 | fullOptions.lowercase = true; 126 | } else if (options.modelName?.toLocaleLowerCase().includes("cased")) { 127 | fullOptions.lowercase = false; 128 | } 129 | } 130 | 131 | let tokenizer: Tokenizer; 132 | switch (fullOptions.modelType) { 133 | case ModelType.Roberta: 134 | tokenizer = await RobertaTokenizer.fromOptions(fullOptions); 135 | break; 136 | 137 | default: 138 | tokenizer = await BertTokenizer.fromOptions(fullOptions); 139 | break; 140 | } 141 | 142 | return tokenizer; 143 | } 144 | -------------------------------------------------------------------------------- /src/tokenizers/tokenizer.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BaseTokenizer, 3 | Encoding, 4 | PaddingConfiguration, 5 | TruncationConfiguration, 6 | TruncationOptions 7 | } from "tokenizers"; 8 | 9 | import { ModelType } from "../models"; 10 | 11 | export interface TokenizerBaseOptions { 12 | /** 13 | * @default true 14 | */ 15 | lowercase?: boolean; 16 | /** 17 | * Name of the merges file (if applicable to the tokenizer) 18 | * @default "merges.txt" 19 | */ 20 | mergesFile?: string; 21 | /** 22 | * Directory under which the files needed by the tokenizer are located. 23 | * Must be an absolute path. 24 | */ 25 | filesDir: string; 26 | modelType: ModelType; 27 | /** 28 | * Name of the vocab file (if applicable to the tokenizer) 29 | * @default "vocab.txt" | "vocab.json" 30 | */ 31 | vocabFile?: string; 32 | } 33 | 34 | export type FullTokenizerOptions = TokenizerBaseOptions & 35 | Partial; 36 | 37 | export abstract class Tokenizer = BaseTokenizer> { 38 | constructor(protected tokenizer: T) {} 39 | 40 | abstract getQuestionLength(encoding: Encoding): number; 41 | 42 | abstract getContextStartIndex(encoding: Encoding): number; 43 | 44 | /** 45 | * Get the last index of the context of an encoding 46 | * @param encoding Encoding for which to return last context index 47 | * @virtual 48 | */ 49 | getContextEndIndex(encoding: Encoding): number { 50 | const nbAddedTokens = encoding.specialTokensMask.reduce((acc, val) => acc + val, 0); 51 | const actualLength = encoding.length - nbAddedTokens; 52 | const contextLength = actualLength - this.getQuestionLength(encoding); 53 | 54 | return this.getContextStartIndex(encoding) + contextLength - 1; 55 | } 56 | 57 | encode(sequence: string, pair?: string, addSpecialTokens = true): Promise { 58 | return this.tokenizer.encode(sequence, pair, { addSpecialTokens }); 59 | } 60 | 61 | /** 62 | * Enable/change padding with specified options 63 | * @param maxLength Padding length 64 | * @virtual 65 | */ 66 | setPadding(maxLength: number): Readonly { 67 | return this.tokenizer.setPadding({ maxLength }); 68 | } 69 | 70 | setTruncation( 71 | maxLength: number, 72 | options?: TruncationOptions 73 | ): Readonly { 74 | return this.tokenizer.setTruncation(maxLength, options); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import fs from "fs"; 2 | import https from "https"; 3 | import fetch from "node-fetch"; 4 | import path from "path"; 5 | import ProgressBar from "progress"; 6 | import shell from "shelljs"; 7 | import tar from "tar"; 8 | import { promisify } from "util"; 9 | 10 | import { getModelType, ModelType } from "./models/model"; 11 | import { ROOT_DIR } from "./qa-options"; 12 | import { LocalRuntime, RuntimeType } from "./runtimes/runtime"; 13 | 14 | export const exists = promisify(fs.exists); 15 | 16 | /** 17 | * Ensures a directory exists, creates as needed. 18 | */ 19 | export async function ensureDir(dirPath: string, recursive = true): Promise { 20 | if (!(await exists(dirPath))) { 21 | recursive ? shell.mkdir("-p", dirPath) : shell.mkdir(dirPath); 22 | } 23 | } 24 | 25 | export function isOneDimensional(arr: number[] | number[][]): arr is number[] { 26 | return !Array.isArray(arr[0]); 27 | } 28 | 29 | export interface DownloadOptions { 30 | model: string; 31 | dir: string; 32 | format?: RuntimeType; 33 | force?: boolean; 34 | fullDir?: boolean; 35 | } 36 | 37 | /** 38 | * Download a model with associated vocabulary files 39 | * @param options Download options 40 | */ 41 | export async function downloadModelWithVocab(options: DownloadOptions): Promise { 42 | const modelFormat = options.format ?? RuntimeType.SavedModel; 43 | 44 | const assetsDir = getAbsolutePath(options.dir); 45 | const modelDir = path.join(assetsDir, options.model); 46 | 47 | if (options.force) { 48 | shell.rm("-rf", modelDir); 49 | } 50 | 51 | if (modelFormat !== RuntimeType.Remote) { 52 | await downloadModel({ 53 | dir: modelDir, 54 | format: modelFormat, 55 | name: options.model, 56 | verbose: true 57 | }); 58 | } 59 | 60 | await getVocab({ 61 | dir: modelDir, 62 | modelName: options.model, 63 | verbose: true 64 | }); 65 | 66 | shell.echo("\nModel successfully downloaded!"); 67 | } 68 | 69 | export interface ModelDownloadOptions { 70 | /** 71 | * Absolute path to the directory under which download model 72 | */ 73 | dir: string; 74 | format: LocalRuntime; 75 | name: string; 76 | verbose?: boolean; 77 | } 78 | 79 | export async function downloadModel(model: ModelDownloadOptions): Promise { 80 | const modelDir = path.join( 81 | model.dir, 82 | model.format === RuntimeType.TFJS ? RuntimeType.TFJS : "" 83 | ); 84 | 85 | if (await exists(modelDir)) { 86 | const exit = (): void => 87 | void model.verbose && 88 | shell.echo( 89 | `Model ${model.name} (format: ${model.format}) already exists, doing nothing...` 90 | ); 91 | 92 | if (model.format === RuntimeType.TFJS) { 93 | return exit(); 94 | } else if (model.format === RuntimeType.SavedModel) { 95 | if (await exists(path.join(modelDir, "saved_model.pb"))) { 96 | return exit(); 97 | } 98 | } 99 | } 100 | 101 | await ensureDir(modelDir); 102 | shell.echo("Downloading model..."); 103 | 104 | let url: string; 105 | // eslint-disable-next-line @typescript-eslint/no-use-before-define 106 | if (HF_MODELS_MAPPING[model.name]) { 107 | // eslint-disable-next-line @typescript-eslint/no-use-before-define 108 | const defaultUrl = HF_MODELS_MAPPING[model.name][model.format]; 109 | if (!defaultUrl) { 110 | throw new Error( 111 | `This model does not appear to be available in ${model.format} format` 112 | ); 113 | } 114 | 115 | url = defaultUrl; 116 | } else { 117 | url = getHfUrl(model.name, `${model.format}.tar.gz`); 118 | } 119 | 120 | await new Promise((resolve, reject) => { 121 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 122 | https.get(url, res => { 123 | const bar = new ProgressBar("[:bar] :percent :etas", { 124 | width: 30, 125 | total: parseInt(res.headers["content-length"] ?? "0", 10) 126 | }); 127 | 128 | res 129 | .on("data", chunk => bar.tick(chunk.length)) 130 | .pipe(tar.x({ cwd: modelDir })) 131 | .on("close", resolve) 132 | .on("error", reject); 133 | }); 134 | }); 135 | } 136 | 137 | export interface VocabDownloadOptions extends VocabFiles { 138 | /** 139 | * Absolute path to the directory under which download vocab files 140 | */ 141 | dir: string; 142 | modelName: string; 143 | verbose?: boolean; 144 | } 145 | 146 | interface VocabFiles { 147 | /** 148 | * Name of the merges file (if applicable to the tokenizer) 149 | * @default "merges.txt" 150 | */ 151 | mergesFile?: string; 152 | /** 153 | * Name of the vocab file (if applicable to the tokenizer) 154 | * @default "vocab.txt" | "vocab.json" 155 | */ 156 | vocabFile?: string; 157 | } 158 | 159 | type VocabFilesKey = keyof VocabFiles; 160 | type ConfigFilesKey = "tokenizer_config.json" | "special_tokens_map.json"; 161 | 162 | const VOCAB_CONFIG_KEYS: ConfigFilesKey[] = [ 163 | "tokenizer_config.json", 164 | "special_tokens_map.json" 165 | ]; 166 | 167 | export interface VocabConfiguration { 168 | tokenizer: { 169 | do_lower_case?: boolean; 170 | }; 171 | tokensMapping: Partial>; 172 | } 173 | 174 | export type TokenMappingKey = 175 | | "cls_token" 176 | | "eos_token" 177 | | "mask_token" 178 | | "pad_token" 179 | | "sep_token" 180 | | "unk_token"; 181 | 182 | const VOCAB_MAPPING: Partial> = { 183 | [ModelType.Roberta]: { mergesFile: "merges.txt", vocabFile: "vocab.json" } 184 | }; 185 | 186 | const DEFAULT_VOCAB = { vocabFile: { name: "vocab.txt" } }; 187 | 188 | type VocabReturn = TReturnConfig extends true ? VocabConfiguration : void; 189 | 190 | export async function getVocab( 191 | options: VocabDownloadOptions, 192 | returnConfig?: TReturnConfig 193 | ): Promise> { 194 | await ensureDir(options.dir); 195 | 196 | const modelType = getModelType(options.modelName); 197 | if (!modelType) { 198 | throw new Error( 199 | "The model name does not allow to infer the associated tokenizer and thus which vocab files to download" 200 | ); 201 | } 202 | 203 | let vocabFiles: Partial>; 207 | // eslint-disable-next-line @typescript-eslint/no-use-before-define 208 | const hfVocabUrl: string | undefined = HF_VOCAB_FILES_MAPPING[options.modelName]; 209 | if (hfVocabUrl) { 210 | vocabFiles = { vocabFile: { name: "vocab.txt", url: hfVocabUrl } }; 211 | } else { 212 | const mapping = VOCAB_MAPPING[modelType]; 213 | if (mapping) { 214 | vocabFiles = {}; 215 | for (const key of Object.keys(mapping) as VocabFilesKey[]) { 216 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 217 | vocabFiles[key] = { name: mapping[key]! }; 218 | } 219 | } else { 220 | vocabFiles = DEFAULT_VOCAB; 221 | } 222 | 223 | for (const file of ["mergesFile", "vocabFile"] as VocabFilesKey[]) { 224 | if (options[file]) { 225 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 226 | vocabFiles[file] = { name: options[file]! }; 227 | } 228 | } 229 | } 230 | 231 | const vocabConfig: VocabConfiguration = { 232 | tokenizer: {}, 233 | tokensMapping: {} 234 | }; 235 | 236 | for (const file of VOCAB_CONFIG_KEYS) { 237 | vocabFiles[file] = { name: file, optional: true }; 238 | } 239 | 240 | for (const vocabFile of Object.values(vocabFiles)) { 241 | if (!vocabFile) { 242 | continue; 243 | } 244 | 245 | const file = path.join(options.dir, vocabFile.name); 246 | if (!(await exists(file))) { 247 | shell.echo(`Downloading ${vocabFile.name}...`); 248 | 249 | const url = vocabFile.url ?? getHfUrl(options.modelName, vocabFile.name); 250 | 251 | const response = await fetch(url); 252 | if (!response.ok) { 253 | if (vocabFile.optional !== true) { 254 | throw new Error(`Unable to download ${vocabFile.name} at ${url}`); 255 | } else { 256 | continue; 257 | } 258 | } 259 | 260 | const rawValue = await response.text(); 261 | await fs.promises.writeFile(file, rawValue); 262 | 263 | if (returnConfig && VOCAB_CONFIG_KEYS.includes(vocabFile.name as ConfigFilesKey)) { 264 | const configKey = getVocabConfigKey(vocabFile.name as ConfigFilesKey); 265 | vocabConfig[configKey] = JSON.parse(rawValue); 266 | } 267 | } else { 268 | options.verbose && shell.echo(`${vocabFile.name} already exists, doing nothing...`); 269 | 270 | if (returnConfig && VOCAB_CONFIG_KEYS.includes(vocabFile.name as ConfigFilesKey)) { 271 | try { 272 | const configFile = await fs.promises.readFile(file, { encoding: "utf-8" }); 273 | const configKey = getVocabConfigKey(vocabFile.name as ConfigFilesKey); 274 | vocabConfig[configKey] = JSON.parse(configFile); 275 | } catch (error) { 276 | // Nothing 277 | } 278 | } 279 | } 280 | } 281 | 282 | if (returnConfig === true) { 283 | return vocabConfig as VocabReturn; 284 | } 285 | 286 | return void 0 as VocabReturn; 287 | } 288 | 289 | function getHfUrl(model: string, file: string): string { 290 | return `https://cdn.huggingface.co/${model}/${file}`; 291 | } 292 | 293 | function getVocabConfigKey(filename: ConfigFilesKey): keyof VocabConfiguration { 294 | return filename === "tokenizer_config.json" ? "tokenizer" : "tokensMapping"; 295 | } 296 | 297 | export function getAbsolutePath(pathToCheck?: string, rootDir = ROOT_DIR): string { 298 | if (!pathToCheck) { 299 | return rootDir; 300 | } 301 | 302 | return path.isAbsolute(pathToCheck) ? pathToCheck : path.join(rootDir, pathToCheck); 303 | } 304 | 305 | const HF_VOCAB_FILES_MAPPING: Record = { 306 | /** DistilBERT */ 307 | "distilbert-base-uncased-distilled-squad": 308 | "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt", 309 | "distilbert-base-cased-distilled-squad": 310 | "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt", 311 | /** BERT */ 312 | "bert-large-uncased-whole-word-masking-finetuned-squad": 313 | "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-vocab.txt", 314 | "bert-large-cased-whole-word-masking-finetuned-squad": 315 | "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-vocab.txt" 316 | }; 317 | 318 | interface DefaultModel { 319 | [RuntimeType.SavedModel]: string; 320 | [RuntimeType.TFJS]?: string; 321 | } 322 | 323 | const HF_MODELS_MAPPING: Record = { 324 | /** BERT */ 325 | "bert-large-cased-whole-word-masking-finetuned-squad": { 326 | [RuntimeType.SavedModel]: 327 | "https://cdn.huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad-saved_model.tar.gz" 328 | }, 329 | "bert-large-uncased-whole-word-masking-finetuned-squad": { 330 | [RuntimeType.SavedModel]: 331 | "https://cdn.huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad-saved_model.tar.gz" 332 | }, 333 | /** DistilBERT */ 334 | "distilbert-base-cased-distilled-squad": { 335 | [RuntimeType.SavedModel]: 336 | "https://cdn.huggingface.co/distilbert-base-cased-distilled-squad-saved_model.tar.gz", 337 | [RuntimeType.TFJS]: 338 | "https://cdn.huggingface.co/distilbert-base-cased-distilled-squad-tfjs.tar.gz" 339 | }, 340 | "distilbert-base-uncased-distilled-squad": { 341 | [RuntimeType.SavedModel]: 342 | "https://cdn.huggingface.co/distilbert-base-uncased-distilled-squad-saved_model.tar.gz" 343 | } 344 | }; 345 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "skipLibCheck": true, 4 | /* Basic Options */ 5 | // "incremental": true, /* Enable incremental compilation */ 6 | "target": "ES2018", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ 7 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 8 | // "lib": [], /* Specify library files to be included in the compilation. */ 9 | // "allowJs": true, /* Allow javascript files to be compiled. */ 10 | // "checkJs": true, /* Report errors in .js files. */ 11 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 12 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 13 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 14 | "sourceMap": true, /* Generates corresponding '.map' file. */ 15 | // "outFile": "./", /* Concatenate and emit output to single file. */ 16 | "outDir": "./dist", /* Redirect output structure to the directory. */ 17 | "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 18 | // "composite": true, /* Enable project compilation */ 19 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 20 | // "removeComments": true, /* Do not emit comments to output. */ 21 | // "noEmit": true, /* Do not emit outputs. */ 22 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 23 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 24 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 25 | 26 | /* Strict Type-Checking Options */ 27 | "strict": true, /* Enable all strict type-checking options. */ 28 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 29 | // "strictNullChecks": true, /* Enable strict null checks. */ 30 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 31 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 32 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 33 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 34 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 35 | 36 | /* Additional Checks */ 37 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 38 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 39 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 40 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 41 | 42 | /* Module Resolution Options */ 43 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 44 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 45 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 46 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 47 | // "typeRoots": [], /* List of folders to include type definitions from. */ 48 | // "types": [], /* Type declaration files to be included in compilation. */ 49 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 50 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 51 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 52 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 53 | 54 | /* Source Map Options */ 55 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 56 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 57 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 58 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 59 | 60 | /* Experimental Options */ 61 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 62 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /tsconfig.prod.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": [ 4 | "./**/*.test.ts" 5 | ], 6 | "compilerOptions": { 7 | "sourceMap": false, 8 | "declaration": true 9 | } 10 | } --------------------------------------------------------------------------------