Howwise RSS
AI & Automation5 min read

HuggingFace Embedding Dimensions: How to Find Any Model's Size

Short answer

HuggingFace embedding dimensions are best found with model.get_sentence_embedding_dimension() for sentence-transformers models, or by embedding one test string and calling len() on the result. Config hidden_size is only a hint.

Key takeaways
  • Call model.get_sentence_embedding_dimension() for sentence-transformers models, and fall back to len(model.encode('test')) for anything else.
  • config.json hidden_size is the per-token size and equals the final output only when pooling adds no projection or concatenation.
  • Dense layers (modules.json, 2_Dense/config.json out_features), CLIP projection_dim and Matryoshka truncation can all change the final size.
  • Derive the dimension in code and pass it to FAISS, Pinecone, Qdrant or pgvector instead of hardcoding it.
  • Storage is 4 bytes per dimension per vector in float32, so 1M vectors at 1024 dimensions need about 4.1 GB before index overhead.

What is the fastest way to find a Hugging Face embedding dimension?

Work in this order: library method, then config, then a test embedding. The first two are quick, and the third always works because it measures what the model actually returns.

For any sentence-transformers model, the library reports the output size directly. This reflects the whole pipeline (transformer, pooling and any Dense layer), so it is the number your vector store needs.

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
print(model.get_sentence_embedding_dimension())   # 384
print(len(model.encode("test")))                  # 384 (universal check)
print(model.encode(["a", "b"]).shape)             # (2, 384)
Tip: The test embedding is the ground truth. If the library method, the config and the model card disagree, trust the length of an actual vector.

Can I read the dimension from config.json without downloading weights?

Yes. AutoConfig fetches only config.json, a few kilobytes, so you can inspect large models cheaply. The same file is visible on the model's Files tab on the Hub.

The field you want is usually hidden_size (some architectures use d_model, n_embd or dim instead). It is the width of each token vector coming out of the transformer, before pooling.

This is only the final answer when the model uses plain mean or CLS pooling and no extra layers.

from transformers import AutoConfig

cfg = AutoConfig.from_pretrained("BAAI/bge-base-en-v1.5")
print(cfg.hidden_size)   # 768

# CLIP-style models expose a separate projection size
cfg = AutoConfig.from_pretrained("openai/clip-vit-base-patch32")
print(cfg.projection_dim)   # 512 (the embedding), not text_config.hidden_size

Why is hidden_size sometimes not the embedding size?

hidden_size describes the transformer body. Anything applied after it can change the vector you actually store. Four cases cause most surprises.

Plain BERT is also not an embedding model: it returns one vector per token, and nothing defines a sentence vector until you add pooling.

CaseWhat changesWhere to look
Dense / projection layerA linear layer maps hidden_size to out_features (for example 1024 to 768)modules.json lists the modules; 2_Dense/config.json has out_features
CLIP-style projectionText and image towers are projected into a shared space of projection_dimconfig.json projection_dim
Concatenated poolingConcatenating CLS and mean, or several layers, multiplies the size (768 x 2 = 1536)1_Pooling/config.json pooling flags
Matryoshka truncationYou or the default config cut the vector to a shorter prefixtruncate_dim argument, model card
Warning: Allocating an index from hidden_size on a model with a Dense layer produces a mismatch error on the first insert. Verify with a real embedding before creating production indexes.

What are the dimensions of popular Hugging Face embedding models?

The values below are the default output sizes for the common checkpoints. Variants (for example v1.5, multilingual or quantized builds) usually keep the size, but confirm on the model card or with a test embedding.

ModelDimension
all-MiniLM-L6-v2384
all-mpnet-base-v2768
bge-small-en384
bge-base-en768
bge-large-en1024
e5-base768
e5-large1024
gte-large1024
nomic-embed-text-v1768
bert-base (needs pooling)768
bert-large (needs pooling)1024
Tip: The model card and the MTEB leaderboard list embedding dimensions, so you can read the number without loading anything.

How do I pass the dimension to FAISS, Pinecone, Qdrant and pgvector?

Compute the dimension once from the loaded model and reuse the variable. Hardcoding 1536, the OpenAI value copied from many tutorials, is a classic mistake when the model is actually 384 or 768.

