Mizan-optimized embedding model training
Project description
mizan-embedder
Mizan-optimized Embedding Models for AI, Search, and RAG.
mizan-embedder is the official embedding-model library in the Mizan ecosystem, designed to create scale-aware, noise-resistant, and proportionally accurate embeddings trained using the Mizan Balance Function.
Proposed & Developed By:
Ahsan Shaokat โ Computer Scientist & AI/ML Researcher
Inventor of the Mizan Balance Function (2025)
๐ Overview
Modern embedding systems (MiniLM, MPNet, E5, etc.) use cosine similarity, which:
- โ Ignores magnitude
- โ Fails with noisy or multi-scale embeddings
- โ Produces unstable rankings in RAG
- โ Forces L2-normalization (losing information)
Mizan-Embedder fixes this by training models specifically for:
- โ Mizan similarity (scale-aware)
- โ Proportional contrastive learning
- โ Chunk-length stable retrieval
- โ Large document embeddings
- โ Multimodal (text + images)
This library enables you to build your own embedding models, optimized for the mizan_vector search engine.
๐ฆ Features
๐ง MizanEmbeddingModel-v1
- Transformer backbone (DistilBERT, MiniLM, BERT, or any HF model)
- Projection head to target embedding dimension (e.g., 384)
- Supports
mean,cls, andmaxpooling - Optional L2 normalization (usually disabled for Mizan)
๐งฐ Utilities Included
- Dataset utilities for contrastive text pairs
- Collate function for fast tokenization
- Inference wrapper (
MizanTextEncoderWrapper) - Example training script (
train_text_contrastive.py)
๐ Integrates Seamlessly With:
mizan_vector(Memory store + Postgres pgvector)mizan-rag(retrieval pipelines)- Any Python ML workflow
๐ Project Structure
mizan-embedder/ โ โโโ mizan_embedder/ โ โโโ init.py โ โโโ model.py # MizanEmbeddingModel + inference wrapper โ โโโ data.py # Dataset + collate functions โ โโโ train_text_contrastive.py # Example training script โโโ pyproject.toml # PyPI-ready config โโโ README.md โโโ LICENSE
โ๏ธ Installation
From local repo:
pip install -e .
๐งฑ Architecture
๐น MizanEmbeddingModel
A transformer-based encoder with:
Backbone (HuggingFace model)
Projection layer โ [hidden_size] โ [embedding_dim]
Pooling (mean, cls, max)
Normalization (optional)
Diagram:
mathematica
Input Text โ Tokenizer โ Transformer Backbone โ Pooling โ Projection โ Embedding
๐น Why Projection?
To unify embedding dimensions across:
text models
code models
multimodal models
future Mizan models
๐ Usage
๐น Load the encoder
from mizan_embedder.model import MizanTextEncoderWrapper
encoder = MizanTextEncoderWrapper(
backbone_name="distilbert-base-uncased",
emb_dim=384,
pooling="mean",
normalize=False, # Mizan works best without normalization
)
vector = encoder.encode_one("Mizan is a scale-aware similarity function.")
print(vector.shape)
๐งช Training Your First Mizan Encoder
Use the provided script:
python train_text_contrastive.py
This script:
Loads text pairs
Tokenizes them
Trains with MizanContrastiveLoss
Prints loss per epoch
Example Training Code (simplified)
from mizan_embedder.model import MizanEmbeddingModel
from mizan-vector.losses import MizanContrastiveLoss
model = MizanEmbeddingModel(
backbone_name="distilbert-base-uncased",
emb_dim=384,
pooling="mean",
)
loss_fn = MizanContrastiveLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)
for enc1, enc2, labels in loader:
emb1 = model(**enc1)
emb2 = model(**enc2)
loss = loss_fn(emb1, emb2, labels)
loss.backward()
optimizer.step()
๐ Contrastive Dataset Format
Your dataset should consist of (text1, text2, label) pairs:
Label = 1 โ similar
Label = 0 โ not similar
Example:
pairs = [
("what is mizan?", "mizan is a scale-aware similarity function", 1),
("who invented mizan?", "Ahsan Shaokat proposed the Mizan Balance Function", 1),
("cosine similarity", "apples are fruit", 0),
]
Dataset loader handles this automatically.
๐ค Inference: Encoding Many Sentences
texts = [
"Mizan is scale-aware.",
"Cosine ignores magnitude.",
"Apples are fruit.",
]
embs = encoder.encode(texts)
print(embs.shape) # e.g. torch.Size([3, 384])
๐ Integrating With mizan-vector
Example: full semantic search pipeline
from mizan-vector import MizanMemoryStore
from mizan_embedder.model import MizanTextEncoderWrapper
encoder = MizanTextEncoderWrapper()
store = MizanMemoryStore(dim=384)
docs = [
"Mizan Balance Function is scale-aware.",
"Cosine similarity uses only angle.",
"Ahsan Shaokat invented Mizan.",
]
embs = encoder.encode(docs)
for doc, emb in zip(docs, embs):
store.add_document(content=doc, embedding=emb.tolist())
query = "who created the mizan function?"
q_emb = encoder.encode_one(query).tolist()
results = store.search(q_emb, top_k=3, metric="mizan")
for r in results:
print(r.score, r.content)
๐ฅ Why Use Mizan-Based Embeddings?
Problem in Cosine Models Mizan Solution
Loses magnitude info Keeps scale meaningfully
Sensitive to noise/outliers Proportional + stable
Long chunks score lower Corrects length bias
Normalized embeddings only No normalization needed
RAG retrieval unstable Stable across chunk sizes
Cosine โ semantic meaning Mizan captures proportional similarity
Mizan-optimized embeddings simply behave more naturally for real-world retrieval.
๐บ๏ธ Roadmap
Next Versions:
โ MizanTextEncoder-base-384
STS/NLI-trained
Released in mizan-models
โ MizanCodeEncoder-base
CodeBERT-based
Code โ docstring training
โ MizanMultimodalEncoder-v1
CLIP-based
Image โ text contrastive training
โ mizan-rag
Full retrieval pipeline (chunking โ embedding โ storing โ LLM answering)
๐ License
MIT License
ยฉ 2025 Ahsan Shaokat
๐ Acknowledgements
Special thanks to:
HuggingFace transformers
pgvector open-source community
PyTorch developers
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mizan_embedder-0.3.1.tar.gz.
File metadata
- Download URL: mizan_embedder-0.3.1.tar.gz
- Upload date:
- Size: 8.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fd588407040f228e1cc90c4ead678bddbdd9365a2f65e0ba715543ff7b8ca83b
|
|
| MD5 |
b0ecbb9a4d9514e25e5328b92fd23e74
|
|
| BLAKE2b-256 |
22e1cff716d8d44c6fddf8da4c13ffa187ec8ea72fe70c19237b6f3f87b923d5
|
File details
Details for the file mizan_embedder-0.3.1-py3-none-any.whl.
File metadata
- Download URL: mizan_embedder-0.3.1-py3-none-any.whl
- Upload date:
- Size: 7.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9b7e3bb4a62b86465c5c754c2664bfc0e7ecb31e54c49c73040cd7c48d306608
|
|
| MD5 |
44d1bfa8612944926d777e7dfa3168ff
|
|
| BLAKE2b-256 |
e4f3d5701a28ab71e0648ef9ad3c230aca49fa7c623118740a47ee6e6a6e716d
|