使用 tfhub 模块时冻结 BERT 层

Freezing of BERT layers while using tfhub module

在这篇linkclick here中作者说:

import tensorflow_hub as hub
module = hub.Module(<<Module URL as string>>, trainable=True)

如果用户希望fine-tune/modify模型的权重,则此参数必须设置为True。 所以我怀疑如果我将其设置为 false 是否意味着我正在冻结 BERT 的所有层,这也是我的意图。我想知道我的做法对不对

我有一个多部分的答案给你。

如何冻结模块

这一切都取决于您的优化器是如何设置的。 TF1 通常的方法是用 TRAINABLE_VARIABLES collection. The doc for hub.Module 中找到的所有变量初始化它说 trainable: "If False, no variables are added to TRAINABLE_VARIABLES collection, ..."。因此,yes,设置 trainable=False(显式或默认)冻结 TF1 标准用法中的模块。

为什么不冻结 BERT

也就是说,BERT 是要进行微调的。 paper talks about the feature-based (i.e., frozen) vs fine-tuning approaches in more general terms, but the module doc 清楚地说明了这一点:"fine-tuning all parameters is the recommended practice." 这使得计算合并输出的最后部分能够更好地适应对任务最重要的特征手边

如果您打算遵循此建议,请注意训练期间的 tensorflow.org/hub/tf1_hub_module#fine-tuning and pick the correct graph version: BERT uses dropout 正则化,并且您需要设置 hub.Module(..., tags={"train"}) 才能做到这一点。但是对于推理(在评估和预测中),dropout 什么都不做,您可以省略 tags= 参数(或将其设置为空 set()None)。

展望:TF2

你问的是 hub.Module(),这是 TF1 的 API,所以我在那个上下文中回答了。相同的注意事项适用于 TF2 SavedModel 格式的 BERT。在那里,一切都是关于设置 hub.KerasLayer(..., trainable=True) 或不设置,但是 select 图形版本的需求已经消失(该层获取 Keras 的 training 状态并在底层应用它)。

训练愉快!