在浏览器中运行
在 https://xenova.github.io/transformers.js/ 查看我们的演示。如你所见,一切都在浏览器中运行!
如果使用 npm,则可以使用以下方法安装它:
npm i @xenova/transformers
或者,你可以在 CDN 中的代码中使用它,例如:
<script>
<!-- Using jsDelivr -->
<script src="https://cdn.jsdelivr.net/npm/@xenova/transformers/dist/transformers.min.js"></script>
<!-- or UNPKG -->
<script src="https://www.unpkg.com/@xenova/transformers/dist/transformers.min.js"></script>
从现有代码翻译非常容易!
蟒蛇(原版) | Javascript (我们的) |
---|---|
from transformers import pipeline
# Allocate a pipeline for sentiment-analysis
pipe = pipeline('sentiment-analysis')
out = pipe('I love transformers!')
# [{'label': 'POSITIVE', 'score': 0.999806941}] |
import { pipeline } from "@xenova/transformers";
// Allocate a pipeline for sentiment-analysis
let pipe = await pipeline('sentiment-analysis');
let out = await pipe('I love transformers!');
// [{'label': 'POSITIVE', 'score': 0.999817686}] |
与 Python 库相同,你可以通过提供其名称作为管道函数的第二个参数来使用不同的模型。例如:
// Use a different model for sentiment-analysis
let pipe = await pipeline('sentiment-analysis', 'nlptown/bert-base-multilingual-uncased-sentiment');
默认情况下,Transformers.js 使用托管模型和预编译的 WASM 二进制文件,这些二进制文件应开箱即用。你可以按如下方式覆盖此行为:
import { env } from "@xenova/transformers";
// Use a different host for models.
// - `remoteURL` defaults to use the HuggingFace Hub
// - `localURL` defaults to '/models/onnx/quantized/'
env.remoteURL = 'https://www.example.com/';
env.localURL = '/path/to/models/';
// Set whether to use remote or local models. Defaults to true.
// - If true, use the path specified by `env.remoteURL`.
// - If false, use the path specified by `env.localURL`.
env.remoteModels = false;
// Set parent path of .wasm files. Defaults to use a CDN.
env.onnx.wasm.wasmPaths = '/path/to/files/';
我们使用 ONNX 运行时在浏览器中运行模型,因此你必须首先将 PyTorch 模型转换为 ONNX(这可以使用我们的转换脚本来完成)。通常,该命令将如下所示:
python ./scripts/convert.py --model_id <hf_model_id> --from_hub --quantize --task <task>
例如,若要用于掩码语言建模,可以使用以下命令:
bert-base-uncased
python ./scripts/convert.py --model_id bert-base-uncased --from_hub --quantize --task masked-lm
如果要使用本地模型,请从上面删除标志并将 PyTorch 模型放在文件夹中。你还可以通过指定父输入文件夹来选择其他位置(注意:没有模型 ID)。
--from_hub
./models/pytorch/
--input_parent_dir /path/to/parent_dir/
或者,你可以在此处找到我们已经转换的一些模型。例如,若要用于掩码语言建模,可以使用在 https://huggingface.co/Xenova/transformers.js/tree/main/quantized/bert-base-uncased/masked-lm 中找到的模型。
bert-base-uncased
注意:我们建议量化模型 () 以减小模型大小并提高推理速度(以略微降低准确性为代价)。有关详细信息,请运行 help 命令:。
--quantize
python ./scripts/convert.py -h
即将推出。。。
即将推出。。。同时,请在此处查看演示的源代码。