Keras 回调
在使用Keras训练Transformers模型时,有一些特定于库的回调可用于自动化常见任务:
KerasMetricCallback
类 transformers.KerasMetricCallback
< source >( metric_fn: typing.Callable eval_dataset: typing.Union[tensorflow.python.data.ops.dataset_ops.DatasetV2, numpy.ndarray, tensorflow.python.framework.tensor.Tensor, tuple, dict] output_cols: typing.Optional[typing.List[str]] = None label_cols: typing.Optional[typing.List[str]] = None batch_size: typing.Optional[int] = None predict_with_generate: bool = False use_xla_generation: bool = False generate_kwargs: typing.Optional[dict] = None )
参数
- metric_fn (
Callable
) — 用户提供的度量函数。它将使用两个参数调用 -predictions
和labels
。 这些包含模型的输出和数据集中的匹配标签。它应该返回一个将度量名称映射到数值的字典。 - eval_dataset (
tf.data.Dataset
或dict
或tuple
或np.ndarray
或tf.Tensor
) — 用于生成metric_fn
预测的验证数据。 - output_cols (`List[str], optional) — 从模型输出中保留的列列表作为预测结果。默认为全部列。
- label_cols (’
List[str]
, optional’) — 从输入数据集中保留作为标签的列列表。如果未提供,将自动检测。 - batch_size (
int
, optional) — 批量大小。仅在数据不是预批处理的tf.data.Dataset
时使用。 - predict_with_generate (
bool
, optional, defaults toFalse
) — 是否应该使用model.generate()
来获取模型的输出。 - use_xla_generation (
bool
, optional, defaults toFalse
) — 如果我们在生成,是否使用XLA编译模型生成。这可以极大地提高生成速度(高达100倍加速),但需要为每个输入形状进行新的XLA编译。当使用XLA生成时,最好将输入填充到相同的大小,或者在tokenizer
或DataCollator
中使用pad_to_multiple_of
参数,这将减少唯一输入形状的数量并节省大量编译时间。如果predict_with_generate
为False
,则此选项无效。 - generate_kwargs (
dict
, 可选) — 传递给model.generate()
的关键字参数,用于生成时使用。如果predict_with_generate
为False
,则无效。
在每个epoch结束时计算指标的回调函数。与普通的Keras指标不同,这些指标不需要由TF编译。这对于需要字符串操作或无法编译的生成循环的常见NLP指标(如BLEU和ROUGE)特别有用。预测(或生成)将在传递给metric_fn
之前在eval_dataset
上计算,并以np.ndarray
格式传递。metric_fn
应计算指标并返回一个将指标名称映射到指标值的字典。
我们提供了一个适合的metric_fn示例,用于计算摘要模型的ROUGE分数。请注意,为了可读性和简洁性,此示例跳过了一些后处理步骤,可能不应直接使用!
from datasets import load_metric
rouge_metric = load_metric("rouge")
def rouge_fn(predictions, labels):
decoded_predictions = tokenizer.batch_decode(predictions, skip_special_tokens=True)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
result = rouge_metric.compute(predictions=decoded_predictions, references=decoded_labels)
return {key: value.mid.fmeasure * 100 for key, value in result.items()}
PushToHubCallback
类 transformers.PushToHubCallback
< source >( output_dir: typing.Union[str, pathlib.Path] save_strategy: typing.Union[str, transformers.trainer_utils.IntervalStrategy] = 'epoch' save_steps: typing.Optional[int] = None tokenizer: typing.Optional[transformers.tokenization_utils_base.PreTrainedTokenizerBase] = None hub_model_id: typing.Optional[str] = None hub_token: typing.Optional[str] = None checkpoint: bool = False **model_card_args )
参数
- output_dir (
str
) — 输出目录,模型预测和检查点将写入该目录,并与Hub上的存储库同步。 - save_strategy (
str
或 IntervalStrategy, 可选, 默认为"epoch"
) — 在训练期间采用的检查点保存策略。可能的值为:"no"
: 在训练结束时保存。"epoch"
: 在每个 epoch 结束时保存。"steps"
: 每save_steps
步保存一次。
- save_steps (
int
, optional) — 在使用“steps”save_strategy
时,保存之间的步骤数。 - tokenizer (
PreTrainedTokenizerBase
, optional) — 模型使用的分词器。如果提供,将与权重一起上传到仓库中。 - hub_model_id (
str
, optional) — The name of the repository to keep in sync with the localoutput_dir
. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance"user_name/model"
, which allows you to push to an organization you are a member of with"organization_name/model"
.将默认为
output_dir
的名称。 - hub_token (
str
, 可选) — 用于将模型推送到 Hub 的令牌。默认为使用huggingface-cli login
在缓存文件夹中获取的令牌。 - checkpoint (
bool
, 可选, 默认为False
) — 是否保存完整的训练检查点(包括周期和优化器状态)以允许训练恢复。仅在save_strategy
为"epoch"
时可用。
回调函数,将定期保存并将模型推送到Hub。默认情况下,它每个epoch推送一次,但可以通过save_strategy
参数进行更改。推送的模型可以像Hub上的任何其他模型一样访问,例如使用from_pretrained
方法。