Chroma needs no value because it infers the size from the first batch you add.

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("BAAI/bge-base-en-v1.5")
dim = model.get_sentence_embedding_dimension()

# FAISS
import faiss
index = faiss.IndexFlatL2(dim)

# Pinecone
from pinecone import Pinecone, ServerlessSpec
pc = Pinecone(api_key="...")
pc.create_index(name="docs", dimension=dim, metric="cosine",
                spec=ServerlessSpec(cloud="aws", region="us-east-1"))

# Qdrant
from qdrant_client import QdrantClient
from qdrant_client.models import VectorParams, Distance
client = QdrantClient(":memory:")
client.create_collection("docs",
    vectors_config=VectorParams(size=dim, distance=Distance.COSINE))

# pgvector (SQL built from the variable)
sql = f"CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector({dim}));"

# LangChain fallback
from langchain_huggingface import HuggingFaceEmbeddings
emb = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
dim = len(emb.embed_query("x"))

What happens when the dimensions do not match?

Index and query vectors must have exactly the same length. Stores reject mismatches rather than guess, and changing models means re-embedding every document and recreating the index, because vectors from different models are not comparable even at equal size.

Typical errors look like these:

StoreTypical message
FAISSAssertionError: d == self.d
PineconeVector dimension 384 does not match the dimension of the index 1536
pgvectorexpected 768 dimensions, not 384
QdrantVector dimension error: expected dim: 768, got 384
  1. Compute the new model's dimension from a real embedding.
  2. Create a new index or collection with that size (do not alter the old one in place).
  3. Re-embed the whole corpus with the new model and load it.
  4. Switch queries to the new model and index together, then delete the old index.
Warning: Deleting the old index before the new one is fully loaded causes downtime and data loss risk. Keep both until verified.

Should I shrink dimensions with Matryoshka truncation, and what does it cost?

Matryoshka-trained models (such as nomic-embed-text-v1.5, mxbai-embed-large and several jina models) pack the most information into the first dimensions, so a prefix stays useful. Pass truncate_dim to sentence-transformers and check the result. Models not trained this way lose quality quickly when truncated.

Re-normalise after truncating, since cutting a unit vector leaves it shorter than 1, which affects dot-product and L2 results.

Storage is dim x 4 bytes in float32. For 1M vectors: 384 dims is about 1.5 GB, 768 about 3.1 GB, 1024 about 4.1 GB and 1536 about 6.1 GB, before index overhead such as HNSW links. Higher dimensions also slow search roughly in proportion, usually for modest quality gains.

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("nomic-ai/nomic-embed-text-v1.5",
                            trust_remote_code=True, truncate_dim=256)
vec = model.encode(["hello"], normalize_embeddings=True)
print(vec.shape)   # (1, 256)

# manual: truncate then re-normalise
import numpy as np
full = np.random.rand(1, 768)
v = full[:, :256]
v = v / np.linalg.norm(v, axis=1, keepdims=True)
Tip: Set truncate_dim at load time and derive the store dimension from get_sentence_embedding_dimension(), which then reports the truncated size.

Common questions

How do I get the embedding size with plain Transformers?

Run the model, pool the token outputs, and read the last axis of the pooled result. For mean or CLS pooling, outputs.last_hidden_state.shape[-1] gives the size, but if you add a projection or concatenate pooled vectors, measure the final tensor instead.

Does the embedding dimension depend on input length?

No. Token count changes the sequence axis of last_hidden_state, but pooling collapses it, so every text yields a vector of the same length. Longer inputs only matter for the model's maximum sequence length.

Is a higher embedding dimension always better?

No. Quality gains between 384 and 1024 dimensions are often modest and task dependent, while memory, index build time and query latency grow with size. Compare candidates on your own retrieval data before paying for the larger vectors.

Can I use a different embedding model for queries than for documents?

Not for ordinary symmetric search. Both sides must use the same model, the same dimension and the same prefixes (such as the query: and passage: prefixes of e5), otherwise similarity scores are meaningless.

Related topics:embeddingshuggingfacevector-databasesentence-transformers