保存并重新加载拥抱微调变压器

时间:2020-11-03 13:03:34

标签: python pytorch huggingface-transformers

我正在尝试重新加载经过微调的DistilBertForTokenClassification模型。我正在使用变压器3.4.0和pytorch版本1.6.0 + cu101。在使用Trainer训练下载的模型之后,我使用trainer.save_model()保存该模型,并且在排除故障时,我通过model.save_pretrained()保存在另一个目录中。我正在使用Google Colab,并将模型保存到我的Google驱动器中。测试完模型后,我还在测试中评估了该模型,并获得了不错的结果,但是,当我回到笔记本计算机(或在Factory中重新启动colab笔记本计算机)并尝试重新加载模型时,预测很糟糕。检查目录后,config.json文件和pytorch_mode.bin也在那里。下面是完整的代码。

from transformers import DistilBertForTokenClassification

# load the pretrained model from huggingface
#model = DistilBertForTokenClassification.from_pretrained('distilbert-base-cased', num_labels=len(uniq_labels))
model = DistilBertForTokenClassification.from_pretrained('distilbert-base-uncased', num_labels=len(uniq_labels)) 

model.to('cuda');

from transformers import Trainer, TrainingArguments

training_args = TrainingArguments(
    output_dir = model_dir +  'mitmovie_pt_distilbert_uncased/results',          # output directory
    #overwrite_output_dir = True,
    evaluation_strategy='epoch',
    num_train_epochs=3,              # total number of training epochs
    per_device_train_batch_size=16,  # batch size per device during training
    per_device_eval_batch_size=64,   # batch size for evaluation
    warmup_steps=500,                # number of warmup steps for learning rate scheduler
    weight_decay=0.01,               # strength of weight decay
    logging_dir = model_dir +  'mitmovie_pt_distilbert_uncased/logs',            # directory for storing logs
    logging_steps=10,
    load_best_model_at_end = True
)

trainer = Trainer(
    model = model,                         # the instantiated ? Transformers model to be trained
    args = training_args,                  # training arguments, defined above
    train_dataset = train_dataset,         # training dataset
    eval_dataset = test_dataset             # evaluation dataset
)

trainer.train()

trainer.evaluate()

model_dir = '/content/drive/My Drive/Colab Notebooks/models/'
trainer.save_model(model_dir + 'mitmovie_pt_distilbert_uncased/model')

# alternative saving method and folder
model.save_pretrained(model_dir + 'distilbert_testing')

重新启动后返回笔记本电脑...

from transformers import DistilBertForTokenClassification, DistilBertConfig, AutoModelForTokenClassification

# retreive the saved model 
model = DistilBertForTokenClassification.from_pretrained(model_dir + 'mitmovie_pt_distilbert_uncased/model', 
                                                        local_files_only=True)

model.to('cuda')

现在无论从哪个目录进行模型预测都是可怕的,但是,该模型可以正常工作并输出我期望的班级数量,看来实际的训练砝码尚未保存或未加载。

0 个答案:

没有答案