使用拥抱面变换器只保存最佳权重

问题描述 投票:0回答:5

目前,我正在构建一个新的基于 transformer 的模型,其中包含 huggingface-transformers,其中的注意力层与原始模型不同。我使用

run_glue.py
来检查我的模型在 GLUE 基准测试中的性能。但是,我发现 huggingface-transformers 的 Trainer 类保存了我设置的所有检查点,我可以在其中设置要保存的最大检查点数。但是,我只想在验证数据集上保存具有 best 性能的权重(或其他类似优化器的东西),而当前的 Trainer 类似乎没有提供这样的东西。 (如果我们设置检查点的最大数量,那么它会删除较旧的检查点,而不是性能较差的检查点)。 有人已经在 Github 上问过同样的问题,但我不知道如何修改脚本并做我想做的事。目前,我正在考虑制作一个继承原始Trainer类并更改
train()
方法的自定义Trainer类,如果有一种简单易行的方法就可以了。提前致谢。

deep-learning nlp pytorch huggingface-transformers
5个回答
12
投票

您可以在huggingface中尝试trainer的以下参数

training_args = TrainingArguments(
    output_dir='/content/drive/results',          # output directory
    do_predict= True, 
    num_train_epochs=3,              # total number of training epochs
    **per_device_train_batch_size=4,  # batch size per device during training
    per_device_eval_batch_size=2**,   # batch size for evaluation
    warmup_steps=1000,                # number of warmup steps for learning rate  
    save_steps=1000,
    save_total_limit=10,
    load_best_model_at_end= True,
    weight_decay=0.01,               # strength of weight decay
    logging_dir='./logs',            # directory for storing logs
    logging_steps=0, evaluate_during_training=True)

可能有更好的方法来避免过多的检查点和选择最好的模型。 到目前为止,您不能只保存最好的模型,但您可以检查评估何时产生比前一个更好的结果。


9
投票

我还没有看到任何参数。但是,有一个解决方法。

使用以下组合

    evaluation_strategy =‘steps’,
    eval_steps = 10, # Evaluation and Save happens every 10 steps
    save_total_limit = 5, # Only last 5 models are saved. Older ones are deleted.
    load_best_model_at_end=True,

当我尝试使用上述组合时,输出目录中随时会保存 5 个以前的模型,但如果最好的模型不在其中,它也会保留最好的模型。所以它将是 1 + 5 个模型。您可以更改 save_total_limit = 1 以达到您的目的


5
投票

这个答案可能有用

training_args = TrainingArguments(
    output_dir=repo_name,
    group_by_length=True,
    length_column_name='input_length',
    per_device_train_batch_size=24,
    gradient_accumulation_steps=2,
    evaluation_strategy="steps",
    num_train_epochs=20,
    fp16=True,
    save_steps=1000,
    save_strategy='steps', # we cannot set it to "no". Otherwise, the model cannot guess the best checkpoint.
    eval_steps=1000,
    logging_steps=1000,
    learning_rate=5e-5,
    warmup_steps=500,
    save_total_limit=3,
    load_best_model_at_end = True # this will let the model save the best checkpoint
)

0
投票

下面的参数是否保存了最好的检查点和模型?

training_args = Seq2SeqTrainingArguments(
  num_train_epochs=2, 
  learning_rate=1e-5,
  predict_with_generate=True,
  evaluation_strategy="steps",
  per_device_train_batch_size=8,
  per_device_eval_batch_size= 8,
  fp16=True,
  output_dir="ft_trocr", 
  logging_steps=100,
  save_steps=2000,
  eval_steps=1000,
  save_total_limit=2,
  load_best_model_at_end=True,  
)

trainer.save_model(output_dir = './')

-3
投票

This 应该有助于将当前验证精度与最佳验证精度进行比较,然后保存最佳模型。

© www.soinside.com 2019 - 2024. All rights reserved.