mjbommar commited on
Commit
72cc4e2
·
verified ·
1 Parent(s): 7a7bdd1

Upload magic-bert-50m-roformer-mlm model files

Browse files
Files changed (6) hide show
  1. README.md +265 -0
  2. config.json +23 -0
  3. mime_type_mapping.json +108 -0
  4. model.safetensors +3 -0
  5. tokenizer.json +0 -0
  6. tokenizer_config.json +9 -0
README.md ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: apache-2.0
5
+ library_name: transformers
6
+ tags:
7
+ - binary-analysis
8
+ - file-type-detection
9
+ - byte-level
10
+ - fill-mask
11
+ - mlm
12
+ - roformer
13
+ - rope
14
+ - magic-bytes
15
+ - security
16
+ pipeline_tag: fill-mask
17
+ model-index:
18
+ - name: magic-bert-50m-roformer-mlm
19
+ results:
20
+ - task:
21
+ type: fill-mask
22
+ name: Masked Language Modeling
23
+ metrics:
24
+ - name: Perplexity
25
+ type: perplexity
26
+ value: 1.13
27
+ - name: Fill-mask Top-1 Accuracy
28
+ type: accuracy
29
+ value: 61.8
30
+ - name: Fill-mask Top-5 Accuracy
31
+ type: accuracy
32
+ value: 75.1
33
+ - name: Probing Classification Accuracy
34
+ type: accuracy
35
+ value: 85.0
36
+ ---
37
+
38
+ # Magic-BERT 50M RoFormer MLM
39
+
40
+ A RoFormer-based transformer model trained for binary file understanding using masked language modeling (MLM). This model uses Rotary Position Embeddings (RoPE) for position encoding, which provides better relative position modeling than absolute embeddings.
41
+
42
+ ## Why Not Just Use libmagic?
43
+
44
+ For intact files starting at byte 0, libmagic works well. But libmagic matches *signatures at fixed offsets*. Magic-BERT learns *structural patterns* throughout the file, enabling use cases where you don't have clean file boundaries:
45
+
46
+ - **Network streams**: Classifying packet payloads mid-connection, before headers arrive
47
+ - **Disk forensics**: Identifying file types during carving, when scanning raw disk images without filesystem metadata
48
+ - **Fragment analysis**: Working with partial files, slack space, or corrupted data
49
+ - **Adversarial contexts**: Detecting file types when magic bytes are stripped, spoofed, or deliberately misleading
50
+
51
+ ## Model Description
52
+
53
+ This model uses the HuggingFace RoFormer architecture with a byte-level BPE tokenizer trained on binary file data. RoPE encodes position information directly in the attention computation through rotation matrices.
54
+
55
+ | Property | Value |
56
+ |----------|-------|
57
+ | Parameters | 42.3M |
58
+ | Hidden Size | 512 |
59
+ | Layers | 8 |
60
+ | Attention Heads | 8 |
61
+ | Max Sequence Length | 512 tokens |
62
+ | Vocabulary Size | 32,768 (byte-level BPE) |
63
+ | Position Encoding | RoPE (Rotary Position Embeddings) |
64
+
65
+ ### Tokenizer
66
+
67
+ The tokenizer uses the Binary BPE methodology introduced in [Bommarito (2025)](https://arxiv.org/abs/2511.17573). The original Binary BPE tokenizers (available at [mjbommar/binary-tokenizer-001-64k](https://huggingface.co/mjbommar/binary-tokenizer-001-64k)) were trained exclusively on executable binaries (ELF, PE, Mach-O). This tokenizer uses the same BPE training approach but was trained on a diverse corpus spanning 106 file types.
68
+
69
+ ## Intended Uses
70
+
71
+ **Primary use cases:**
72
+ - Fill-mask: Predicting missing bytes in binary files
73
+ - Magic byte and file signature recognition
74
+ - Feature extraction for downstream classification
75
+ - Research on binary file structure with relative position encoding
76
+
77
+ **Example tasks:**
78
+ - Completing partial file headers
79
+ - Identifying file type from structure
80
+ - Exploring position-independent file patterns
81
+
82
+ ## Detailed Use Cases
83
+
84
+ ### Network Traffic Analysis
85
+ When inspecting packet payloads, you often see file data mid-stream—TCP reassembly may give you bytes 1500-3000 of a PDF before you ever see byte 0. Traditional signature matching fails here. Structural understanding can identify file types from interior content.
86
+
87
+ ### Disk Forensics & File Carving
88
+ During disk image analysis, you scan raw bytes looking for file boundaries. Tools like Scalpel rely on header/footer signatures, but many files lack clear footers. This model can score byte ranges for file type probability, helping identify carved fragments or validate carving results.
89
+
90
+ ### Incident Response
91
+ Malware often strips or modifies magic bytes to evade detection. Polyglot files (valid as multiple types) exploit signature-based tools. Learning structural patterns provides a second opinion that doesn't rely solely on the first few bytes.
92
+
93
+ ### Embedded Content Detection
94
+ Files within files (email attachments, archive contents, OLE streams) may appear at arbitrary offsets. Embeddings enable similarity search: "find all chunks that look structurally like JPEG data" regardless of where they appear.
95
+
96
+ ## Architecture: RoPE vs Absolute Position Embeddings
97
+
98
+ This model uses **Rotary Position Embeddings (RoPE)**, which encode position through rotation matrices applied to query and key vectors in attention. This differs from **absolute position embeddings** (used by standard BERT), which add learned position vectors to token embeddings.
99
+
100
+ ### Why RoPE?
101
+
102
+ RoPE was designed for better relative position modeling:
103
+ - Encodes relative position naturally through the rotation angle
104
+ - Theoretically supports length extrapolation (though not tested beyond 512)
105
+ - 28% fewer parameters than absolute position variant (42M vs 59M)
106
+
107
+ ### Position Bias: Key Finding
108
+
109
+ **RoPE does not solve position bias for file type modeling.** Both RoPE (this model) and absolute position embeddings (Magic-BERT) show nearly identical position bias (~47% accuracy drop at offset 1000).
110
+
111
+ This occurs because position bias is learned from the training data distribution, where files naturally start at offset 0. The position encoding mechanism doesn't affect this learned correlation. Solutions should focus on data augmentation rather than architecture changes.
112
+
113
+ | Aspect | RoFormer (this) | Magic-BERT |
114
+ |--------|-----------------|------------|
115
+ | Position Encoding | RoPE (rotary) | Absolute (learned) |
116
+ | Parameters | **42.3M** | 59M |
117
+ | Perplexity | 1.13 | **1.05** |
118
+ | Fill-mask Top-1 | **61.8%** | 58.9% |
119
+ | Probing Accuracy | 85.0% | **87.0%** |
120
+ | Position Bias @ 1000 | ~46% drop | ~48% drop |
121
+
122
+ RoFormer achieves better fill-mask accuracy with fewer parameters. Magic-BERT achieves better perplexity and probing accuracy.
123
+
124
+ ## MLM vs Classification: Two-Phase Training
125
+
126
+ This is the **Phase 1 (MLM)** model. The training pipeline has two phases:
127
+
128
+ | Phase | Model | Task | Purpose |
129
+ |-------|-------|------|---------|
130
+ | **Phase 1** | **This model** | Masked Language Modeling | Learn byte-level patterns and file structure |
131
+ | Phase 2 | magic-bert-50m-roformer-classification | Contrastive Learning | Optimize embeddings for file type discrimination |
132
+
133
+ **When to use each:**
134
+ - Use **this model (MLM)** for: fill-mask tasks, research, or as a base for custom fine-tuning
135
+ - Use **classification model** for: file type detection, similarity search, production classification
136
+
137
+ ## Training
138
+
139
+ ### Data
140
+ Trained on a diverse corpus of binary files spanning 106 MIME types, including documents, images, audio/video, archives, executables, and more.
141
+
142
+ ### Procedure
143
+
144
+ | Phase | Steps | Learning Rate | Batch Size | Objective |
145
+ |-------|-------|---------------|------------|-----------|
146
+ | MLM Pre-training | 100,000 | 1e-4 | 240 | Masked LM (15% masking) |
147
+
148
+ **Data augmentation:** 50% of samples use random byte offset to reduce position bias.
149
+
150
+ ## Evaluation Results
151
+
152
+ ### Perplexity by Region
153
+ | Region | Perplexity |
154
+ |--------|------------|
155
+ | Magic Bytes (0-9) | 1.12 |
156
+ | Header (10-49) | 1.15 |
157
+ | Body (50+) | 1.13 |
158
+ | **Overall** | **1.13** |
159
+
160
+ ### Fill-Mask Accuracy
161
+ | Metric | Value |
162
+ |--------|-------|
163
+ | Top-1 Accuracy | 61.8% |
164
+ | Top-5 Accuracy | 75.1% |
165
+ | Mean Reciprocal Rank | 0.682 |
166
+
167
+ ### Representation Quality
168
+ | Metric | Value |
169
+ |--------|-------|
170
+ | Linear Probe Accuracy | 85.0% |
171
+ | Silhouette Score | 0.328 |
172
+ | Separation Ratio | 2.65 |
173
+
174
+ ## How to Use
175
+
176
+ ```python
177
+ from transformers import RoFormerForMaskedLM, AutoTokenizer
178
+ import torch
179
+
180
+ # Load model and tokenizer
181
+ model = RoFormerForMaskedLM.from_pretrained("path/to/magic-bert-50m-roformer-mlm")
182
+ tokenizer = AutoTokenizer.from_pretrained("path/to/magic-bert-50m-roformer-mlm")
183
+
184
+ model.eval()
185
+
186
+ # Fill-mask example
187
+ with open("example.pdf", "rb") as f:
188
+ data = f.read(512)
189
+
190
+ # Decode bytes to string using latin-1 (preserves all byte values 0-255)
191
+ text = data.decode("latin-1")
192
+
193
+ # Tokenize and mask
194
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
195
+ mask_pos = 0 # Mask first token
196
+ inputs["input_ids"][0, mask_pos] = tokenizer.mask_token_id
197
+
198
+ # Predict
199
+ with torch.no_grad():
200
+ outputs = model(**inputs)
201
+ predictions = outputs.logits[0, mask_pos].topk(5)
202
+
203
+ print("Top-5 predictions:", tokenizer.convert_ids_to_tokens(predictions.indices))
204
+ ```
205
+
206
+ ### Getting Embeddings
207
+
208
+ ```python
209
+ from transformers import RoFormerModel
210
+
211
+ # Load base model for embeddings
212
+ model = RoFormerModel.from_pretrained("path/to/magic-bert-50m-roformer-mlm")
213
+
214
+ with torch.no_grad():
215
+ outputs = model(**inputs)
216
+ # CLS token embedding
217
+ cls_embedding = outputs.last_hidden_state[:, 0, :]
218
+ # Mean pooling
219
+ mean_embedding = outputs.last_hidden_state.mean(dim=1)
220
+ ```
221
+
222
+ ## Limitations
223
+
224
+ 1. **Position bias:** Despite using RoPE, the model shows similar position bias to absolute position models (~46% accuracy drop at offset 1000). This is due to training data distribution, not architecture.
225
+
226
+ 2. **Sequence length:** Limited to 512 tokens. While RoPE theoretically supports length extrapolation, this model was not trained for longer sequences.
227
+
228
+ 3. **HuggingFace integration:** Uses standard RoFormer architecture, making it easy to deploy but less customizable than the Magic-BERT variant.
229
+
230
+ ## Model Selection Guide
231
+
232
+ | Use Case | Recommended Model | Reason |
233
+ |----------|-------------------|--------|
234
+ | Fill-mask / byte prediction | **This model** | Best fill-mask accuracy (61.8%) with fewer params |
235
+ | Research baseline | magic-bert-50m-mlm | Established BERT architecture, best perplexity |
236
+ | Classification + fill-mask | magic-bert-50m-classification | Retains 41.8% fill-mask capability |
237
+ | **Production classification** | **magic-bert-50m-roformer-classification** | Highest accuracy (93.7%), efficient (42M params) |
238
+
239
+ ## Related Models
240
+
241
+ - **magic-bert-50m-roformer-classification**: Same architecture fine-tuned for classification (93.7% accuracy, recommended for production)
242
+ - **magic-bert-50m-mlm**: Absolute position embedding variant
243
+ - **magic-bert-50m-classification**: Absolute position variant fine-tuned for classification (89.7% accuracy)
244
+
245
+ ## Related Work
246
+
247
+ This model builds on the Binary BPE tokenization approach:
248
+
249
+ - **Binary BPE Paper**: [Bommarito (2025)](https://arxiv.org/abs/2511.17573) introduced byte-level BPE tokenization for binary analysis, demonstrating 2-3x compression over raw bytes for executable content.
250
+ - **Binary BPE Tokenizers**: Pre-trained tokenizers for executables are available at [mjbommar/binary-tokenizer-001-64k](https://huggingface.co/mjbommar/binary-tokenizer-001-64k).
251
+
252
+ **Key difference**: The original Binary BPE work focused on executable binaries (ELF, PE, Mach-O). Magic-BERT extends this to general file type understanding across 106 diverse formats, using a tokenizer trained on the broader dataset.
253
+
254
+ ## Citation
255
+
256
+ A paper describing Magic-BERT, the training methodology, and the dataset is forthcoming.
257
+
258
+ ```bibtex
259
+ @article{bommarito2025binarybpe,
260
+ title={Binary BPE: A Family of Cross-Platform Tokenizers for Binary Analysis},
261
+ author={Bommarito, Michael J., II},
262
+ journal={arXiv preprint arXiv:2511.17573},
263
+ year={2025}
264
+ }
265
+ ```
config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "RoFormerForMaskedLM"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "embedding_size": 512,
7
+ "hidden_act": "gelu",
8
+ "hidden_dropout_prob": 0.1,
9
+ "hidden_size": 512,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 2048,
12
+ "layer_norm_eps": 1e-12,
13
+ "max_position_embeddings": 512,
14
+ "model_type": "roformer",
15
+ "num_attention_heads": 8,
16
+ "num_hidden_layers": 8,
17
+ "pad_token_id": 2,
18
+ "rotary_value": false,
19
+ "transformers_version": "4.57.3",
20
+ "type_vocab_size": 1,
21
+ "use_cache": true,
22
+ "vocab_size": 32768
23
+ }
mime_type_mapping.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "0": "application/SIMH-tape-data",
3
+ "1": "application/encrypted",
4
+ "2": "application/gzip",
5
+ "3": "application/javascript",
6
+ "4": "application/json",
7
+ "5": "application/msword",
8
+ "6": "application/mxf",
9
+ "7": "application/octet-stream",
10
+ "8": "application/pdf",
11
+ "9": "application/pgp-keys",
12
+ "10": "application/postscript",
13
+ "11": "application/vnd.microsoft.portable-executable",
14
+ "12": "application/vnd.ms-excel",
15
+ "13": "application/vnd.ms-opentype",
16
+ "14": "application/vnd.ms-powerpoint",
17
+ "15": "application/vnd.oasis.opendocument.spreadsheet",
18
+ "16": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
19
+ "17": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
20
+ "18": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
21
+ "19": "application/vnd.rn-realmedia",
22
+ "20": "application/vnd.wordperfect",
23
+ "21": "application/wasm",
24
+ "22": "application/x-7z-compressed",
25
+ "23": "application/x-archive",
26
+ "24": "application/x-bzip2",
27
+ "25": "application/x-coff",
28
+ "26": "application/x-dbf",
29
+ "27": "application/x-dosexec",
30
+ "28": "application/x-executable",
31
+ "29": "application/x-gettext-translation",
32
+ "30": "application/x-ms-ne-executable",
33
+ "31": "application/x-ndjson",
34
+ "32": "application/x-object",
35
+ "33": "application/x-ole-storage",
36
+ "34": "application/x-sharedlib",
37
+ "35": "application/x-shockwave-flash",
38
+ "36": "application/x-tar",
39
+ "37": "application/x-wine-extension-ini",
40
+ "38": "application/zip",
41
+ "39": "application/zlib",
42
+ "40": "application/zstd",
43
+ "41": "audio/amr",
44
+ "42": "audio/flac",
45
+ "43": "audio/mpeg",
46
+ "44": "audio/ogg",
47
+ "45": "audio/x-ape",
48
+ "46": "audio/x-hx-aac-adts",
49
+ "47": "audio/x-m4a",
50
+ "48": "audio/x-wav",
51
+ "49": "biosig/atf",
52
+ "50": "font/sfnt",
53
+ "51": "font/woff",
54
+ "52": "font/woff2",
55
+ "53": "image/bmp",
56
+ "54": "image/fits",
57
+ "55": "image/gif",
58
+ "56": "image/heif",
59
+ "57": "image/jpeg",
60
+ "58": "image/png",
61
+ "59": "image/svg+xml",
62
+ "60": "image/tiff",
63
+ "61": "image/vnd.adobe.photoshop",
64
+ "62": "image/vnd.microsoft.icon",
65
+ "63": "image/webp",
66
+ "64": "image/x-eps",
67
+ "65": "image/x-exr",
68
+ "66": "image/x-jp2-codestream",
69
+ "67": "image/x-portable-bitmap",
70
+ "68": "image/x-portable-greymap",
71
+ "69": "image/x-tga",
72
+ "70": "image/x-xpixmap",
73
+ "71": "inode/x-empty",
74
+ "72": "message/rfc822",
75
+ "73": "text/csv",
76
+ "74": "text/html",
77
+ "75": "text/plain",
78
+ "76": "text/rtf",
79
+ "77": "text/troff",
80
+ "78": "text/x-Algol68",
81
+ "79": "text/x-asm",
82
+ "80": "text/x-c",
83
+ "81": "text/x-c++",
84
+ "82": "text/x-diff",
85
+ "83": "text/x-file",
86
+ "84": "text/x-fortran",
87
+ "85": "text/x-java",
88
+ "86": "text/x-m4",
89
+ "87": "text/x-makefile",
90
+ "88": "text/x-msdos-batch",
91
+ "89": "text/x-perl",
92
+ "90": "text/x-php",
93
+ "91": "text/x-po",
94
+ "92": "text/x-ruby",
95
+ "93": "text/x-script.python",
96
+ "94": "text/x-shellscript",
97
+ "95": "text/x-tex",
98
+ "96": "text/xml",
99
+ "97": "video/3gpp",
100
+ "98": "video/mp4",
101
+ "99": "video/mpeg",
102
+ "100": "video/quicktime",
103
+ "101": "video/webm",
104
+ "102": "video/x-ivf",
105
+ "103": "video/x-matroska",
106
+ "104": "video/x-ms-asf",
107
+ "105": "video/x-msvideo"
108
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a3261fa9e328c33dacb5c5b25639d6d5014392f1bd13307c866bce39b0abf6c
3
+ size 169324736
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tokenizer_class": "PreTrainedTokenizerFast",
3
+ "model_max_length": 512,
4
+ "pad_token": "[PAD]",
5
+ "mask_token": "[MASK]",
6
+ "cls_token": "[CLS]",
7
+ "sep_token": "[SEP]",
8
+ "unk_token": "[UNK]"
9
+ }