当使用 EinsumDense 时,如何查看其 FLOPs 并与普通 Dense 对比?
解读
面试官真正想考察的是:
- 你是否知道 Keras 里“层”的 FLOPs 并不会像参数量那样自动打印,需要借助额外工具;
- 你是否能区分 Dense 与 EinsumDense 在计算图上的差异,并给出可量化的对比方法;
- 你是否能在真实工业场景(GPU/TPU 部署、算子融合、XLA)下解释“纸面 FLOPs”与“实测耗时”可能不一致的原因。
国内大厂(阿里、字节、商汤、旷视)的算法工程岗面试中,这道题常作为“手写模型压缩”或“算子替换”环节的追问,答出“用 tf.profiler+自定义公式”只是及格线,能进一步说出“einsum 路径优化”“反向算子融合”才是加分项。
知识点
- FLOPs 定义:深度学习里通常只统计乘加(multiply-accumulate)次数,1 MACC = 2 FLOPs。
- Dense 计算量:输出元素数 × 输入维度 = batch×out_units×in_units。
- EinsumDense 计算量:由 einsum 表达式决定,例如 "abc,cd->abd" 等价于 batch×seq×in×out,与 Dense 相同;若出现多轴合并("abmn,mnk->abk")则对应高维卷积式乘加。
- 查看工具:
- TF 2.x 官方:tf.profiler.experimental、tf.compat.v1.profiler.profile;
- 社区:keras-flops、ptflops(支持 TF 后端)、thop;
- 手写:在 call 里用 tf.nn.compute_average_flops、或利用 graph_util 转静态图后遍历 op。
- 易错点:
- 动态 shape 下 profiler 会返回“?”导致统计失败,需先用 @tf.function(input_signature=...) 固化;
- TPU 下 XLA 会把 einsum 重写成多个 matmul+reduce,纸面 FLOPs 不变但墙钟时间下降,面试时要主动提到。
答案
示范代码与步骤(可直接在面试官给的笔记本上跑通):
import tensorflow as tf
from tensorflow.keras import layers
from keras_flops import get_flops # pip install keras-flops
# 1. 构造两个结构相同但实现不同的层
inputs = tf.keras.Input(shape=(512,))
x1 = layers.Dense(256)(inputs)
model_dense = tf.keras.Model(inputs, x1)
inputs2 = tf.keras.Input(shape=(512,))
x2 = layers.EinsumDense("ab,bc->ac", output_shape=256)(inputs2)
model_einsum = tf.keras.Model(inputs2, x2)
# 2. 统计 FLOPs
flops_dense = get_flops(model_dense, batch_size=1)
flops_einsum = get_flops(model_einsum, batch_size=1)
print("Dense FLOPs :", flops_dense) # 输出 262144 MACC = 524288 FLOPs
print("EinsumDense FLOPs :", flops_einsum) # 数值相同
解释:
- Dense 的矩阵乘法维度为 (1,512)·(512,256) → 512×256=131072 MACC,乘加各一次,共 262144 FLOPs;
- EinsumDense 在 einsum 表达式等价于普通矩阵乘时,计算量完全一致;
- 若把 EinsumDense 换成 "abm,mn->abn" 做多维投影,只需改 output_shape 与方程,FLOPs 公式变为 batch×seq×in×out,同样可用上述代码自动读出。
对比结论:在单轴投影场景下二者 FLOPs 相等;EinsumDense 的优势是省显存(省去中间 reshape)、支持任意维张量一次性乘加,而 Dense 只能处理二维。
拓展思考
- 实际业务中,序列长度可变,如何获得“每 token”FLOPs? 答:在 tf.function 里加 input_signature=[tf.TensorSpec([None, None, 512], tf.float32)],再用 profiler 统计,可把 batch×seq 维度标为变量,得到 FLOPs = seq×in×out。
- 如果后端换成 JAX,怎样保证统计口径一致? 答:JAX 没有 tf.profiler,可用 jax.experimental.jet 或 oak_flops,但注意 JAX 默认把 einsum 做“隐式转置+blas”,纸面 FLOPs 相同,实际常量折叠后可能少一次 transpose。
- 面试追问:若发现 EinsumDense 比 Dense 实测慢,如何定位?
答:三板斧:
- nvprof/nsys 看 kernel 名,若出现“Eigen::”说明未调用 cublas,属于路径选择问题;
- 设置 TF_XLA_FLAGS="--tf_xla_auto_jit=2" 强制 XLA,对比 wall time;
- 若仍慢,可手写 tf.matmul+reshape 回退,证明是 einsum 路径解析开销,给出 PR 优化 einsum 单测即可。