Text Classification
Transformers
Safetensors
English
mimelens
image-feature-extraction
file-type-detection
mime-classification
binary-content
binary-analysis
position-agnostic
libmagic
forensics
packet-inspection
bpe
byte-pair-encoding
custom_code
Eval Results (legacy)
Instructions to use mjbommar/mimelens-001-tiny-bpe-64k-s2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use mjbommar/mimelens-001-tiny-bpe-64k-s2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="mjbommar/mimelens-001-tiny-bpe-64k-s2", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("mjbommar/mimelens-001-tiny-bpe-64k-s2", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
mimelens-001 cell: tiny/bpe-64k/s2
Browse files- README.md +100 -57
- config.json +1 -1
- configuration_mimelens.py +5 -4
- modeling_mimelens.py +101 -1
- tokenizer.json +0 -0
- tokenizer_config.json +54 -0
README.md
CHANGED
|
@@ -1,17 +1,22 @@
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
library_name: transformers
|
|
|
|
|
|
|
| 4 |
tags:
|
| 5 |
- file-type-detection
|
| 6 |
- mime-classification
|
| 7 |
- binary-content
|
|
|
|
| 8 |
- position-agnostic
|
| 9 |
- libmagic
|
|
|
|
|
|
|
| 10 |
- bpe
|
|
|
|
| 11 |
- mimelens
|
| 12 |
-
language: en
|
| 13 |
base_model: mjbommar/binary-tokenizer-001-64k
|
| 14 |
-
pipeline_tag:
|
| 15 |
model-index:
|
| 16 |
- name: mimelens-001-tiny-bpe-64k-s2
|
| 17 |
results:
|
|
@@ -19,8 +24,8 @@ model-index:
|
|
| 19 |
type: feature-extraction
|
| 20 |
name: MIME-125 classification (libmagic 125-class taxonomy)
|
| 21 |
dataset:
|
| 22 |
-
name: magic-
|
| 23 |
-
type:
|
| 24 |
metrics:
|
| 25 |
- name: top-1 accuracy
|
| 26 |
type: accuracy
|
|
@@ -33,95 +38,133 @@ model-index:
|
|
| 33 |
value: 0.6754
|
| 34 |
source:
|
| 35 |
name: "MimeLens paper (Bommarito 2026), Appendix A"
|
| 36 |
-
url: https://github.com/mjbommar/
|
| 37 |
---
|
| 38 |
|
| 39 |
-
#
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
A single 4 KB byte buffer in (of which the first 1,022 body tokens are consumed), one of libmagic's 125 MIME labels out, regardless of where in a source file the buffer came from.
|
| 44 |
|
| 45 |
-
For the family overview, decision tree (which cell to load?), and full cube results, see [`mjbommar/mimelens-001`](https://huggingface.co/mjbommar/mimelens-001).
|
| 46 |
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
```python
|
| 50 |
import torch
|
| 51 |
-
from transformers import AutoModel
|
| 52 |
-
from tokenizers import Tokenizer
|
| 53 |
|
| 54 |
-
repo
|
| 55 |
model = AutoModel.from_pretrained(repo, trust_remote_code=True).eval()
|
| 56 |
-
tok
|
| 57 |
-
cfg = model.config
|
| 58 |
|
| 59 |
-
# BPE cell: encode 4 KB of raw bytes via the published binary-BPE tokenizer.
|
| 60 |
window = open("path/to/file", "rb").read(4096)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
input_ids = torch.tensor([ids])
|
| 64 |
-
|
| 65 |
with torch.no_grad():
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
embedding = out.pooler_output # (1, 256) mean-pooled body-token embedding
|
| 69 |
-
# Downstream: a frozen LR probe, a kNN over a labeled gallery, or fine-tune a classification head.
|
| 70 |
-
# See the paper for the standard evaluation protocol.
|
| 71 |
```
|
| 72 |
|
| 73 |
-
|
| 74 |
|
| 75 |
-
- **Family**: [MimeLens-001](https://huggingface.co/mjbommar/mimelens-001) — 28 pretrained checkpoints across 3 sizes × 4 vocabularies × 2 seeds, plus one matched-tokens-seen ablation.
|
| 76 |
-
- **Size**: `tiny` — 3.15 M backbone params, 4 layers, hidden 256, 4 attention heads, head dim 64.
|
| 77 |
-
- **Input pipeline**: `bpe-64k` (65{,}536-entry binary BPE tokenizer (from binary-tokenizer-001-64k), ~2.09 bytes per token on the corpus.).
|
| 78 |
-
- **Seed**: `2` (1 of 2 for this (size, vocab) combination).
|
| 79 |
-
- **Pretraining**: 22,888 gradient updates, MLM-only, 30% mask ratio, 1024-token windows sampled uniformly at random across files and 64 KB fragments. AdamW + cosine LR (peak 5e-4, 2,000-step warmup, 10% floor), bf16 mixed precision, single RTX 4060 Ti.
|
| 80 |
-
- **License**: MIT.
|
| 81 |
|
| 82 |
-
|
| 83 |
|
| 84 |
-
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
## Recommended deployment regimes
|
| 93 |
|
| 94 |
See the family hub README ([`mjbommar/mimelens-001`](https://huggingface.co/mjbommar/mimelens-001)) for the regime decision tree.
|
| 95 |
|
|
|
|
|
|
|
| 96 |
## Training
|
| 97 |
|
| 98 |
-
This cell is one point of the
|
| 99 |
|
| 100 |
-
- **33 GB stratified multi-source binary
|
| 101 |
-
- **Position-arbitrary windowing**: 1024-token windows sampled uniformly at random across files and 64 KB fragments
|
| 102 |
-
- **
|
| 103 |
-
- **
|
| 104 |
-
- **
|
|
|
|
| 105 |
|
| 106 |
-
|
| 107 |
|
| 108 |
-
|
|
|
|
|
|
|
| 109 |
- The training corpus is one 33 GB stratified multi-source binary sample. Results may not transfer to substantially different corpora.
|
| 110 |
-
- All numbers are computed on data
|
| 111 |
-
- CPU latency at the `medium` size is ~
|
| 112 |
-
- End-to-end fine-tuning on the production label distribution may shift these numbers and should be evaluated before deployment. The frozen-probe numbers
|
|
|
|
|
|
|
| 113 |
|
| 114 |
## Citation
|
| 115 |
|
| 116 |
```bibtex
|
| 117 |
@misc{bommarito2026mimelens,
|
| 118 |
-
title = {MimeLens:
|
| 119 |
author = {Bommarito II, Michael J.},
|
| 120 |
year = {2026},
|
| 121 |
-
note = {https://github.com/mjbommar/
|
| 122 |
}
|
| 123 |
-
```
|
| 124 |
-
|
| 125 |
-
## Acknowledgments
|
| 126 |
-
|
| 127 |
-
Thanks to the [magic-bpe](https://github.com/mjbommar/magic-bpe) project and the [binary-tokenizer-001](https://huggingface.co/mjbommar/binary-tokenizer-001-64k) family for the labelled corpus and BPE tokenizers this work builds on, and to the [Magika](https://github.com/google/magika) team for releasing a public package that made the §3 calibration possible.
|
|
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
library_name: transformers
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
tags:
|
| 7 |
- file-type-detection
|
| 8 |
- mime-classification
|
| 9 |
- binary-content
|
| 10 |
+
- binary-analysis
|
| 11 |
- position-agnostic
|
| 12 |
- libmagic
|
| 13 |
+
- forensics
|
| 14 |
+
- packet-inspection
|
| 15 |
- bpe
|
| 16 |
+
- byte-pair-encoding
|
| 17 |
- mimelens
|
|
|
|
| 18 |
base_model: mjbommar/binary-tokenizer-001-64k
|
| 19 |
+
pipeline_tag: text-classification
|
| 20 |
model-index:
|
| 21 |
- name: mimelens-001-tiny-bpe-64k-s2
|
| 22 |
results:
|
|
|
|
| 24 |
type: feature-extraction
|
| 25 |
name: MIME-125 classification (libmagic 125-class taxonomy)
|
| 26 |
dataset:
|
| 27 |
+
name: magic-frags (4 KB head of 64 KB random chunks, n=4,096)
|
| 28 |
+
type: custom
|
| 29 |
metrics:
|
| 30 |
- name: top-1 accuracy
|
| 31 |
type: accuracy
|
|
|
|
| 38 |
value: 0.6754
|
| 39 |
source:
|
| 40 |
name: "MimeLens paper (Bommarito 2026), Appendix A"
|
| 41 |
+
url: https://github.com/mjbommar/mimelens-training
|
| 42 |
---
|
| 43 |
|
| 44 |
+
# mimelens-001-tiny-bpe-64k-s2
|
| 45 |
|
| 46 |
+
A 3.15M-backbone-parameter BERT-style encoder for position-agnostic file-content-type detection from binary data. It reads a byte window taken from *any* offset in a file (the first ~1{,}022 tokens of whatever you pass) and produces a 256-dimensional embedding that classifiers map to one of [libmagic](https://github.com/file/file)'s 125 MIME labels. Designed for inputs where you only have a chunk: a forensic-carved fragment, a random disk-block read, a streaming HTTP upload, a single network packet payload.
|
| 47 |
+
|
| 48 |
+
- **🔗 Model**: [`mjbommar/mimelens-001-tiny-bpe-64k-s2`](https://huggingface.co/mjbommar/mimelens-001-tiny-bpe-64k-s2)
|
| 49 |
+
- **👥 Family**: [`mjbommar/mimelens-001`](https://huggingface.co/mjbommar/mimelens-001) (36 released cells: 28 parent + 8 short-sequence)
|
| 50 |
+
- **🔤 Tokenizer**: [`mjbommar/binary-tokenizer-001-64k`](https://huggingface.co/mjbommar/binary-tokenizer-001-64k)
|
| 51 |
+
- **📄 Paper**: *MimeLens: Position-Agnostic Content-Type Detection for Binary Fragments* (Bommarito 2026)
|
| 52 |
+
- **💻 Training code**: [`mjbommar/mimelens-training`](https://github.com/mjbommar/mimelens-training)
|
| 53 |
+
- **📊 Pretraining corpus**: [`mjbommar/binary-30k-tokenized`](https://huggingface.co/datasets/mjbommar/binary-30k-tokenized) plus magic-corpus extracts, packed binaries, a [`glaurung`](https://github.com/mjbommar/glaurung)-sourced binary corpus, and Windows drivers (33 GB stratified; the full corpus is not redistributable)
|
| 54 |
+
|
| 55 |
+
---
|
| 56 |
+
|
| 57 |
+
## What MimeLens does
|
| 58 |
+
|
| 59 |
+
MimeLens classifies file content type from a byte window taken at any offset, not just the header of a complete file.
|
| 60 |
+
|
| 61 |
+
Existing tools assume whole-file access at a known offset:
|
| 62 |
+
|
| 63 |
+
- [`libmagic`](https://github.com/file/file) and [Apache Tika](https://tika.apache.org/) match handcrafted magic-byte signatures, almost always anchored at the file head.
|
| 64 |
+
- [Magika](https://github.com/google/magika) (Google) is a small (~1 M-parameter) feedforward network over three 512-byte windows (head, middle, tail) of a known-bounded file.
|
| 65 |
+
- TrID, PRONOM/Siegfried/DROID similarly require a complete file.
|
| 66 |
+
|
| 67 |
+
These break down on a fragment. MimeLens is pretrained MLM-only on 1024-token windows sampled *uniformly at random* across files and 64 KB fragments, with no privileged head-of-file position. One checkpoint handles streaming, partial-arrival, mid-file, packet-payload, and forensic-carved inputs uniformly. The trade-off is CPU latency (roughly two orders of magnitude slower than Magika at the medium size; hardware-dependent) in exchange for libmagic's 125-class taxonomy plus position arbitrariness.
|
| 68 |
+
|
| 69 |
+
The family ships 28 parent cells (3 sizes × 4 vocabs × 2-3 seeds at seq\_len=1024) plus an 8-cell short-sequence extension (medium tier × 4 vocabs × 2 seeds at seq\_len=256). This README documents one of them.
|
| 70 |
+
|
| 71 |
+
> **Short-sequence sibling available.** If your inputs are sub-KB (DNS payloads, sub-MTU packets, small forensic fragments), use `mjbommar/mimelens-001-tiny-bpe-64k-s2-seq256` instead. Same architecture, 4× shorter context, ~5× lower CPU latency, BPE-cell accuracy ties or beats this cell on the magic-files probe-fit. See paper Appendix B.5.
|
| 72 |
|
|
|
|
| 73 |
|
|
|
|
| 74 |
|
| 75 |
+
---
|
| 76 |
+
|
| 77 |
+
## Overview
|
| 78 |
+
|
| 79 |
+
- **This cell**: `tiny` tier, `bpe-64k` input pipeline, seed `2`
|
| 80 |
+
- **Backbone**: 3.15M parameters (4 layers, hidden 256, 4 attention heads, head dim 64, RoPE, RMSNorm, no biases, no dropout)
|
| 81 |
+
- **Input vocabulary**: `bpe-64k`. 65,536-entry binary BPE tokenizer (binary-tokenizer-001-64k), ~2.09 bytes/token. Reads ~2,134 bytes of the 4 KB buffer.
|
| 82 |
+
- **Output**: 256-dim mean-pooled body-token embedding
|
| 83 |
+
- **Label space**: [libmagic](https://github.com/file/file) 125-class MIME taxonomy (full list in paper Appendix)
|
| 84 |
+
- **Pretraining**: MLM-only, 30% mask ratio, 33 GB stratified multi-source binary corpus, 22,888 gradient updates, single RTX 4060 Ti, ~2.7 h wall-clock
|
| 85 |
+
- **License**: MIT
|
| 86 |
+
|
| 87 |
+
## Headline benchmarks (this cell)
|
| 88 |
+
|
| 89 |
+
| Benchmark | Value |
|
| 90 |
+
|---|---|
|
| 91 |
+
| MIME-125 top-1 (magic-frags, 4 KB head, n=4,096) | **0.732** |
|
| 92 |
+
| MIME-125 macro-F1 (magic-frags, 4 KB head) | 0.609 |
|
| 93 |
+
| kNN R@1 (magic-frags, 3,147-file gallery / 949 queries) | 0.675 |
|
| 94 |
+
|
| 95 |
+
Full evaluation (within-cube bootstrap CIs, adversarial sweep, calibration, real-network curves, disk-block matrix, baselines against libmagic 5.46 and TrID 2.24) is in the [paper](https://github.com/mjbommar/mimelens-training).
|
| 96 |
+
|
| 97 |
+
---
|
| 98 |
+
|
| 99 |
+
## Quick start
|
| 100 |
+
|
| 101 |
+
This cell publishes the encoder only (no classifier head baked in). Use it to extract embeddings, then fit a probe, run kNN over a labelled gallery, or fine-tune a head:
|
| 102 |
|
| 103 |
```python
|
| 104 |
import torch
|
| 105 |
+
from transformers import AutoModel, AutoTokenizer
|
|
|
|
| 106 |
|
| 107 |
+
repo = "mjbommar/mimelens-001-tiny-bpe-64k-s2"
|
| 108 |
model = AutoModel.from_pretrained(repo, trust_remote_code=True).eval()
|
| 109 |
+
tok = AutoTokenizer.from_pretrained(repo)
|
|
|
|
| 110 |
|
|
|
|
| 111 |
window = open("path/to/file", "rb").read(4096)
|
| 112 |
+
inputs = tok(window.decode("latin-1"), max_length=1024, truncation=True,
|
| 113 |
+
padding="max_length", return_tensors="pt")
|
|
|
|
|
|
|
| 114 |
with torch.no_grad():
|
| 115 |
+
embedding = model(**inputs).pooler_output # (1, 256)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
```
|
| 117 |
|
| 118 |
+
The pre-fit LR probe weights for this cell are not bundled here. The deployed cells and per-size winners (e.g. `mimelens-001-medium-bpe-16k-s1`) ship a baked classifier head for a one-line `pipeline()` path.
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
---
|
| 122 |
|
| 123 |
+
## Choosing a window
|
| 124 |
|
| 125 |
+
The model reads the first ~1{,}022 tokens of whatever you pass — a prefix of the buffer (for this BPE cell, whatever tokenizes to ~1{,}022 tokens, typically the first ~1.5--2.5 KB), not the whole window.
|
| 126 |
+
|
| 127 |
+
- **Magic-byte / compressed types** (PNG, ZIP, GZIP, JPEG): a **short head window (256 B--1 KB) classifies better than 4 KB**. A long high-entropy body dilutes the header signal within the fixed token budget, and the model returns `application/octet-stream` on a mostly-opaque window — correct behaviour for genuinely high-entropy input, not a bug.
|
| 128 |
+
- **Fragments / packets**: you cannot choose the offset, so pass what you have. This is the regime MimeLens is built for.
|
| 129 |
+
|
| 130 |
+
---
|
| 131 |
|
| 132 |
## Recommended deployment regimes
|
| 133 |
|
| 134 |
See the family hub README ([`mjbommar/mimelens-001`](https://huggingface.co/mjbommar/mimelens-001)) for the regime decision tree.
|
| 135 |
|
| 136 |
+
---
|
| 137 |
+
|
| 138 |
## Training
|
| 139 |
|
| 140 |
+
This cell is one point of the 3 × 4 × 2 factorial cube described in the paper.
|
| 141 |
|
| 142 |
+
- **Corpus** (33 GB, stratified multi-source): [`binary-30k`](https://huggingface.co/datasets/mjbommar/binary-30k-tokenized) (assorted ELF/PE/Mach-O), magic-frags (random 64 KB chunks across libmagic's full corpus), assorted packed/raw binaries, a [`glaurung`](https://github.com/mjbommar/glaurung)-sourced binary corpus, Windows drivers.
|
| 143 |
+
- **Position-arbitrary windowing**: 1024-token windows sampled uniformly at random across files and 64 KB fragments. **No privileged "head of file" position.** This is the design choice that makes MimeLens work on streaming / partial / random-offset inputs.
|
| 144 |
+
- **Objective**: MLM with 30% mask ratio (BERT replacement schedule: 80% `[MASK]`, 10% random, 10% original); tied input/output embeddings.
|
| 145 |
+
- **Pooling**: mean-pool over body tokens for downstream tasks. The BERT-style `cls_pool` linear projection is *not* used: under MLM-only training it receives no gradient and remains byte-identical to its random initialisation across all 28 cube cells (paper §3.4 verifies this; left in the saved weights for architectural completeness only).
|
| 146 |
+
- **Optimisation**: AdamW + cosine LR (peak 5e-4, 2,000-step warmup, 10% floor), bf16 mixed precision, gradient clipping at $\|g\|_2 \leq 1$, effective batch 128 at sequence length 1024, 22,888 gradient updates.
|
| 147 |
+
- **Hardware**: single RTX 4060 Ti (16 GB), ~2.7 h wall-clock for this cell.
|
| 148 |
|
| 149 |
+
---
|
| 150 |
|
| 151 |
+
## Caveats
|
| 152 |
+
|
| 153 |
+
- This is one cell of a 28-cell parent cube (36 released cells including the 8-cell short-sequence extension). Within-cube comparisons in the paper carry bootstrap CIs at n=2 seeds; some marginal orderings (byte vs bpe-16k at the largest size) are within seed noise and should be read as ties.
|
| 154 |
- The training corpus is one 33 GB stratified multi-source binary sample. Results may not transfer to substantially different corpora.
|
| 155 |
+
- All numbers are computed on data labelled by a single pipeline (libmagic-pinned). Cross-validation against PRONOM, Siegfried, DROID, or IANA reference files is a documented limitation.
|
| 156 |
+
- CPU latency at the `medium` size is ~155× slower than Magika v1.1 on a desktop CPU (hardware-dependent). For sub-millisecond whole-file triage on broad categories, Magika is purpose-built and is the right tool. MimeLens occupies a different point on the deployment surface (position-arbitrary inputs + libmagic's 125-class taxonomy), not a drop-in replacement.
|
| 157 |
+
- End-to-end fine-tuning on the production label distribution may shift these numbers and should be evaluated before deployment. The frozen-probe numbers above are not claimed as a lower bound on fine-tuned performance.
|
| 158 |
+
|
| 159 |
+
---
|
| 160 |
|
| 161 |
## Citation
|
| 162 |
|
| 163 |
```bibtex
|
| 164 |
@misc{bommarito2026mimelens,
|
| 165 |
+
title = {MimeLens: Position-Agnostic Content-Type Detection for Binary Fragments},
|
| 166 |
author = {Bommarito II, Michael J.},
|
| 167 |
year = {2026},
|
| 168 |
+
note = {https://github.com/mjbommar/mimelens-training},
|
| 169 |
}
|
| 170 |
+
```
|
|
|
|
|
|
|
|
|
|
|
|
config.json
CHANGED
|
@@ -22,7 +22,7 @@
|
|
| 22 |
"cls_token_id": 4,
|
| 23 |
"sep_token_id": 5,
|
| 24 |
"mask_token_id": 6,
|
| 25 |
-
"byte_offset":
|
| 26 |
"cls_pool_dim": 256,
|
| 27 |
"mimelens_cell_id": "tiny/bpe-64k/s2",
|
| 28 |
"mimelens_vocab_pipeline": "bpe-64k",
|
|
|
|
| 22 |
"cls_token_id": 4,
|
| 23 |
"sep_token_id": 5,
|
| 24 |
"mask_token_id": 6,
|
| 25 |
+
"byte_offset": 7,
|
| 26 |
"cls_pool_dim": 256,
|
| 27 |
"mimelens_cell_id": "tiny/bpe-64k/s2",
|
| 28 |
"mimelens_vocab_pipeline": "bpe-64k",
|
configuration_mimelens.py
CHANGED
|
@@ -28,8 +28,9 @@ class MimeLensConfig(PretrainedConfig):
|
|
| 28 |
paper repository (https://github.com/mjbommar/binary-embedding-paper).
|
| 29 |
|
| 30 |
Args:
|
| 31 |
-
vocab_size: int — full vocabulary including
|
| 32 |
-
|
|
|
|
| 33 |
hidden_size: int — transformer model dimension (256 / 384 / 512 for
|
| 34 |
tiny / small / medium).
|
| 35 |
num_hidden_layers: int — layer count (4 / 8 / 12 for tiny / small /
|
|
@@ -46,7 +47,7 @@ class MimeLensConfig(PretrainedConfig):
|
|
| 46 |
pad_token_id / cls_token_id / sep_token_id / mask_token_id: int —
|
| 47 |
special-token indices, matching binary_embedding.constants.
|
| 48 |
byte_offset: int — for byte cells, ord(b)+byte_offset gives the token
|
| 49 |
-
id. Fixed at
|
| 50 |
cls_pool_dim: int — output dim of the cls_pool layer. Note: this layer
|
| 51 |
receives no gradient under MLM-only training (see paper §3.4); the
|
| 52 |
mean-pool over body tokens is the trained pooling, not cls_pool.
|
|
@@ -82,7 +83,7 @@ class MimeLensConfig(PretrainedConfig):
|
|
| 82 |
cls_token_id: int = 4,
|
| 83 |
sep_token_id: int = 5,
|
| 84 |
mask_token_id: int = 6,
|
| 85 |
-
byte_offset: int =
|
| 86 |
cls_pool_dim: int = 256,
|
| 87 |
initializer_range: float = 0.02,
|
| 88 |
mimelens_cell_id: str = "medium/bpe-16k/s1",
|
|
|
|
| 28 |
paper repository (https://github.com/mjbommar/binary-embedding-paper).
|
| 29 |
|
| 30 |
Args:
|
| 31 |
+
vocab_size: int — full vocabulary including 7 special tokens (start, end,
|
| 32 |
+
pad, unk, cls, sep, mask). byte cells: 263 (256 bytes + 7 specials).
|
| 33 |
+
BPE cells: 4103 / 16391 / 65543.
|
| 34 |
hidden_size: int — transformer model dimension (256 / 384 / 512 for
|
| 35 |
tiny / small / medium).
|
| 36 |
num_hidden_layers: int — layer count (4 / 8 / 12 for tiny / small /
|
|
|
|
| 47 |
pad_token_id / cls_token_id / sep_token_id / mask_token_id: int —
|
| 48 |
special-token indices, matching binary_embedding.constants.
|
| 49 |
byte_offset: int — for byte cells, ord(b)+byte_offset gives the token
|
| 50 |
+
id. Fixed at 7 (after the 7 special tokens). Unused for BPE cells.
|
| 51 |
cls_pool_dim: int — output dim of the cls_pool layer. Note: this layer
|
| 52 |
receives no gradient under MLM-only training (see paper §3.4); the
|
| 53 |
mean-pool over body tokens is the trained pooling, not cls_pool.
|
|
|
|
| 83 |
cls_token_id: int = 4,
|
| 84 |
sep_token_id: int = 5,
|
| 85 |
mask_token_id: int = 6,
|
| 86 |
+
byte_offset: int = 7,
|
| 87 |
cls_pool_dim: int = 256,
|
| 88 |
initializer_range: float = 0.02,
|
| 89 |
mimelens_cell_id: str = "medium/bpe-16k/s1",
|
modeling_mimelens.py
CHANGED
|
@@ -32,7 +32,7 @@ import torch
|
|
| 32 |
import torch.nn as nn
|
| 33 |
import torch.nn.functional as F
|
| 34 |
from transformers import PreTrainedModel
|
| 35 |
-
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
| 36 |
|
| 37 |
from .configuration_mimelens import MimeLensConfig
|
| 38 |
|
|
@@ -272,3 +272,103 @@ class MimeLensModel(PreTrainedModel):
|
|
| 272 |
attention_mask = torch.tensor([attn], dtype=torch.long, device=device)
|
| 273 |
with torch.inference_mode():
|
| 274 |
return self(input_ids, attention_mask=attention_mask).pooler_output
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
import torch.nn as nn
|
| 33 |
import torch.nn.functional as F
|
| 34 |
from transformers import PreTrainedModel
|
| 35 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput
|
| 36 |
|
| 37 |
from .configuration_mimelens import MimeLensConfig
|
| 38 |
|
|
|
|
| 272 |
attention_mask = torch.tensor([attn], dtype=torch.long, device=device)
|
| 273 |
with torch.inference_mode():
|
| 274 |
return self(input_ids, attention_mask=attention_mask).pooler_output
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class MimeLensForSequenceClassification(PreTrainedModel):
|
| 278 |
+
"""MimeLens encoder + a 125-class libmagic-MIME classifier head.
|
| 279 |
+
|
| 280 |
+
Lets users do, in one line:
|
| 281 |
+
|
| 282 |
+
from transformers import pipeline
|
| 283 |
+
clf = pipeline("text-classification",
|
| 284 |
+
model="mjbommar/mimelens-001-medium-bpe-16k-s1",
|
| 285 |
+
trust_remote_code=True)
|
| 286 |
+
clf(open("some.bin", "rb").read(4096).decode("latin-1"))
|
| 287 |
+
# → [{"label": "text/x-python", "score": 0.91}, ...]
|
| 288 |
+
|
| 289 |
+
The classifier head is the same logistic-regression probe the paper
|
| 290 |
+
reports on the magic-files corpus, re-fit on the full 4,096-file
|
| 291 |
+
labelled set and baked into `model.safetensors` as `classifier.weight`
|
| 292 |
+
and `classifier.bias`. Labels live in `config.id2label` / `config.label2id`.
|
| 293 |
+
|
| 294 |
+
For embedding-only use, load via `AutoModel.from_pretrained(...)` instead,
|
| 295 |
+
which returns mean-pooled embeddings and ignores the classifier head.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
config_class = MimeLensConfig
|
| 299 |
+
base_model_prefix = "mimelens"
|
| 300 |
+
|
| 301 |
+
def __init__(self, config: MimeLensConfig):
|
| 302 |
+
super().__init__(config)
|
| 303 |
+
self.config = config
|
| 304 |
+
self.num_labels = getattr(config, "num_labels", 125)
|
| 305 |
+
# The encoder body, identical to MimeLensModel — same parameter names so
|
| 306 |
+
# the encoder weights load from the same safetensors keys.
|
| 307 |
+
self.embed = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 308 |
+
self.layers = nn.ModuleList([Layer(config) for _ in range(config.num_hidden_layers)])
|
| 309 |
+
self.final_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 310 |
+
self.cls_pool = nn.Linear(config.hidden_size, config.cls_pool_dim, bias=False)
|
| 311 |
+
# The 125-way classifier head.
|
| 312 |
+
self.classifier = nn.Linear(config.hidden_size, self.num_labels)
|
| 313 |
+
|
| 314 |
+
self._rope_cache: Optional[tuple[torch.Tensor, torch.Tensor]] = None
|
| 315 |
+
self._rope_cache_meta: Optional[tuple[torch.device, torch.dtype, int]] = None
|
| 316 |
+
self.post_init()
|
| 317 |
+
|
| 318 |
+
def _init_weights(self, module):
|
| 319 |
+
if isinstance(module, nn.Linear):
|
| 320 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 321 |
+
if module.bias is not None:
|
| 322 |
+
module.bias.data.zero_()
|
| 323 |
+
elif isinstance(module, nn.Embedding):
|
| 324 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 325 |
+
if module.padding_idx is not None:
|
| 326 |
+
module.weight.data[module.padding_idx].zero_()
|
| 327 |
+
|
| 328 |
+
def _get_rope(self, seq_len: int, device: torch.device, dtype: torch.dtype):
|
| 329 |
+
meta = (device, dtype, seq_len)
|
| 330 |
+
if self._rope_cache_meta != meta:
|
| 331 |
+
self._rope_cache = _build_rope_cache(seq_len, self.config.head_dim,
|
| 332 |
+
self.config.rope_theta,
|
| 333 |
+
device=device, dtype=dtype)
|
| 334 |
+
self._rope_cache_meta = meta
|
| 335 |
+
return self._rope_cache
|
| 336 |
+
|
| 337 |
+
def forward(
|
| 338 |
+
self,
|
| 339 |
+
input_ids: torch.LongTensor,
|
| 340 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 341 |
+
labels: Optional[torch.LongTensor] = None,
|
| 342 |
+
return_dict: bool = True,
|
| 343 |
+
):
|
| 344 |
+
B, S = input_ids.shape
|
| 345 |
+
x = self.embed(input_ids)
|
| 346 |
+
|
| 347 |
+
if attention_mask is None:
|
| 348 |
+
attention_mask = torch.ones(B, S, device=input_ids.device, dtype=torch.long)
|
| 349 |
+
attn_mask = attention_mask.to(x.dtype)
|
| 350 |
+
attn_mask = (1.0 - attn_mask).masked_fill((1.0 - attn_mask).bool(),
|
| 351 |
+
torch.finfo(x.dtype).min)
|
| 352 |
+
attn_mask = attn_mask.view(B, 1, 1, S)
|
| 353 |
+
|
| 354 |
+
cos, sin = self._get_rope(S, device=x.device, dtype=x.dtype)
|
| 355 |
+
for layer in self.layers:
|
| 356 |
+
x = layer(x, cos, sin, attn_mask)
|
| 357 |
+
x = self.final_norm(x)
|
| 358 |
+
|
| 359 |
+
lens = attention_mask.sum(dim=1, keepdim=True)
|
| 360 |
+
positions = torch.arange(S, device=x.device).unsqueeze(0)
|
| 361 |
+
body_mask = (positions >= 1) & (positions < (lens - 1))
|
| 362 |
+
body_mask_f = body_mask.to(x.dtype).unsqueeze(-1)
|
| 363 |
+
pooled = (x * body_mask_f).sum(dim=1) / body_mask_f.sum(dim=1).clamp(min=1)
|
| 364 |
+
|
| 365 |
+
# Cast pooled to classifier dtype (bf16 encoder + fp32 classifier is common).
|
| 366 |
+
logits = self.classifier(pooled.to(self.classifier.weight.dtype))
|
| 367 |
+
|
| 368 |
+
loss = None
|
| 369 |
+
if labels is not None:
|
| 370 |
+
loss = F.cross_entropy(logits, labels)
|
| 371 |
+
|
| 372 |
+
if not return_dict:
|
| 373 |
+
return (loss, logits) if loss is not None else (logits,)
|
| 374 |
+
return SequenceClassifierOutput(loss=loss, logits=logits)
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"model_max_length": 1024,
|
| 4 |
+
"padding_side": "right",
|
| 5 |
+
"truncation_side": "right",
|
| 6 |
+
"pad_token": "[PAD]",
|
| 7 |
+
"unk_token": "[UNK]",
|
| 8 |
+
"cls_token": "[CLS]",
|
| 9 |
+
"sep_token": "[SEP]",
|
| 10 |
+
"mask_token": "[MASK]",
|
| 11 |
+
"clean_up_tokenization_spaces": false,
|
| 12 |
+
"added_tokens_decoder": {
|
| 13 |
+
"2": {
|
| 14 |
+
"content": "[PAD]",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"rstrip": false,
|
| 17 |
+
"single_word": false,
|
| 18 |
+
"normalized": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"3": {
|
| 22 |
+
"content": "[UNK]",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"rstrip": false,
|
| 25 |
+
"single_word": false,
|
| 26 |
+
"normalized": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"4": {
|
| 30 |
+
"content": "[CLS]",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"rstrip": false,
|
| 33 |
+
"single_word": false,
|
| 34 |
+
"normalized": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"5": {
|
| 38 |
+
"content": "[SEP]",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"rstrip": false,
|
| 41 |
+
"single_word": false,
|
| 42 |
+
"normalized": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"6": {
|
| 46 |
+
"content": "[MASK]",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"rstrip": false,
|
| 49 |
+
"single_word": false,
|
| 50 |
+
"normalized": false,
|
| 51 |
+
"special": true
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
}
|