Run this model with HF Jobs
Run Zenbu/embeddinggemma-2-text-lid-probe on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Zenbu/embeddinggemma-2-text-lid-probe. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Zenbu/embeddinggemma-2-text-lid-probe on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Zenbu/embeddinggemma-2-text-lid-probe with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use Zenbu/embeddinggemma-2-text-lid-probe with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download Zenbu/embeddinggemma-2-text-lid-probe --local-dir embeddinggemma-2-text-lid-probe
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
EmbeddingGemma 2 Written-Language Classifier Probe (v1)
A 41 KB linear written-language classifier probe (10,260 float32 parameters in W_eff and b_eff) on top of Layer 2 (language_model.layers[2]) of Google's frozen google/embeddinggemma-2, with code and noise fallback classes.
Use it to detect written language, skip source code, logs, URLs, or numeric tables, or filter non-English chunks before indexing and reranking. You can stop after Layer 2 (~158 MB RAM in 8-bit MLX, skipping layers 3 to 23) or read Layer 2 during a full embedding pass at near-zero extra cost.
This bundle also carries an optional 14 KB experimental content-role classifier documented at the bottom. You can ignore or drop it if you only need language detection, or if the code/noise fallback is sufficient for your use-case.
Put simply, this is a very light addon to EmbeddingGemma2 that classifies text into languages. It can run at the same time as vector generation. It can also tell if text is part of a category that language does not apply to.
Why does this exist?
EmbeddingGemma 2 maps text from different languages into one shared 768-dimensional semantic space, so the contents of the final vectors do not tell you which language a text is written in.
Early transformer layers still keep that language signal. In our 24-layer sweep (1,573 test texts), Layer 2 (512-d) reached 98.09% language accuracy and 100.0% on parallel translations. By Layer 8, accuracy on parallel translations fell to 77.45%, and final text_embeds dropped to 86.27% overall (66.4% on unseen languages) as cross-lingual topic matching climbed from 0.457 to 0.608.
Putting a 41 KB linear layer on Layer 2 recovers the written language during embedding, or lets you stop after 3 layers (10.17 ms/text vs 109.27 ms/text across all 24 layers on an M1 Mac) without loading a separate language-ID model.
Classes
There are 20 outputs in fixed order:
- 17 written languages:
en,pt,es,fr,de,it,nl,pl,ru,uk,tr,ar,hi,zh,ja,ko,vi other_lang: catch-all bucket for other written languages, trained on 33Davlan/sib200and 34google/fleurslanguages (8 held-out languages plus 25 unseen OOD languages were kept out of training to test generalization)code: source code, configuration files, and markup across 16 permissive formats frombigcode/commitpackft, plus short comment-free snippetsnoise: generated logs, stack traces, CSV/TSV/pipe tables, base64, JWTs, SHA-256 hex, UUIDs, and raw URLs
Texts up to 80 body tokens are pooled in one window. Longer texts use overlapping 64-token windows with a 32-token hop.
Scope and known failure modes
What holds up in testing:
- Articles, markdown docs, source code, configs, logs, and tables (
99.73%held-out accuracy,0.9978Macro-F1,48/48on a local repo scan, and12/12exact language sets on 50/50 and 80/20 bilingual documents). - Short commands and tweets (
97.11%accuracy across 17 target splits inmteb/massive_scenariowith99.66%precision whenlanguage_confidentis true, and96.67%across the 7 non-Romanized languages incardiffnlptweets with99.01%confident precision). - Catching languages outside the 17-language list as
other_lang(419/420across 14 unseenDavlan/sib200languages with0confident false positives, and423/440across 11 unseenmassive_scenariolanguages). - Abstaining when uncertain:
language_confidentrequires at least 5 body tokens and a length-adjusted score>= 0.65on a named language.
What does not work reliably:
- Strings under 5 body tokens (
language_confidentalways returns false belowMIN_PROSE_TOKENS = 5). - Romanized text and mixed scripts: Romanized Hindi (
Hinglish) and Arabic tweets written with Persian letters (گ,ی) are often misread asenorother_lang. - Short commands mostly made of English names: inputs like
'olly death metal agora'(4tokens, 3 English words) can predicten, thoughlanguage_confidentusually stays false. - Closely related languages on short strings: Afrikaans shares enough vocabulary with Dutch that
6/40short Afrikaans commands inmassive_scenariopredictednl. - Replies buried in
@mentionsand links: with default settings, long runs ofRT @user:handles and URLs outweigh a 4- or 5-word reply (28.25%accuracy on that stress test, vs97.25%if you opt in with--mask-social). - Image-only or audio-only inputs: scanned PDF pages passed only as
<|image|>have no text tokens for this probe to read. Run OCR first and classify the extracted text.
Inference details
Four details matter if you reimplement inference outside probe_inference.py (standalone MLX 8-bit and egemma2-engine match 6/6 with max_prob_delta = 0.000000):
- Normalize text to Unicode
NFC(unicodedata.normalize("NFC", text)) before tokenizing. DecomposedNFDaccents (common in Vietnamese and macOS paths) split into extra tokens and hurt accuracy;NFCfixes this without changing ASCII or code. - Exclude special tokens (
<pad>,<bos>,<eos>, media tokens), standalone whitespace tokens right next to media tokens, and anytask: ... | query:ortitle: ... | text:prefix. Count prefix tokens onprefix.rstrip()so a trailing space does not shift the start of the body by one token. - Scale down short-text confidence before checking the
0.65threshold: divide logits bysqrt(1 + 6.0 / max(n, 1.0)), wherenis the body token count. Because Layer 2 vectors are L2-normalized before the linear layer, 3- or 4-token strings score artificially high without this adjustment. - Leave input tokens untouched by default (
mask_social_wrappers=False). Only pass--mask-social(CLI) ormask_social_wrappers=True(Python) if you are classifying tweets or chat exports whereRT @handle:,@mentions, URLs, and#hashtagsdrown out short replies (applied only when at least 6 letters and 3 body tokens remain).
Interleaved text + image / audio inputs
Layers 0 through 4 of EmbeddingGemma 2 use bidirectional sliding-window attention (sliding_window = 512), so text tokens within 512 positions of <|image|> or <|audio|> attend to those media tokens before Layer 2. You still do not need a second text-only pass for normal interleaved inputs (>= 5 tokens): only the token right next to <|image|> or <|audio|> shifts much, and across 20 to 82 token prose and code the probabilities move by less than 0.01 (0 label or confidence changes in our tests).
If you read Layer 2 during your own interleaved forward pass (such as PDF pages paired with page images, or captioned audio and photos), pass both the model's media token IDs (image_token_id, video_token_id, audio_token_id, boi_token_id, eoi_token_id, boa_token_id, eoa_token_id / eoa_token_index) and find_whitespace_token_ids(...) to build_body_token_mask(...) in probe_inference.py. Prompts like f"{text} <|image|>" or f"{text} <|audio|>" tokenize with a standalone space token right before the media tag; leaving that space unmasked adds 1 to token_count and lets nearby audio tokens skew 3- or 4-token captions.
Usage
Standalone script (probe_inference.py + model.safetensors)
Requires numpy and safetensors, plus either mlx / mlx-vlm / transformers (Apple Silicon) or torch / transformers (PyTorch/CUDA).
python probe_inference.py "Olá, tudo bem com você hoje?" --backend mlx --json
python probe_inference.py --file README.md --file app.py --backend pytorch --json
from probe_inference import TextProbeHead, classify_pytorch
head = TextProbeHead.load("model.safetensors")
results = classify_pytorch(["Este documento descreve a arquitetura do sistema."], head)
print(results[0]["label"], results[0]["language_confident"], results[0]["detected_languages"])
Direct linear head (safetensors)
W_eff and b_eff already fold in the training StandardScaler and calibrated temperature (T = 0.92951), so scoring an L2-normalized Layer 2 window vector feat_512 is one matmul:
from safetensors import safe_open
import numpy as np
with safe_open("model.safetensors", framework="numpy") as f:
W_eff = f.get_tensor("W_eff") # (20, 512) float32
b_eff = f.get_tensor("b_eff") # (20,) float32
thresholds = f.get_tensor("class_thresholds") # uniform 0.65
logits = feat_512 @ W_eff.T + b_eff
logits -= logits.max(axis=-1, keepdims=True)
probs = np.exp(logits) / np.exp(logits).sum(axis=-1, keepdims=True)
Evaluation summary
Held-out multi-domain split (n = 5,154, group-disjoint)
| Metric | Result | Notes |
|---|---|---|
| Overall accuracy / Macro-F1 | 99.73% / 0.9978 |
95% CI [0.9967, 0.9990], ECE = 0.0016 |
Unseen other_lang (n = 570, 8 langs) |
99.65% (568/570) |
100% on 15 sib200/fleurs slices; 0.980 papluca/bg; 0.975 cat_Latn |
task: / title: prefix invariance |
99.63% |
Macro-F1 0.9969 |
en PR-AUC (n = 260) |
0.9994 |
pt F1 = 0.9982 (n = 270, including pt_bosque pt-PT) |
code (n = 769) / noise (n = 225) |
0.9954 F1 / 0.9978 F1 |
Synthetic logs, tabular, noise 100%; permissive commitpackft 93.3% to 100% |
Out-of-distribution (OOD) stress suites (MLX 8-bit)
| Suite | Result | Confident Precision / FPs |
|---|---|---|
mteb/massive_scenario targets (n = 658, 16 + zh-TW) |
97.11% acc |
99.66% (2/582 conf FPs) |
massive_pt[:300] / massive_tr[:300] |
98.00% / 98.00% acc |
98.91% / 100.0% |
cardiffnlp tweets (n = 480 / n = 420 ex-hi) |
90.83% / 96.67% acc |
96.80% / 99.01% |
RT @user: / URL prefixes (n = 400, default / --mask-social) |
28.25% / 97.25% acc |
39.62% / 98.42% (opt-in 0 code/noise FPs) |
Diacritics stripped / ALL CAPS / Punctuation stripped (400 each) |
97.50% / 96.50% / 98.25% |
98.39% / 98.41% / 98.93% |
8% OCR corruption (n = 400) |
92.25% acc |
97.53% |
Davlan/sib200 14 unseen other_lang (n = 420) |
99.76% (419/420) |
0/420 (0.00%) confident FPs |
massive_scenario 11 unseen other_lang (n = 440) |
96.14% (423/440) |
7/440 (1.59%) confident FPs |
Bilingual windows (12 docs) / Repo scan (48 files) |
12/12 exact / 48/48 LID |
0 EN FPs / 0 mismatches |
Detailed breakdowns live in evals/TEXT_PROBE_V1_RELEASE_EVAL.md, evals/TEXT_PROBE_V1_OOD_EVAL.md, and text_lid_report_v1.json.
Training data and licenses
All 18,377 dev and 5,154 test records come from commercially permissive sources, split with 5-fold StratifiedGroupKFold (selected_C = 0.25, T = 0.92951). Train-only augmentations (kept in the same group as their source text) cover short crops, markdown formatting, task:/title: prefixes, ALL CAPS, stripped accents, and 5% synthetic OCR typos.
| Source | Used for | License / Notes |
|---|---|---|
Davlan/sib200 |
17 languages + other_lang |
CC BY-SA 4.0 (glg_Latn excluded from other_lang; yue_Hant excluded from other_lang eval) |
google/fleurs |
17 languages + other_lang |
CC BY 4.0 TSV transcripts (gl_es, az_az excluded from other_lang) |
papluca/language-identification |
Web and review text | Held-out bg used as unseen other_lang |
commul/universal_dependencies (pt_bosque CP) |
European Portuguese (pt-PT) |
CC BY-SA 4.0, grouped by article (150 train / 40 val / 60 test) |
bigcode/commitpackft |
Code, config, markup, EN markdown | Filtered to MIT / BSD / Apache-2.0 / ISC / Unlicense / CC0-1.0 |
Synthetic logs, tabular, noise |
Generated logs, tables, and random strings | Public Domain (generated) |
Optional extra: content-role head (experimental)
This repo also includes an optional 14 KB experimental head (3,591 float32 parameters stored as role_W_eff, role_b_eff, and role_class_thresholds in model.safetensors, plus text_role_probe_v1.npz and text_role_report_v1.json).
It is a small optional extra for sorting local files, not a general document parser:
- 7 coarse buckets:
prose,source_code,config,markup,logs,tabular,noise - Trained on permissive code, config, and markup files from
bigcode/commitpackftplus the generated logs, tables, and random strings listed above (not real production logs, real spreadsheets, or PDF/HTML exports) - Held-out split (
n = 5,154,T = 1.15032):99.50%accuracy,0.9844Macro-F1 ([0.9770, 0.9902]),ECE = 0.0017(not tested on a separate external OOD benchmark) - Skipping it: load only
W_eff,b_eff, andclass_thresholdsfrommodel.safetensors(or loadtext_lid_probe_v1.npz). Whenrole_W_effis absent,probe_inference.pyomitscontent_rolefrom its output.
- Downloads last month
- 59
Quantized
Model tree for Zenbu/embeddinggemma-2-text-lid-probe
Base model
google/embeddinggemma-2