Matryoshka Representation Learning (MRL)
了解 Matryoshka 表示学习 (MRL) 如何实现多粒度嵌入。探索如何优化 Ultralytics YOLO26 的搜索和边缘部署。
Matryoshka Representation Learning (MRL) 是一种在人工智能 (AI) 和 机器学习 (ML) 领域中使用的训练技术,它强制神经网络在单个输出向量内学习多粒度嵌入 (embeddings)。受俄罗斯套娃的启发,MRL 对嵌入进行了结构化设计,使得重要的语义信息被优先置于前端。这意味着一个高维向量(例如 1024 维)可以被截断为更小的嵌套子集(如 512、256 或 64 维),而不会丢失其底层表示。这种灵活性极大地降低了通常与信息检索任务相关的计算开销。
Link to this sectionMatryoshka Representation Learning 的工作原理#
传统上,嵌入模型被训练用于针对固定输出大小优化特定的损失函数 (loss function)。如果系统需要更小的向量以节省内存,则必须训练一个全新的模型。MRL 通过在训练阶段应用嵌套损失函数解决了这个问题。它同时优化完整表示及其嵌套子集。像 OpenAI 这样已采用 MRL 用于其现代嵌入 API 的组织,允许开发者在保留准确的余弦相似度 (cosine similarity) 分数的同时,动态地从向量末端去除维度。
Link to this section实际应用#
在平衡准确性与存储成本及内存带宽 (memory bandwidth) 时,MRL 提供了显著优势。
- 面向 LLM 的自适应向量搜索: 在检索增强生成 (RAG) 流水线中,大语言模型 (LLMs) 通常依赖于庞大的向量数据库 (vector databases)。利用 MRL,企业可以使用嵌入的前 64 个维度执行快速、粗略的语义搜索 (semantic search),然后使用完整的 1024 维向量对排名靠前的结果进行重排。这种两步法极大地加速了向量搜索 (vector search) 并降低了数据库存储成本。
- Scalable Computer Vision at the Edge: When deploying computer vision systems using the Ultralytics Platform, hardware constraints can vary wildly. A model utilizing MRL can transmit full-sized visual embeddings to a powerful cloud deployment server, but gracefully fall back to transmitting truncated 128-dimensional embeddings when operating on low-power edge computing devices, optimizing latency without retraining the model.
Link to this section区分相关概念#
为了正确使用 MRL,将其与用于压缩数据的旧技术区分开来会有所帮助。
- MRL 与 降维 (Dimensionality Reduction) 的对比: 像 PCA(主成分分析)或 t-SNE 这样的算法是在训练之后应用以压缩数据的。相比之下,MRL 原生地内置于训练期间的神经网络架构中,从而保留了更深层的非线性关系。
- MRL 与 模型剪枝 (Model Pruning) 的对比: 剪枝会从实际的神经网络中移除权重和层以加快推理速度,例如创建 Ultralytics YOLO 模型的小型变体。MRL 不会改变模型大小;它只会改变模型产生的输出向量的大小。
Link to this section实际实施#
Truncating an MRL embedding is incredibly straightforward and requires no complex semantic indexing logic. Because the most critical features are heavily weighted in the earliest dimensions, you can simply slice the array. The following example demonstrates truncating a simulated YOLO26 multi-modal output using basic PyTorch tensor operations.
import torch
# Simulate a full 1024-dimensional MRL embedding returned by a model
full_embedding = torch.rand(1, 1024)
# To deploy on memory-constrained hardware, simply slice the first 256 dimensions
# Because the model was trained with MRL, this subset remains highly accurate
truncated_embedding = full_embedding[:, :256]
print(f"Original size: {full_embedding.shape[1]}, Compressed size: {truncated_embedding.shape[1]}")





