/ Модель

Характеристики

Контекст
512 токенов
Параметры
40 млн
Лицензия
MIT
Архитектура
bert · dense
Базовая модель
bge-small-en-v1.5
Библиотека
mnn
Опубликована
17 апр 2026

bge-small-en-MNN

ЭмбеддингиТекст → embedding9 профессий
7 202скачиваний за 30 дней0лайковвеса обновлены11 ноя 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

darkmaniac7/bge-small-en-MNN — это конверсия модели эмбеддингов BAAI/bge-small-en-v1.5 в формат MNN, подготовленная TokForge для локального вывода на Android, Linux и iOS.

Модель предназначена для построения векторных представлений текстов, семантического поиска, sentence similarity, RAG, а также формирования embeddings для памяти и задач reflection на устройствах без зависимости от GGUF/llama.cpp. Исходные веса разработаны Beijing Academy of Artificial Intelligence, а конверсия не содержит новых весов.

Модель основана на 12-слойном BERT-энкодере с 33 млн параметров, размером скрытого состояния 384, 12 attention heads и промежуточным слоем размерности 1536. Используются CLS-пулинг и L2-нормализация; размер итогового embedding — 384, максимальная длина последовательности — 512 токенов. Веса представлены в fp16, размер файла составляет около 64 МБ. Поддерживается английский язык; модель принимает токенизированный текст и возвращает last_hidden_state, из которого извлекается embedding CLS-токена.

Сильная сторона модели — возможность эффективного on-device-инференса через MNN и практически полное совпадение качества с GGUF-базовой версией в указанном синтетическом retrieval-тесте: для Recall@1, @3, @5 и @10 регрессии не выявлено, а среднее межмодельное cosine similarity составило 0,9962. Ограничения включают поддержку только английского языка, предел в 512 токенов и необходимость корректно выполнять CLS-пулинг, L2-нормализацию и, для асимметричного поиска, добавлять стандартный BGE-префикс к запросу. Модель распространяется по лицензии MIT.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит9

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

bge-small-en-v1.5 (MNN, TFLite)

BAAI's bge-small-en-v1.5 embedding model in MNN and TensorFlow Lite form, which TokForge uses on the phone to search your documents and memories.

Published by TokForge for on-device inference.

What it isEmbedding model (helper model, 384-dim vectors)
FormatMNN encoder (fp16) and four TensorFlow Lite files (INT8 weights)
Runs onAndroid phones (CPU: TensorFlow Lite with XNNPACK, or MNN)
Phone class4 GB RAM or more (TokForge helper module)
Download207 MB (11 files)
Base modelBAAI/bge-small-en-v1.5
LicenseMIT

TokForge

Runs on-device in the TokForge app.

Use it in TokForge

  1. Install TokForge from Google Play.
  2. You do not need to download it by hand. TokForge fetches it the first time it needs it: when you attach a document to a chat, or once you allow automatic helper downloads. You can also get or repair it in Settings > Speed & engine > Models & Modules, where it is listed as BGE-small MNN Embedder.
  3. TokForge turns your document chunks and memory facts into vectors with it, then finds the passages and memories that match your message. Everything runs on the phone.

Collections: TokForge Voice and Helper Models.

Files

FileSizeWhat it is
bge_dynamic_int8.tflite35.3 MBTensorFlow Lite, INT8 weights, 256-token inputs
bge_dynamic_int8_seq128.tflite34.9 MBTensorFlow Lite, INT8 weights, 128-token inputs
bge_dynamic_int8_seq32.tflite34.6 MBTensorFlow Lite, INT8 weights, 32-token inputs
bge_dynamic_int8_seq64.tflite34.7 MBTensorFlow Lite, INT8 weights, 64-token inputs
config.json578 BBundle settings (pooling, embedding size, inputs and outputs)
encoder.mnn66.8 MBMNN encoder, fp16 (fallback path)
hf_config.json743 BBERT model config from the source model
special_tokens_map.json125 BSpecial tokens
tokenizer.json711 KBTokenizer
tokenizer_config.json366 BTokenizer settings
vocab.txt232 KBWordPiece vocabulary (used by both paths)

What TokForge uses

  • Default: the four bge_dynamic_int8*.tflite files with vocab.txt, on the TensorFlow Lite (LiteRT) XNNPACK CPU path. Each file is fixed to one input length (32, 64, 128 or 256 tokens; bge_dynamic_int8.tflite is the 256-token one), and TokForge picks the smallest one that fits the text. These graphs take input_ids and attention_mask and return the 384-dim sentence vector with CLS pooling and L2 normalization built in.
  • Fallback: encoder.mnn (fp16) with vocab.txt, on the MNN CPU backend, when the TFLite files or runtime are not available.
  • Both paths produce vectors in the same embedding space, so stored vectors stay valid whichever path made them.

About the model

MNN-format conversion of BAAI/bge-small-en-v1.5 for use in on-device inference via the MNN runtime (Android / Linux / iOS). Produced for TokForge to consolidate embedding + LLM inference on a single runtime and remove a GGUF/llama.cpp dependency for RAG and memory/reflection embeddings.

  • Base model: BAAI/bge-small-en-v1.5 (BERT encoder, 33M params)
  • Architecture: 12-layer BERT, hidden=384, 12 attention heads, intermediate=1536
  • Pooling: CLS token (token 0 of last_hidden_state), then L2-normalize
  • Max sequence length: 512
  • Embedding dim: 384
  • Precision: fp16 weights (encoder.mnn); INT8 weights with fp32 activations (.tflite files)
  • File size: 66.8 MB (encoder.mnn), about 35 MB per .tflite file

