知识讲堂

← 返回日报
算法理论 第一讲

哈希嵌入压缩

历史演进

嵌入矩阵的参数量与词表大小线性耦合,是大模型参数效率与端侧部署的根本瓶颈之一;哈希嵌入通过共享参数表和多重哈希组合,从信息论角度解耦了"词表规模"与"参数规模"。

2009
Feature Hashing 的诞生

Weinberger、Dasgupta、Langford 等人在 ICML 2009 提出 Feature Hashing(又称 Hashing Trick),将高维稀疏特征通过哈希函数映射到固定大小的向量空间。其核心洞察是:对于线性模型,只要哈希函数满足 2-universal 性质,内积的期望就不会因碰撞而产生系统偏差。这一工作源自垃圾邮件过滤和大规模文本分类的实际需求——当特征空间达到数百万维时,显式维护特征索引既浪费内存又增加工程复杂度。Hashing Trick 将 $O(|V|)$ 的索引空间压缩到 $O(B)$($B$ 为桶数),代价仅是少量随机碰撞带来的方差增大。这一思想后来被 Vowpal Wabbit、scikit-learn 的 HashingVectorizer 等工具广泛采纳,成为工业界处理高维稀疏特征的标准手段。

2017
Hash Embeddings 进入神经网络

Svenstrup、Winther 和 Hansen 在论文 "Hash Embeddings for Efficient Word Representations" 中首次将哈希思想系统性地引入神经网络嵌入层。他们的关键创新是使用 $k$ 个独立哈希函数,每个函数将 token 映射到一个共享嵌入表的不同行,然后通过可学习的重要性权重对 $k$ 个查找结果加权求和。这种设计的精妙之处在于:单个哈希函数的碰撞率为 $1/B$,但 $k$ 个独立哈希函数同时碰撞的概率降至 $(1/B)^k$,指数级降低了碰撞对表达能力的损害。实验表明,在情感分析等任务上,Hash Embeddings 用不到标准嵌入十分之一的参数即可达到相当的性能。

2018-2019
工业界的组合嵌入实践

Facebook(现 Meta)在推荐系统 DLRM 中面临极端的嵌入瓶颈——类别特征的词表可达数十亿。Shi 等人提出 Compositional Embedding(商余分解法),将 token ID 分解为商和余数,分别查两个小表再组合,本质上是一种结构化哈希。同期,Google 的 ALBERT(Lan 等人,2019)采用嵌入矩阵分解 $V \times d \to V \times e + e \times d$($e \ll d$),从矩阵低秩近似角度压缩嵌入。这些工作与哈希嵌入殊途同归,都在探索"如何用远少于 $V \times d$ 的参数表达 $V$ 个可区分的嵌入向量"。

2020-2023
深度哈希嵌入与理论深化

Kang 等人提出 DHE(Deep Hash Embedding),用多层 MLP 将哈希编码映射为嵌入向量,进一步增强了哈希嵌入的表达能力。理论方面,研究者开始从 Johnson-Lindenstrauss 引理和压缩感知的角度分析哈希嵌入的信息保持能力,证明在一定条件下,$O(\log V)$ 量级的哈希维度即可近似保持词间距离关系。

2026
MultiHashFormer 将哈希嵌入引入生成式语言模型

MultiHashFormer 证明哈希嵌入不仅适用于判别任务,在自回归生成中同样有效。通过精心设计的多哈希组合策略和输出层高效共享机制,生成质量与全参数嵌入模型相当,而嵌入参数量减少一个数量级以上,为大词表生成模型的轻量化部署开辟了新路径。

核心思想
用多个独立哈希函数将词表映射到共享的小参数表,通过加权组合多次查表结果消除碰撞歧义,以指数级降低碰撞概率为代价,将嵌入参数从 $O(Vd)$ 压缩到 $O(Bd)$($B \ll V$)。
数学结构

