不“怎么”增加模型计算开销的情况下,提升模型的体积
模型总参数量不变的情况下,降低每次推理的计算开销(所用参数)
一种"weighted multiplication"
为了体现稀疏性,一般选Top-k Gating
Switch Transformers将Transformers中的FFN替换为MoE结构

| 模型 | #Experts | top-k数量 | 备注 |
|---|---|---|---|
| Mixtral 8x22B | 8 | 2 | 专家更大,推理仍保持稀疏 |
| DeepSeek-V3 (670B A37B) | 256+1 | 8+1 | 开源中文 MoE,提供高效推理规模 |
| Qwen3-235B-A22B | 128 | 8 | 阿里开源 |

(mlp): LlamaMLP(
(gate_proj): Linear(in_features=2048, out_features=8192, bias=False)
(up_proj): Linear(in_features=2048, out_features=8192, bias=False)
(down_proj): Linear(in_features=8192, out_features=2048, bias=False)
(act_fn): SiLU()
)
import torch
import torch.nn as nn
class TopKGating(nn.Module):
def __init__(self, hidden_dim, num_experts, k=2):
super().__init__()
self.router = nn.Linear(hidden_dim, num_experts, bias=False)
self.k = k
def forward(self, x):
scores = self.router(x) # [batch, experts]
topk_scores, topk_idx = torch.topk(scores, self.k, dim=-1)
probs = torch.softmax(topk_scores, dim=-1)
gate = torch.zeros_like(scores)
gate.scatter_(-1, topk_idx, probs)
return gate, topk_idx
router 根据输入生成专家打分,通过topk仅保留稀疏激活gate中的概率用于加权专家输出,topk_idx决定调用哪些expert
import torch.nn as nn
class LoRALayer(nn.Module):
def __init__(self, in_dim, out_dim, rank, alpha):
super().__init__()
std_dev = 1 / torch.sqrt(torch.tensor(rank).float())
self.A = nn.Parameter(torch.randn(in_dim, rank) * std_dev)
self.B = nn.Parameter(torch.zeros(rank, out_dim))
self.alpha = alpha
def forward(self, x):
x = self.alpha * (x @ self.A @ self.B)
return x
class LinearWithLoRA(nn.Module):
def __init__(self, linear, rank, alpha):
super().__init__()
self.linear = linear
self.lora = LoRALayer(
linear.in_features, linear.out_features, rank, alpha
)
def forward(self, x):
return self.linear(x) + self.lora(x)




| 格式 | 尾数 | 指数 | 近似数值范围 | 常见场景 |
|---|---|---|---|---|
| FP32 | 23 | 8 | 1.18e-38 ~ 3.4e38 | 全精度训练、关键评估 |
| BF16 | 7 | 8 | 1.18e-38 ~ 3.4e38 | 大规模训练,保留 FP32 动态范围 |
| FP16 | 10 | 5 | 6.10e-5 ~ 6.55e4 | 混合精度训练、推理 |
| FP8 (E4M3 / E5M2) | 3 / 2 | 4 / 5 | 2.4e-2 ~ 4.48e2 / 5.96e-4 ~ 5.73e4 | 最新 GPU 上的高效推理/训练 |

scale 和零点 zero_point
x_q = round(x/scale + zero_point)
https://marp.app/



* 位宽越低误差越大,可配合蒸馏、RPTQ 等手段补偿 * 整数矩阵乘法在 GPU/ASIC 上通常吞吐更高、能耗更低
--- ## 常见量化方式 | 策略 | 说明 | 典型场景 | | --- | --- | --- | | Post-Training Quantization (PTQ) | 模型训练完成后离线量化,依赖小规模校准数据 | 快速上线、推理加速 | | Quantization-Aware Training (QAT) | 训练阶段插入假量化节点,显式模拟量化误差 | 对精度敏感或降 bit 较激进的任务 | | Weight-Only INT8/INT4 | 仅量化权重、激活保持 FP16/BF16 | 服务器侧 LLM.int8() / AWQ | | Activation-Aware Quantization | 权重和激活一起量化,需处理 KV cache 与注意力输出 | 移动端/边缘部署、极致压缩 |