Downloads · 30 days
34
18% of all-time downloads
mjbommar/magic-bert-50m-roformer-classification
magic-bert-50m-roformer-classification is a text classification model from mjbommar. Use it when you need a label for a piece of text. It is set up for transformers. The card lists the license as apache-2.0.
A RoFormer-based transformer model fine-tuned for binary file type classification. This model achieves 93.7% classification accuracy across 106 MIME types, making it the recommended choice for production file type det…
Downloads · 30 days
34
18% of all-time downloads
All-time downloads
193
Public
Parameters
42.5M
341 MB on disk
Likes
0
Public
Click a slice to open those files.
.safetensors172 MB · 99%
From the Hugging Face model README
A RoFormer-based transformer model fine-tuned for binary file type classification. This model achieves 93.7% classification accuracy across 106 MIME types, making it the recommended choice for production file type detection.
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:
This model extends magic-bert-50m-roformer-mlm with contrastive learning fine-tuning. It uses Rotary Position Embeddings (RoPE) and produces highly discriminative embeddings for file type classification.
| Property | Value |
|---|---|
| Parameters | 42.0M (+ 0.45M classifier head) |
| Hidden Size | 512 |
| Projection Dimension | 256 |
| Number of Classes | 106 MIME types |
| Base Model | magic-bert-50m-roformer-mlm |
| Position Encoding | RoPE (Rotary Position Embeddings) |
The tokenizer uses the Binary BPE methodology introduced in Bommarito (2025). The original Binary BPE tokenizers (available at 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.
Primary use cases:
This is the recommended model for file classification tasks due to its combination of high accuracy (93.7%) and parameter efficiency (42M parameters).
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. Classification embeddings can identify file types from interior content.
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.
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.
The embedding space (256-dimensional, L2-normalized) enables similarity search across file collections: "find files structurally similar to this sample" for malware clustering, duplicate detection, or content-based retrieval.
This model uses Rotary Position Embeddings (RoPE), which encode position through rotation matrices in attention. This differs from the Magic-BERT variant which uses absolute position embeddings.
| Metric | RoFormer (this) | Magic-BERT |
|---|---|---|
| Classification Accuracy | 93.7% | 89.7% |
| Silhouette Score | 0.663 | 0.55 |
| F1 (Weighted) | 0.933 | 0.886 |
| Parameters | 42.5M | 59M |
| Fill-mask Retention | 14.5% | 41.8% |
This model achieves higher classification accuracy with fewer parameters, making it the preferred choice for production deployment when only classification is needed.
This is the Phase 2 (Classification) model built on RoFormer. The training pipeline has two phases:
| Phase | Model | Task | Purpose |
|---|---|---|---|
| Phase 1 | magic-bert-50m-roformer-mlm | Masked Language Modeling | Learn byte-level patterns and file structure |
| Phase 2 | This model | Contrastive Learning | Optimize embeddings for file type discrimination |
| Phase | Steps | Learning Rate | Objective |
|---|---|---|---|
| 1: MLM Pre-training | 100,000 | 1e-4 | Masked Language Modeling |
| 2: Contrastive Fine-tuning | 50,000 | 1e-6 | Supervised Contrastive Loss |
Phase 2 specifics:
| Metric | Value |
|---|---|
| Linear Probe Accuracy | 93.7% |
| F1 (Macro) | 0.829 |
| F1 (Weighted) | 0.933 |
| Metric | Value |
|---|---|
| Silhouette Score | 0.663 |
| Separation Ratio | 4.00 |
| Intra-class Distance | 7.24 |
| Inter-class Distance | 28.98 |
The silhouette score of 0.663 indicates well-separated clusters, suitable for embedding-based retrieval and similarity search.
| Metric | Phase 1 | Phase 2 | Change |
|---|---|---|---|
| Probing Accuracy | 85.0% | 93.7% | +8.7% |
| Silhouette Score | 0.328 | 0.663 | +102% |
| Separation Ratio | 2.65 | 4.00 | +51% |
The model classifies files into 106 MIME types across these categories:
| Category | Count | Examples | Typical Accuracy |
|---|---|---|---|
| application/ | 41 | PDF, ZIP, GZIP, Office docs, executables | >90% |
| text/ | 24 | Python, C, Java, HTML, XML, shell scripts | >80% |
| image/ | 18 | PNG, JPEG, GIF, WebP, TIFF, PSD | >95% |
| video/ | 9 | MP4, WebM, MKV, AVI, MOV | >90% |
| audio/ | 8 | MP3, FLAC, WAV, OGG, M4A | >90% |
| font/ | 3 | SFNT, WOFF, WOFF2 | >85% |
| other | 3 | biosig/atf, inode/x-empty, message/rfc822 | varies |
application/ (41 types):
text/ (24 types):
image/ (18 types):
video/ (9 types):
audio/ (8 types):
font/ (3 types):
other (3 types):
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
model = AutoModelForSequenceClassification.from_pretrained(
"mjbommar/magic-bert-50m-roformer-classification", trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained("mjbommar/magic-bert-50m-roformer-classification")
model.eval()
# Classify a file
with open("example.pdf", "rb") as f:
data = f.read(512)
# Decode bytes to string using latin-1 (preserves all byte values 0-255)
text = data.decode("latin-1")
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
with torch.no_grad():
outputs = model(**inputs)
predicted_id = outputs.logits.argmax(-1).item()
confidence = torch.softmax(outputs.logits, dim=-1).max().item()
print(f"Predicted class: {predicted_id}")
print(f"Confidence: {confidence:.2%}")
# Get normalized embeddings (256-dim, L2-normalized)
with torch.no_grad():
embeddings = model.get_embeddings(inputs["input_ids"], inputs["attention_mask"])
# embeddings shape: [batch_size, 256]
# Compute cosine similarity
similarity = torch.mm(embeddings1, embeddings2.T)
from huggingface_hub import hf_hub_download
import json
mime_path = hf_hub_download("mjbommar/magic-bert-50m-roformer-classification", "mime_type_mapping.json")
with open(mime_path) as f:
id_to_mime = {int(k): v for k, v in json.load(f).items()}
print(f"Predicted MIME type: {id_to_mime[predicted_id]}")
MLM capability sacrificed: Fill-mask accuracy drops to 14.5% after classification fine-tuning. Use the MLM variant if byte prediction is needed.
Position bias: Still present (~46% accuracy drop at offset 1000), though less relevant for classification than for fill-mask tasks.
Ambiguous formats: ZIP-based formats (DOCX, XLSX, JAR, APK) share similar structure and may be confused.
Rare types: Lower accuracy on underrepresented file types in training data.
| Use Case | Recommended Model | Reason |
|---|---|---|
| Production classification | This model | Highest accuracy (93.7%), efficient (42M params) |
| Classification + fill-mask | magic-bert-50m-classification | Retains 41.8% fill-mask capability |
| Fill-mask / byte prediction | magic-bert-50m-roformer-mlm | Optimized for MLM |
| Research baseline | magic-bert-50m-mlm | Best perplexity (1.05) |
This model builds on the Binary BPE tokenization approach:
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.
A paper describing Magic-BERT, the training methodology, and the dataset is forthcoming.
@article{bommarito2025binarybpe,
title={Binary BPE: A Family of Cross-Platform Tokenizers for Binary Analysis},
author={Bommarito, Michael J., II},
journal={arXiv preprint arXiv:2511.17573},
year={2025}
}