mjbommar commited on
Commit
8f59d90
·
verified ·
1 Parent(s): d37cc3b

MimeLens-001 release: mimelens-001-tiny-bpe-64k-s2 (paper-applied @ git 47c142d)

Browse files
Files changed (6) hide show
  1. README.md +127 -0
  2. config.json +32 -0
  3. configuration_mimelens.py +126 -0
  4. manifest.json +11 -0
  5. model.safetensors +3 -0
  6. modeling_mimelens.py +274 -0
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: feature-extraction
15
+ model-index:
16
+ - name: mimelens-001-tiny-bpe-64k-s2
17
+ results:
18
+ - task:
19
+ type: feature-extraction
20
+ name: MIME-125 classification (libmagic 125-class taxonomy)
21
+ dataset:
22
+ name: magic-bpe magic-frags (4 KB head of 64 KB random chunks, n=4,096)
23
+ type: mjbommar/magic-bpe-stratified
24
+ metrics:
25
+ - name: top-1 accuracy
26
+ type: accuracy
27
+ value: 0.7324
28
+ - name: macro-F1
29
+ type: f1
30
+ value: 0.6086
31
+ - name: kNN R@1
32
+ type: recall@1
33
+ value: 0.6754
34
+ source:
35
+ name: "MimeLens paper (Bommarito 2026), Appendix A"
36
+ url: https://github.com/mjbommar/binary-embedding-paper
37
+ ---
38
+
39
+ # MimeLens-001 / tiny / bpe-64k / s2
40
+
41
+ **One cell from the [MimeLens-001](https://huggingface.co/mjbommar/mimelens-001) family** — `3.15` M backbone params, `bpe-64k` input pipeline, seed `2`. Pretrained MLM-only on 33 GB of position-arbitrary binary content for fine-grained file-content-type classification under [libmagic](https://github.com/file/file)'s 125-class MIME taxonomy.
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
+ ## How to use
48
+
49
+ ```python
50
+ import torch
51
+ from transformers import AutoModel
52
+ from tokenizers import Tokenizer
53
+
54
+ repo = "mjbommar/mimelens-001-tiny-bpe-64k-s2"
55
+ model = AutoModel.from_pretrained(repo, trust_remote_code=True).eval()
56
+ tok = Tokenizer.from_pretrained("mjbommar/binary-tokenizer-001-64k")
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
+ body = tok.encode(window.decode("latin-1")).ids[:1022]
62
+ ids = [cfg.cls_token_id] + body + [cfg.sep_token_id]
63
+ input_ids = torch.tensor([ids])
64
+
65
+ with torch.no_grad():
66
+ out = model(input_ids=input_ids, attention_mask=torch.ones_like(input_ids))
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
+ ## What this cell is
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
+ ## Evaluation
83
+
84
+ Numbers below are for **this specific cell** on the `magic-frags` held-out test set (4 KB head of 64 KB random chunks, n=4,096). The within-cube comparison (3 sizes × 4 vocabs × 2-3 seeds, bootstrap CIs, adversarial sweep, calibration, real-network and disk-block validations) is in the [paper](https://github.com/mjbommar/binary-embedding-paper).
85
+
86
+ | Benchmark | This cell |
87
+ |---|---|
88
+ | MIME-125 top-1 (magic-frags 4 KB head, n=4,096) | **0.732** |
89
+ | MIME-125 macro-F1 (magic-frags 4 KB head) | 0.609 |
90
+ | kNN R@1 (magic-frags, 3,147-file gallery / 949 queries) | 0.675 |
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 pre-registered 3 × 4 × 2 factorial cube described in the [MimeLens paper](https://github.com/mjbommar/binary-embedding-paper). Salient details:
99
+
100
+ - **33 GB stratified multi-source binary corpus** (binary-30k + magic-frags + glaurung + Windows drivers).
101
+ - **Position-arbitrary windowing**: 1024-token windows sampled uniformly at random across files and 64 KB fragments — no privileged "head of file" position. This is what makes MimeLens work on streaming / partial / random-offset inputs that whole-file detectors were not designed for.
102
+ - **MLM-only** objective, 30% mask ratio (BERT replacement schedule: 80% `[MASK]`, 10% random, 10% original); tied input/output embeddings.
103
+ - **Mean-pool over body tokens** for downstream tasks; the BERT-style `cls_pool` linear projection is *not* used because under MLM-only training it receives no gradient and remains at random init across all 28 cube cells (paper §3.4 verifies this).
104
+ - **Wall-clock**: ~2.7 h on a single RTX 4060 Ti.
105
+
106
+ ## Honest caveats
107
+
108
+ - This is one cell of a 28-cell cube. Within-cube comparisons in the paper come with bootstrap CIs at n=2 seeds; some marginal orderings (byte vs bpe-16k at the top of medium) are within seed noise and should be read as ties.
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 derived from a single labelling pipeline (libmagic-pinned via the [magic-bpe](https://github.com/mjbommar/magic-bpe) project). Cross-validation against PRONOM, Siegfried, DROID, or IANA reference files is a documented limitation.
111
+ - CPU latency at the `medium` size is ~348× slower than Magika; for sub-millisecond whole-file triage on broad categories, Magika is purpose-built and is the right default. MimeLens occupies a different point on the deployment surface (position-arbitrary inputs + libmagic's 125-class taxonomy) rather than a drop-in replacement.
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 reported above are not claimed as a lower bound on fine-tuned performance.
113
+
114
+ ## Citation
115
+
116
+ ```bibtex
117
+ @misc{bommarito2026mimelens,
118
+ title = {MimeLens: Pretrained Encoders for Fine-Grained Content-Type Detection},
119
+ author = {Bommarito II, Michael J.},
120
+ year = {2026},
121
+ note = {https://github.com/mjbommar/binary-embedding-paper},
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.
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MimeLensModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_mimelens.MimeLensConfig",
7
+ "AutoModel": "modeling_mimelens.MimeLensModel"
8
+ },
9
+ "model_type": "mimelens",
10
+ "torch_dtype": "float32",
11
+ "vocab_size": 65543,
12
+ "hidden_size": 256,
13
+ "num_hidden_layers": 4,
14
+ "num_attention_heads": 4,
15
+ "head_dim": 64,
16
+ "ffn_multiplier_num": 8,
17
+ "ffn_multiplier_den": 3,
18
+ "max_position_embeddings": 1024,
19
+ "rope_theta": 10000.0,
20
+ "rms_norm_eps": 1e-06,
21
+ "pad_token_id": 2,
22
+ "cls_token_id": 4,
23
+ "sep_token_id": 5,
24
+ "mask_token_id": 6,
25
+ "byte_offset": 5,
26
+ "cls_pool_dim": 256,
27
+ "mimelens_cell_id": "tiny/bpe-64k/s2",
28
+ "mimelens_vocab_pipeline": "bpe-64k",
29
+ "mimelens_tokenizer_hub_id": "mjbommar/binary-tokenizer-001-64k",
30
+ "mimelens_pretraining_steps": 22888,
31
+ "mimelens_seed": 2
32
+ }
configuration_mimelens.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace-compatible config class for MimeLens.
2
+
3
+ Copied verbatim into each per-cell HF repo (`mjbommar/mimelens-001-*`). Lets users
4
+ do `AutoConfig.from_pretrained("mjbommar/mimelens-001-medium-bpe-16k-s1",
5
+ trust_remote_code=True)` after the auto_map in config.json is honored.
6
+
7
+ This file has zero non-stdlib dependencies beyond `transformers`. It's
8
+ intentionally short — all torch / nn imports live in modeling_mimelens.py.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Optional
14
+
15
+ from transformers import PretrainedConfig
16
+
17
+
18
+ class MimeLensConfig(PretrainedConfig):
19
+ """Configuration for a MimeLens encoder cell.
20
+
21
+ A MimeLens cell is one (size × vocab × seed) point of the binary-embedding
22
+ paper's 3x4xN cube: a BERT-style transformer encoder pretrained MLM-only on
23
+ 33 GB of position-arbitrary binary content, with one of four input
24
+ pipelines (raw bytes, or BPE at 4K/16K/64K vocabulary).
25
+
26
+ For the architectural rationale and pretraining details see
27
+ docs/02-model-architecture.md and docs/04-training-protocol.md in the
28
+ paper repository (https://github.com/mjbommar/binary-embedding-paper).
29
+
30
+ Args:
31
+ vocab_size: int — full vocabulary including 5 special tokens. byte
32
+ cells: 261 (256 bytes + 5 specials). BPE cells: 4101 / 16391 / 65543.
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 /
36
+ medium).
37
+ num_attention_heads: int — head count (4 / 6 / 8). Head dim is always
38
+ 64 by design.
39
+ head_dim: int — per-head attention dimension. Fixed at 64 in the paper.
40
+ ffn_multiplier_num / ffn_multiplier_den: int — GeGLU FFN expansion as
41
+ a rational (8/3 ≈ 2.67, the LLaMA convention).
42
+ max_position_embeddings: int — RoPE position table size. Fixed at 1024
43
+ in the paper.
44
+ rope_theta: float — RoPE base frequency. Fixed at 10,000.
45
+ rms_norm_eps: float — RMSNorm epsilon. Fixed at 1e-6.
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 5 (after the 5 special tokens). Unused for BPE cells.
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.
53
+ initializer_range: float — std of trunc-normal init.
54
+
55
+ # MimeLens-specific provenance / tokenizer metadata:
56
+ mimelens_cell_id: str — e.g. "medium/bpe-16k/s1".
57
+ mimelens_vocab_pipeline: str — one of "byte", "bpe-4k", "bpe-16k",
58
+ "bpe-64k". Drives the tokenization in modeling_mimelens.
59
+ mimelens_tokenizer_hub_id: Optional[str] — for BPE cells, the HF Hub
60
+ id of the canonical tokenizer (e.g.
61
+ "mjbommar/binary-tokenizer-001-16k"). None for byte cells.
62
+ mimelens_pretraining_steps: int — total gradient updates (22,888
63
+ standard; 47,808 for the matched-tokens-seen ablation cell).
64
+ mimelens_seed: int — pretraining RNG seed (1, 2, or 3).
65
+ """
66
+
67
+ model_type = "mimelens"
68
+
69
+ def __init__(
70
+ self,
71
+ vocab_size: int = 16391,
72
+ hidden_size: int = 512,
73
+ num_hidden_layers: int = 12,
74
+ num_attention_heads: int = 8,
75
+ head_dim: int = 64,
76
+ ffn_multiplier_num: int = 8,
77
+ ffn_multiplier_den: int = 3,
78
+ max_position_embeddings: int = 1024,
79
+ rope_theta: float = 10_000.0,
80
+ rms_norm_eps: float = 1e-6,
81
+ pad_token_id: int = 2,
82
+ cls_token_id: int = 4,
83
+ sep_token_id: int = 5,
84
+ mask_token_id: int = 6,
85
+ byte_offset: int = 5,
86
+ cls_pool_dim: int = 256,
87
+ initializer_range: float = 0.02,
88
+ mimelens_cell_id: str = "medium/bpe-16k/s1",
89
+ mimelens_vocab_pipeline: str = "bpe-16k",
90
+ mimelens_tokenizer_hub_id: Optional[str] = "mjbommar/binary-tokenizer-001-16k",
91
+ mimelens_pretraining_steps: int = 22_888,
92
+ mimelens_seed: int = 1,
93
+ **kwargs,
94
+ ):
95
+ self.vocab_size = vocab_size
96
+ self.hidden_size = hidden_size
97
+ self.num_hidden_layers = num_hidden_layers
98
+ self.num_attention_heads = num_attention_heads
99
+ self.head_dim = head_dim
100
+ self.ffn_multiplier_num = ffn_multiplier_num
101
+ self.ffn_multiplier_den = ffn_multiplier_den
102
+ self.max_position_embeddings = max_position_embeddings
103
+ self.rope_theta = rope_theta
104
+ self.rms_norm_eps = rms_norm_eps
105
+ self.cls_token_id = cls_token_id
106
+ self.sep_token_id = sep_token_id
107
+ self.mask_token_id = mask_token_id
108
+ self.byte_offset = byte_offset
109
+ self.cls_pool_dim = cls_pool_dim
110
+ self.initializer_range = initializer_range
111
+ self.mimelens_cell_id = mimelens_cell_id
112
+ self.mimelens_vocab_pipeline = mimelens_vocab_pipeline
113
+ self.mimelens_tokenizer_hub_id = mimelens_tokenizer_hub_id
114
+ self.mimelens_pretraining_steps = mimelens_pretraining_steps
115
+ self.mimelens_seed = mimelens_seed
116
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
117
+
118
+ @property
119
+ def head_size(self) -> int:
120
+ """For HF compatibility — alias for head_dim."""
121
+ return self.head_dim
122
+
123
+ @property
124
+ def intermediate_size(self) -> int:
125
+ """GeGLU expansion: hidden * (ffn_multiplier_num / ffn_multiplier_den)."""
126
+ return self.hidden_size * self.ffn_multiplier_num // self.ffn_multiplier_den
manifest.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mimelens_release": "001",
3
+ "cell_id": "tiny/bpe-64k/s2",
4
+ "ckpt_source": "/data0/binary-embedding/phase-b/runs/tiny/bpe-64k/s2/checkpoints/best.safetensors",
5
+ "ckpt_sha256": "b2c5a5c935b300ad14eb2fd5efcb39dc2af784aa8fc40ca5ac7f3d8ed5b5d8ae",
6
+ "magicfiles_top1": 0.732421875,
7
+ "magicfiles_f1": 0.6086128821558999,
8
+ "magicfrags_top1": 0.732421875,
9
+ "magicfrags_f1": 0.6086128821558999,
10
+ "params_m": 3.15
11
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2c5a5c935b300ad14eb2fd5efcb39dc2af784aa8fc40ca5ac7f3d8ed5b5d8ae
3
+ size 79965016
modeling_mimelens.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace-compatible inference model for MimeLens.
2
+
3
+ Copied verbatim into each per-cell HF repo (`mjbommar/mimelens-001-*`). Lets
4
+ users do:
5
+
6
+ from transformers import AutoModel, AutoConfig
7
+ config = AutoConfig.from_pretrained("mjbommar/mimelens-001-medium-bpe-16k-s1",
8
+ trust_remote_code=True)
9
+ model = AutoModel.from_pretrained("mjbommar/mimelens-001-medium-bpe-16k-s1",
10
+ trust_remote_code=True)
11
+ # → forward(input_ids, attention_mask) returns the mean-pooled body-token
12
+ # embedding, shape (batch, hidden_size).
13
+
14
+ The architecture is the small ModernBERT-style encoder from
15
+ binary_embedding.models.encoder, vendored here to make each HF repo
16
+ self-contained (no pip install binary_embedding required at inference time).
17
+
18
+ Parameter naming is byte-compatible with the saved best.safetensors files so
19
+ that AutoModel.from_pretrained() loads weights without prefix surgery.
20
+
21
+ Pure torch; no scapy / sklearn / external deps. The mean-pool returned here
22
+ is the same projection used throughout the paper; the cls_pool layer is
23
+ known to receive no gradient under MLM-only training (see paper §3.4) and is
24
+ kept only for state-dict compatibility — do not use it for downstream tasks.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Optional
30
+
31
+ 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
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Building blocks
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ class RMSNorm(nn.Module):
46
+ """RMSNorm without bias. bf16-safe (norm computed in fp32)."""
47
+
48
+ def __init__(self, hidden_size: int, eps: float = 1e-6) -> None:
49
+ super().__init__()
50
+ self.weight = nn.Parameter(torch.ones(hidden_size))
51
+ self.eps = eps
52
+
53
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
54
+ variance = x.float().pow(2).mean(-1, keepdim=True)
55
+ normed = x * torch.rsqrt(variance + self.eps).to(x.dtype)
56
+ return normed * self.weight
57
+
58
+
59
+ def _build_rope_cache(seq_len: int, head_dim: int, base: float,
60
+ device: torch.device, dtype: torch.dtype):
61
+ positions = torch.arange(seq_len, device=device, dtype=torch.float32)
62
+ inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device,
63
+ dtype=torch.float32) / head_dim))
64
+ freqs = torch.einsum("p,d->pd", positions, inv_freq)
65
+ cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1).to(dtype)
66
+ sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1).to(dtype)
67
+ return cos, sin
68
+
69
+
70
+ def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
71
+ """Apply rotary position embedding. x: (..., seq, head_dim)."""
72
+ d = x.shape[-1]
73
+ x1, x2 = x[..., : d // 2], x[..., d // 2 :]
74
+ rotated = torch.cat([-x2, x1], dim=-1)
75
+ return x * cos + rotated * sin
76
+
77
+
78
+ class Attention(nn.Module):
79
+ def __init__(self, hidden_size: int, num_heads: int, head_dim: int):
80
+ super().__init__()
81
+ self.num_heads = num_heads
82
+ self.head_dim = head_dim
83
+ self.qkv = nn.Linear(hidden_size, 3 * num_heads * head_dim, bias=False)
84
+ self.out = nn.Linear(num_heads * head_dim, hidden_size, bias=False)
85
+
86
+ def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
87
+ attn_mask: torch.Tensor) -> torch.Tensor:
88
+ B, S, _ = x.shape
89
+ qkv = self.qkv(x).reshape(B, S, 3, self.num_heads, self.head_dim)
90
+ q, k, v = qkv.unbind(dim=2) # each (B, S, H, D)
91
+ q = _apply_rope(q.transpose(1, 2), cos, sin) # (B, H, S, D)
92
+ k = _apply_rope(k.transpose(1, 2), cos, sin)
93
+ v = v.transpose(1, 2)
94
+ # attn_mask: (B, 1, 1, S) with -inf at pad positions, 0 at real positions
95
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
96
+ out = out.transpose(1, 2).contiguous().reshape(B, S, -1)
97
+ return self.out(out)
98
+
99
+
100
+ class FFN(nn.Module):
101
+ """GeGLU FFN: gelu(w_gate(x)) * w_up(x) → w_down."""
102
+
103
+ def __init__(self, hidden_size: int, intermediate_size: int):
104
+ super().__init__()
105
+ self.w_gate = nn.Linear(hidden_size, intermediate_size, bias=False)
106
+ self.w_up = nn.Linear(hidden_size, intermediate_size, bias=False)
107
+ self.w_down = nn.Linear(intermediate_size, hidden_size, bias=False)
108
+
109
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
110
+ return self.w_down(F.gelu(self.w_gate(x)) * self.w_up(x))
111
+
112
+
113
+ class Layer(nn.Module):
114
+ def __init__(self, config: MimeLensConfig):
115
+ super().__init__()
116
+ self.norm1 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
117
+ self.attn = Attention(config.hidden_size, config.num_attention_heads,
118
+ config.head_dim)
119
+ self.norm2 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
120
+ self.ffn = FFN(config.hidden_size, config.intermediate_size)
121
+
122
+ def forward(self, x, cos, sin, attn_mask):
123
+ x = x + self.attn(self.norm1(x), cos, sin, attn_mask)
124
+ x = x + self.ffn(self.norm2(x))
125
+ return x
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # Top-level model
130
+ # ---------------------------------------------------------------------------
131
+
132
+
133
+ class MimeLensModel(PreTrainedModel):
134
+ """MimeLens encoder: bytes → mean-pooled embedding.
135
+
136
+ Use `forward(input_ids, attention_mask)` and consume the `pooler_output`
137
+ field (mean over body tokens, skipping the CLS / SEP / PAD positions).
138
+ Last-hidden-state is also returned as `last_hidden_state` if you want to
139
+ do your own pooling.
140
+ """
141
+
142
+ config_class = MimeLensConfig
143
+ base_model_prefix = "mimelens"
144
+
145
+ def __init__(self, config: MimeLensConfig):
146
+ super().__init__(config)
147
+ self.config = config
148
+
149
+ # Parameter naming MUST match best.safetensors: flat (no `encoder.` prefix).
150
+ self.embed = nn.Embedding(config.vocab_size, config.hidden_size)
151
+ self.layers = nn.ModuleList([Layer(config) for _ in range(config.num_hidden_layers)])
152
+ self.final_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
153
+ # cls_pool is kept ONLY for safetensors compatibility — receives no
154
+ # gradient under MLM-only training; use mean-pool instead.
155
+ self.cls_pool = nn.Linear(config.hidden_size, config.cls_pool_dim, bias=False)
156
+
157
+ # Lazily-built RoPE cache (one per device/dtype combination).
158
+ self._rope_cache: Optional[tuple[torch.Tensor, torch.Tensor]] = None
159
+ self._rope_cache_meta: Optional[tuple[torch.device, torch.dtype, int]] = None
160
+
161
+ # No weight init here — we always load_state_dict from a pretrained
162
+ # checkpoint via from_pretrained(). HF complains if we don't provide
163
+ # an init_weights; provide the no-op version.
164
+ self.post_init()
165
+
166
+ def _init_weights(self, module):
167
+ """No-op: we always load from a pretrained checkpoint."""
168
+ if isinstance(module, nn.Linear):
169
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
170
+ if module.bias is not None:
171
+ module.bias.data.zero_()
172
+ elif isinstance(module, nn.Embedding):
173
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
174
+ if module.padding_idx is not None:
175
+ module.weight.data[module.padding_idx].zero_()
176
+
177
+ def _get_rope(self, seq_len: int, device: torch.device, dtype: torch.dtype):
178
+ meta = (device, dtype, seq_len)
179
+ if self._rope_cache_meta != meta:
180
+ self._rope_cache = _build_rope_cache(seq_len, self.config.head_dim,
181
+ self.config.rope_theta,
182
+ device=device, dtype=dtype)
183
+ self._rope_cache_meta = meta
184
+ return self._rope_cache
185
+
186
+ def forward(
187
+ self,
188
+ input_ids: torch.LongTensor,
189
+ attention_mask: Optional[torch.Tensor] = None,
190
+ output_hidden_states: bool = False,
191
+ return_dict: bool = True,
192
+ ):
193
+ B, S = input_ids.shape
194
+ x = self.embed(input_ids) # (B, S, H)
195
+
196
+ # Build SDPA attention mask: (B, 1, 1, S) additive, -inf at pad.
197
+ if attention_mask is None:
198
+ attention_mask = torch.ones(B, S, device=input_ids.device, dtype=torch.long)
199
+ # Convert to additive: real (=1) → 0, pad (=0) → -inf
200
+ # SDPA expects mask broadcastable to (B, H, S, S)
201
+ attn_mask = attention_mask.to(x.dtype)
202
+ attn_mask = (1.0 - attn_mask).masked_fill((1.0 - attn_mask).bool(),
203
+ torch.finfo(x.dtype).min)
204
+ # shape: (B, 1, 1, S) — broadcasts over heads and queries
205
+ attn_mask = attn_mask.view(B, 1, 1, S)
206
+
207
+ cos, sin = self._get_rope(S, device=x.device, dtype=x.dtype)
208
+
209
+ for layer in self.layers:
210
+ x = layer(x, cos, sin, attn_mask)
211
+
212
+ x = self.final_norm(x)
213
+ last_hidden_state = x
214
+
215
+ # Mean-pool over BODY tokens (skip CLS @ pos 0, SEP @ pos lens-1, PAD).
216
+ # attention_mask is (B, S) of {0,1}.
217
+ lens = attention_mask.sum(dim=1, keepdim=True) # (B, 1)
218
+ positions = torch.arange(S, device=x.device).unsqueeze(0) # (1, S)
219
+ body_mask = (positions >= 1) & (positions < (lens - 1)) # (B, S) bool
220
+ body_mask_f = body_mask.to(x.dtype).unsqueeze(-1) # (B, S, 1)
221
+ pooled = (x * body_mask_f).sum(dim=1) / body_mask_f.sum(dim=1).clamp(min=1)
222
+ # shape: (B, H)
223
+
224
+ if not return_dict:
225
+ return (last_hidden_state, pooled)
226
+ return BaseModelOutputWithPooling(
227
+ last_hidden_state=last_hidden_state,
228
+ pooler_output=pooled,
229
+ )
230
+
231
+ # ---------------------------------------------------------------------
232
+ # Helper utilities for users (not part of the standard HF surface)
233
+ # ---------------------------------------------------------------------
234
+
235
+ def encode_bytes(
236
+ self,
237
+ byte_window: bytes,
238
+ tokenizer=None,
239
+ seq_len: Optional[int] = None,
240
+ ) -> torch.Tensor:
241
+ """Convenience: encode one raw byte window into a mean-pooled embedding.
242
+
243
+ For byte cells (`config.mimelens_vocab_pipeline == 'byte'`), tokenizer
244
+ is ignored. For BPE cells, pass a BinaryTokenizer (from
245
+ `mjbommar/binary-tokenizer-001-*`) or any tokenizer with `.encode(bytes)
246
+ -> list[int]`.
247
+
248
+ Returns a (1, hidden_size) tensor on the same device as the model.
249
+ """
250
+ seq_len = seq_len or self.config.max_position_embeddings
251
+ body = seq_len - 2
252
+ cls_id = self.config.cls_token_id
253
+ sep_id = self.config.sep_token_id
254
+ pad_id = self.config.pad_token_id
255
+
256
+ if self.config.mimelens_vocab_pipeline == "byte":
257
+ ids = [b + self.config.byte_offset for b in byte_window[:body]]
258
+ else:
259
+ if tokenizer is None:
260
+ raise ValueError(
261
+ f"BPE cell {self.config.mimelens_cell_id} requires a tokenizer; "
262
+ f"load with e.g. `_native.BinaryTokenizer.from_file(...)` from "
263
+ f"{self.config.mimelens_tokenizer_hub_id}"
264
+ )
265
+ ids = list(tokenizer.encode(byte_window))[:body]
266
+ out_ids = [cls_id, *ids, sep_id]
267
+ attn = [1] * len(out_ids) + [0] * (seq_len - len(out_ids))
268
+ out_ids = out_ids + [pad_id] * (seq_len - len(out_ids))
269
+
270
+ device = next(self.parameters()).device
271
+ input_ids = torch.tensor([out_ids], dtype=torch.long, device=device)
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