标准嵌入层为每个 token $t \in \{1,...,V\}$ 维护独立向量 $\mathbf{e}_t \in \mathbb{R}^d$,参数量为 $V \times d$。当 $V = 256{,}000$、$d = 4096$ 时,仅嵌入层就占约 4GB(FP32)。哈希嵌入的核心构造:维护一个共享参数表 $\mathbf{T} \in \mathbb{R}^{B \times d}$($B \ll V$),以及 $k$ 个独立哈希函数 $h_i: \{1,...,V\} \to \{1,...,B\}$。对 token $t$,其嵌入为:$\mathbf{e}(t) = \sum_{i=1}^{k} w_i(t) \cdot \mathbf{T}[h_i(t)]$,其中 $w_i(t)$ 是可学习的标量权重,$\mathbf{T}[h_i(t)]$ 表示从共享表中查找第 $h_i(t)$ 行。参数量从 $V \times d$ 降至 $B \times d + k \times V$(权重部分),当 $B \ll V$ 且 $k$ 较小时压缩比显著。碰撞分析:两个不同 token $t_1 \neq t_2$ 在单个哈希函数下碰撞的概率为 $P(h_i(t_1) = h_i(t_2)) = 1/B$。若 $k$ 个哈希函数相互独立,则所有函数同时碰撞的概率为 $P(\forall i: h_i(t_1) = h_i(t_2)) = (1/B)^k$。例如 $B = 1024, k = 3$ 时,完全碰撞概率约 $10^{-9}$。这意味着即使两个 token 在某个哈希函数上碰撞,它们在其他哈希函数上大概率映射到不同行,加权组合后的嵌入向量仍然可区分。梯度流方面,反向传播时 $\partial L / \partial \mathbf{T}[j]$ 累积来自所有映射到第 $j$ 行的 token 的梯度,这种梯度共享起到隐式正则化作用,防止低频 token 的嵌入过拟合。

工作机制

哈希嵌入的整体逻辑是:用哈希函数将"token → 嵌入"的一一映射替换为"token → 多个共享槽位 → 加权组合"的多对多映射,通过组合的唯一性恢复表达能力。

Step 1哈希函数族构建

选择 $k$ 个相互独立的哈希函数 $h_1, ..., h_k$,每个将 token ID 映射到 $\{1, ..., B\}$。实践中常用 MurmurHash、xxHash 等非密码学哈希函数,因为它们计算极快(纳秒级)且分布均匀。关键设计选择在于 $k$ 和 $B$ 的取值:$k$ 越大碰撞概率越低,但计算和内存开销线性增长;$B$ 越大共享程度越低,压缩比下降。经验法则是 $k \in [2, 4]$,$B$ 取 $V$ 的 1/10 到 1/100。为什么不用一个大表?因为多个小表通过组合产生的有效容量为 $B^k$(组合爆炸),远大于单个大小为 $kB$ 的表。

Step 2多路查表与组合

对输入 token $t$,并行计算 $k$ 个哈希值 $h_1(t), ..., h_k(t)$,从共享表 $\mathbf{T}$ 中查找 $k$ 个向量。组合方式有多种选择:(a) 加权求和 $\sum_i w_i \cdot \mathbf{T}[h_i(t)]$,最常用,保持维度不变;(b) 拼接后投影 $\text{Linear}([\mathbf{T}[h_1(t)]; ...; \mathbf{T}[h_k(t)]])$,表达能力更强但增加参数;(c) 逐元素乘积 $\prod_i \mathbf

长远价值
前沿动向

往期讲解档案 125 个知识点