Inputs and outputs (encoder.mnn)

Input tensors (int32):

  • input_ids: shape (batch, seq)
  • attention_mask: shape (batch, seq)
  • token_type_ids: shape (batch, seq), all zeros for single-text embedding

Output tensor (fp32 on CPU):

  • last_hidden_state: shape (batch, seq, 384): Caffe/NCHW layout (use Tensor_DimensionType_Caffe when copying to host).

To get a sentence embedding: take position 0 (CLS token), then L2 normalize.

Quality check against the GGUF version

Synthetic retrieval benchmark over 300 chunks + 20 gold queries drawn from a private technical documentation corpus. GGUF baseline ran via llama.cpp llama-embedding against the standard BAAI bge-small-en-v1.5.Q*_K_M.gguf. Both models use CLS pooling + L2 normalization and the BGE query prefix "Represent this sentence for searching relevant passages: ".

MetricGGUF (baseline)MNN fp16Ratio
Recall@170.0%70.0%100%
Recall@375.0%75.0%100%
Recall@585.0%85.0%100%
Recall@1095.0%95.0%100%
MRR0.76590.765399.9%
Mean gold-chunk cos sim0.76460.7654n/a

Cross-model per-chunk cosine similarity: mean 0.9962, 5th-percentile 0.9948. The MNN fp16 conversion produces essentially the same embedding subspace as the PyTorch/ONNX reference (cosine 1.0000 vs sentence-transformers on sanity checks). Retrieval scores did not drop measurably.

Python usage (reference)

import MNN, numpy as np
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("darkmaniac7/bge-small-en-MNN")
interp = MNN.Interpreter("encoder.mnn")
sess = interp.createSession({"backend": "CPU", "numThread": 4})
in_ids  = interp.getSessionInput(sess, "input_ids")
in_mask = interp.getSessionInput(sess, "attention_mask")
in_tok  = interp.getSessionInput(sess, "token_type_ids")
out_t   = interp.getSessionOutput(sess, "last_hidden_state")

def embed(text):
    enc = tok(text, padding=False, truncation=True, max_length=512, return_tensors="np")
    seq = enc["input_ids"].shape[1]
    for t, arr in ((in_ids, enc["input_ids"]), (in_mask, enc["attention_mask"]), (in_tok, enc["token_type_ids"])):
        interp.resizeTensor(t, (1, seq))
    interp.resizeSession(sess)
    for t, arr in ((in_ids, enc["input_ids"]), (in_mask, enc["attention_mask"]), (in_tok, enc["token_type_ids"])):
        tmp = MNN.Tensor((1, seq), MNN.Halide_Type_Int,
                         arr.astype(np.int32), MNN.Tensor_DimensionType_Tensorflow)
        t.copyFrom(tmp)
    interp.runSession(sess)
    shape = out_t.getShape()
    host = MNN.Tensor(shape, MNN.Halide_Type_Float,
                      np.zeros(tuple(shape), dtype=np.float32),
                      MNN.Tensor_DimensionType_Caffe)
    out_t.copyToHostTensor(host)
    arr = np.array(host.getData(), dtype=np.float32).reshape(tuple(shape))
    cls = arr[0, 0, :]
    return cls / (np.linalg.norm(cls) + 1e-12)

# For asymmetric retrieval, prefix queries per BGE convention:
qvec = embed("Represent this sentence for searching relevant passages: " + "your query here")
pvec = embed("passage text here")
score = float(np.dot(qvec, pvec))  # cosine (both are unit-norm)

How it was made

  1. Downloaded BAAI/bge-small-en-v1.5 from Hugging Face: the repo ships an ONNX export (onnx/model.onnx, opset 11) exported from PyTorch.
  2. Ran MNNConvert -f ONNX --fp16 against that ONNX, which fused 25 LayerNorms and produced encoder.mnn.
  3. Copied tokenizer files (tokenizer.json, tokenizer_config.json, special_tokens_map.json, vocab.txt) from the source repo.

Reproduce:

MNNConvert -f ONNX \
    --modelFile BAAI/bge-small-en-v1.5/onnx/model.onnx \
    --MNNModel encoder.mnn \
    --fp16 --bizCode bge-small

The bge_dynamic_int8*.tflite files are dynamic-range INT8 TensorFlow Lite exports of the same BAAI model (INT8 weights, fp32 activations), one per fixed input length.

Limitations

  • English only
  • The .tflite files take fixed input lengths (32, 64, 128 or 256 tokens); longer text needs encoder.mnn (up to 512) or splitting
  • TokForge runs the .tflite files on the CPU (XNNPACK) only, not with the GPU or NNAPI delegates

License

bge-small-en-v1.5 is released by BAAI under the MIT license.

Credits

  • bge-small-en-v1.5 by BAAI (Hugging Face). Used under the MIT license. Source weights are Copyright 2023 Beijing Academy of Artificial Intelligence, MIT-licensed.
  • The bge_dynamic_int8*.tflite files are TensorFlow Lite INT8 exports of the same BAAI model.
  • Converted from the source ONNX graph with MNNConvert from MNN by Alibaba (Apache-2.0).

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · mnn

Нельзя запустить

Библиотека «mnn» рантаймом не поддерживается.

Ревизия весов
3b0187c

0 моделей