2026年06月29日一致性蒸馏Consistency ModelsProgressive DistillationODE Trajectory
2026年06月29日原生推理引擎Native RuntimeggmlInference Engine
2026年06月28日无分类器引导Classifier-Free GuidanceGuidance ScaleScore Interpolation
2026年06月25日MVDR波束成形MVDR BeamformingSpatial FilteringCovariance Estimation
2026年06月24日神经缩放定律Scaling LawsCompute-Optimal TrainingPower Law
2026年06月23日最小贝叶斯风险解码Minimum Bayes RiskDecision TheoryHypothesis Selection
2026年06月23日PID控制与生成调控PID ControllerFeedback ControlClosed-loop Generation
2026年06月22日生成模型评估度量Frechet Inception DistanceGenerative EvaluationFeature Statistics
2026年06月21日浮点量化收缩偏差FP4 TrainingShrinkage BiasLow-Precision Arithmetic
2026年06月21日模型上线仿真Deployment SimulationShadow TestingOffline Evaluation
2026年06月20日现代联想记忆Hopfield NetworkAssociative MemoryEnergy-Based Model
2026年06月19日离散扩散语言模型Discrete DiffusionAbsorbing StateConcrete Score
2026年06月18日循环变换器架构Looped TransformerWeight TyingAdaptive Computation
2026年06月17日韵律建模演进Prosody PredictionF0 ModelingDuration Prediction
2026年06月16日说话人日志Speaker DiarizationSpeaker EmbeddingEEND
2026年06月15日偏好对齐优化Preference OptimizationDPOReward Modeling
2026年06月14日多令牌并行预测Multi-Token PredictionSpeculative DecodingParallel Decoding
2026年06月13日流匹配生成模型Flow MatchingRectified FlowOptimal Transport Path
2026年06月13日实时管线延迟预算Latency BudgetPipeline OrchestrationTime-to-First-Token
2026年06月12日MoE路由机制Mixture of ExpertsSparse GatingRouter Design
2026年06月11日连续自回归生成Continuous AutoregressiveLatent PredictionAudioVAE
2026年06月10日KV缓存压缩KV Cache CompressionToken EvictionAttention Sparsity
2026年06月09日浏览器端模型推理WebGPUBrowser InferenceClient-side ML
2026年06月02日残差向量量化Residual Vector QuantizationAudio TokenizationNeural Codec
2026年05月31日彩色噪声扩散采样Colored NoiseSpectral BiasSDE Solver
2026年05月31日算子融合编译原理Kernel FusionOperator Fusiontorch.compile
2026年05月20日AI生成内容溯源 (7 chars) ✓Content ProvenanceC2PASynthID
2026年05月19日推理委托设计模式 (8 chars) ✓ Let me now write the full content for both topics. Actually, I realize I should double-check: is "Runtime Abstraction" or "Delegate Pattern" too close to any covered keyword? Looking at the list: Cluster Scheduling, Co-design, Collective Communication, Computational Expressiveness, CUTLASS... No, none of these overlap. OK, let me finalize and write everything out. Let me reconsider the engineering topic one more time. The title "推理委托设计模式" is good but maybe I should make it even more specific and interesting. What about focusing on the "graph partitioning" aspect - how ML runtimes decide which operations to delegate to which backend? This is a more specific and technically interesting angle. No, I think the broader "delegate pattern" is better because it covers the full picture and is more useful to the reader. Let me write it all out now. For the engineering topic, let me think about the history: - Early days: frameworks were monolithic (Caffe, early TensorFlow) - TensorRT (2017): NVIDIA's specialized inference engine, initially standalone - ONNX Runtime (2019): Microsoft introduced "Execution Providers" - the first major delegate-like abstraction - TFLite delegates (2018-2019): TensorFlow Lite introduced delegate API for GPU, NNAPI, etc. - ExecuTorch (2023-2024): PyTorch's answer to edge inference with a clean delegate API - 2025-2026: MLX delegate, Qualcomm AI Engine Direct delegate, etc. This is a rich history. Let me write it up. Actually, I want to make sure I have the dates right: - TensorRT was first released around 2016-2017 - ONNX was announced in 2017 - ONNX Runtime was open-sourced in 2018-2019 - TFLite was released in 2017, delegates came later - ExecuTorch was announced at PyTorch Conference 2023 OK, let me write everything now. I'll be thorough. One more thought: for the MATH section of the engineering topic, I could discuss the graph partitioning problem formally, or I could discuss the cost model for deciding whether to delegate. Let me think... The graph partitioning for delegation can be formalized as: - Given a computation graph $G = (V, E)$ where $V$ is the set of operations and $E$ is data dependencies - And a set of delegates $D = \{d_1, ..., d_m\}$ where each delegate supports a subset of operations $S_i \subseteq V$ - Find a partition $P = \{P_0, P_1, ..., P_m\}$ (where $P_0$ is the fallback/CPU partition) that minimizes total execution time - Subject to: each $
2026年05月17日连续批处理异步化
2026年05月10日连续潜在扩散语言模型Continuous Latent DiffusionNon-autoregressive LMDiffusion Language Model
2026年05月10日零样本跨语言语音克隆Zero-shot Voice CloningCross-lingual TTSIPA Phoneme Representation
2026年05月09日最优传输音频距离Optimal TransportFréchet Audio DistanceRiemannian Metric
2026年05月09日推荐系统推理核内广播优化Intra-kernel BroadcastEmbedding TableRecommendation Inference
2026年05月08日扩散Transformer异常值令牌Outlier TokensDiffusion TransformerAttention Sink
2026年05月08日WebRTC低延迟语音工程WebRTCReal-time AudioJitter Buffer
2026年05月07日音素级深度伪造检测原理Phoneme-level Deepfake DetectionSelf-supervised Speech EmbeddingEmotional Speech Synthesis
2026年05月07日AI训练网络协议工程哲学Multi-path Reliable ConnectionRDMA over EthernetCollective Communication
2026年05月05日对抗解纠缠说话人验证Speaker DisentanglementAdversarial TrainingCross-lingual Verification
2026年05月05日LLM推理为何用语言Chain-of-ThoughtLatent ReasoningToken Space
2026年05月01日跨架构知识蒸馏原理Cross-Architecture DistillationDiffusion LMAutoregressive Teacher
2026年05月01日AI评估计算瓶颈工程LLM Evaluation InfrastructureBenchmark SaturationEval Compute Bottleneck
2026年04月29日平衡传输语音增强Schrödinger BridgeStochastic Differential EquationSpeech Enhancement
2026年04月29日深度学习理论形成Deep Learning TheoryLoss LandscapeNeural Tangent Kernel
2026年04月28日语义进度函数原理Semantic Progress FunctionDiffusion TrajectoryNonlinear Denoising
2026年04月28日大模型OCR选型认知OCR BenchmarkModel Selection BiasCost-Performance Tradeoff
2026年04月27日说话人验证核心原理Speaker Verificationd-vectorECAPA-TDNN
2026年04月27日GPU核函数语言选型GPU Kernel EngineeringCuTe DSLCUTLASS
2026年04月26日时长控制TTS原理Duration ModelingProsody ControlAutoregressive TTS
2026年04月26日AI研究价值评估困境Research EvaluationPublication BiasPeer Review
2026年04月25日全双工对话建模原理Full-Duplex DialogueTurn-TakingVoice Activity Detection
2026年04月25日流式TTS文本规范化Text NormalizationStreaming TTSInverse Text Normalization
2026年04月24日离散扩散语言模型原理Discrete DiffusionMasked Diffusion Language ModelAbsorbing Diffusion
2026年04月24日跟进ML研究的认知工程Information OverloadResearch TriageSpaced Repetition
2026年04月23日一致性正则化ASR原理Consistency RegularizationUnified ASRTransducer
2026年04月23日流式TTS文本规范化工程Text NormalizationStreaming TTSInverse Text Normalization
2026年04月22日神经编码器伪影检测Neural Audio CodecArtifact DetectionForensic Residual
2026年04月22日AI研究复现危机工程Reproducibility CrisisML EngineeringExperimental Rigor
2026年04月21日扩散SNR偏差校正原理Signal-to-Noise RatioDiffusion Timestep BiasScore Matching
2026年04月21日论文复现危机根治工程Reproducibility CrisisAblation StudyExperimental Rigor
2026年04月20日音频时序定位原理Temporal GroundingAudio Event DetectionCross-modal Alignment
2026年04月20日论文复现危机根因Reproducibility CrisisBenchmark OverfittingEvaluation Validity
2026年04月19日流匹配对齐原理Flow Matching AlignmentReward Gradient BackpropagationTrajectory Optimization
2026年04月19日分布式训练任务编排Distributed Training OrchestrationCluster SchedulingFault Tolerance
2026年04月18日最优传输信号融合Optimal TransportWasserstein BarycenterTime-Frequency Resolution
2026年04月18日分布式训练任务调度Distributed Training OrchestrationJob SchedulingCluster Resource Management
2026年04月17日扩散语音识别原理Masked Diffusion Language ModelDiscrete DiffusionASR Decoding
2026年04月17日Mel尺度跨文化偏差Mel ScalePsychoacousticsCultural Bias
2026年04月16日音频水印对抗原理Audio WatermarkingSemi-FragilePsychoacoustic Masking
2026年04月16日推测解码草稿树工程Speculative DecodingDraft TreeBlock Diffusion
2026年04月15日对抗流模型原理Continuous Normalizing FlowAdversarial TrainingFlow Matching
2026年04月15日代理状态可观测性工程Agent ObservabilityDistributed TracingState Machine Debugging
2026年04月14日过程奖励模型原理Process Reward ModelStep-level SupervisionReasoning Chain
2026年04月13日离散令牌音源分离Discrete Token ModelingSource SeparationConditional Generation
2026年04月13日超算API工程哲学Distributed Training OrchestrationSupercomputer API DesignFault Tolerance
2026年04月12日信息瓶颈原理演进Information BottleneckVariational IBDisentanglement
2026年04月12日Safetensors格式工程哲学SafetensorsModel SerializationMemory-Mapped IO
2026年04月11日归一化层演进原理Layer NormalizationRMS NormalizationBatch Normalization
2026年04月11日GEMM自调优后端工程GEMM AutotuningTorchInductorCuteDSL
2026年04月10日多令牌预测原理Multi-Token PredictionSpeculative DecodingMedusa Heads
2026年04月10日ML从业者认知校准Calibration BiasCapability IllusionBenchmark Overfitting
2026年04月09日编码器-解码器LM原理Encoder-Decoder LMCross-Attention ConditioningSequence-to-Sequence
2026年04月09日torch.compile归一化优化torch.compileLayerNormRMSNorm
2026年04月08日KV缓存压缩原理KV Cache CompressionRoPE Position EncodingAttention Score Estimation
2026年04月08日音效基础模型工程Sound Effect GenerationFoundation ModelFoley Synthesis
2026年04月07日可验证奖励强化学习Verifiable RewardRLVRProcess Reward Model
2026年04月07日LLM技能退化认知机制Cognitive OffloadingSkill AtrophyDesirable Difficulty
2026年04月06日音素可解释说话人验证Phoneme-aware Speaker VerificationInterpretable BiometricsLocal Acoustic Evidence
2026年04月06日音频幻觉攻击评估Hallucination AttackAudio Language Model ReliabilityAdversarial Probing
2026年04月05日潜在空间推理原理Latent Space ReasoningContinuous RepresentationToken-Free Inference
2026年04月05日mRNA模型极低成本训练Biology Foundation ModelCross-Species TransferLow-Budget Training
2026年04月04日编码器-解码器TTS原理Encoder-Decoder TTSText ConditioningPositional Capacity
2026年04月04日大模型训练的MXFP8工程MXFP8MicroscalingMixed Precision Training
2026年04月03日在线知识蒸馏原理Online DistillationKnowledge TransferStudent-Teacher
2026年04月03日MoE专家并行调度工程Expert ParallelismMixture of ExpertsAll-to-All Communication
2026年04月02日波形潜空间扩散TTSwaveform latent diffusionnon-autoregressive TTSlatent space acoustic modeling
2026年04月02日波形隐空间扩散原理waveform latent spacediffusion TTSVAE audio codec
2026年04月02日LLM量化权重工程weight quantizationLLM compression4-bit quantization
2026年04月02日扩散语言模型离散生成Discrete DiffusionMasked Diffusion Language ModelNon-autoregressive TTS
2026年04月02日LLM后训练库工程演进RLHF engineeringPPO training stabilityreward hacking
2026年04月02日声学证据瓶颈原理Audio Evidence BottleneckAcoustic GroundingAudio Language Model
2026年04月02日状态空间模型音频建模State Space ModelMambaSelective Scan
2026年04月02日实时语音增强工程选型Real-time Speech EnhancementNoise SuppressionStreaming Inference
2026年04月02日对话上下文压缩原理Context CompressionAbstractive SummarizationCross-Attention Fusion
2026年04月02日说话人匿名化工程Speaker AnonymizationVoice ConversionStreaming Inference
2026年04月02日视听语音识别融合Audio-Visual Speech RecognitionLip ReadingViseme
2026年04月02日GPU训练吞吐加速工程MXFP8MoE TrainingExpert Parallelism
2026年04月01日熵驱动多样性生成diversity samplingtypicality biasrepulsion in latent space
2026年04月01日说话人分割工程选型speaker diarizationbenchmark methodologystreaming ASR pipeline
2026年03月31日转向检测联合建模turn-taking detectionvoice activity detectionjoint acoustic-linguistic modeling
2026年03月31日基准测试的系统性失效benchmark contaminationevaluation validityLLM judge reliability
2026年03月31日扩散模型声学生成diffusion modelscore matchingstochastic differential equation
2026年03月31日TTS开源生态竞争open-weight TTStime-to-first-audiomultilingual speech synthesis
2026年03月30日注意力机制变体演进Multi-Head AttentionGrouped Query AttentionMulti-head Latent Attention
2026年03月30日设备端语音推理架构on-device inferenceExecuTorchvoice agent pipeline
2026年03月29日混合自回归流匹配TTSautoregressive semantic tokensflow matching acoustic decoderhybrid TTS architecture
2026年03月29日NCCL超时诊断方法论NCCL watchdog timeoutdistributed training debuggingcollective communication
2026年03月29日混合架构音频表示Mambastate space modelaudio representation learning
2026年03月29日DeepSeek预训练加速工程MXFP8 trainingexpert parallelismMoE pretraining
2026年03月27日说话人验证度量学习speaker verificationmetric learningcurriculum learning
2026年03月27日MX浮点格式加速训练MXFP8microscalingmixed precision training
2026年03月26日TTS模型极限压缩model compressionknowledge distillationTTS on-device
2026年03月26日小模型极限压缩哲学model compressionknowledge distillationquantization
2026年03月25日流匹配生成原理flow matchingrectified flowODE
2026年03月25日神经音频编解码器neural audio codecresidual vector quantizationEnCodec
2026年03月25日推测解码加速推理speculative decodingdraft modeltoken verification