1. 几种编码的区别
encode 与 encode_plus区别
- encode: 仅返回inputs_id
- encode_plus: 返回所有的信息, input_ids,token_type_ids,attention_mask
# encoder 与 encode_plus区别
import torch
from transformers import BertTokenizer
model_name = './chinese_roberta_wwm/'
# a.通过词典导入分词器
tokenizer = BertTokenizer.from_pretrained(model_name)
sentence = "Hello, my son is laughing."
# encode
print(tokenizer.encode(sentence))
# encode_plus
print(tokenizer.encode_plus(sentence))
# 输出
[101, 8701, 117, 8422, 8968, 8171, 8310, 8515, 12667, 8221, 119, 102]
{'input_ids': [101, 8701, 117, 8422, 8968, 8171, 8310, 8515, 12667, 8221, 119, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
- encode与tokeninze方法区别
sentence = "Hello, my son is cuting."
input_ids_method1 = torch.tensor(
tokenizer.encode(sentence, add_special_tokens=True)) # Batch size 1
# tensor([ 101, 7592, 1010, 2026, 2365, 2003, 3013, 2075, 1012, 102])
input_token2 = tokenizer.tokenize(sentence)
# ['hello', ',', 'my', 'son', 'is', 'cut', '##ing', '.']
input_ids_method2 = tokenizer.convert_tokens_to_ids(input_token2)
# tensor([7592, 1010, 2026, 2365, 2003, 3013, 2075, 1012])
# 并没有开头和结尾的标记:[cls]、[sep]
2. gradient_accumulation_steps
如果显存不足,我们可以通过gradient_accumulation_steps梯度累计来解决。
假设原来的batch size=10,数据总量为1000,那么一共需要100train steps,同时一共进行100次梯度更新。
若是显存不够,我们需要减小batch size,我们设置gradient_accumulation_steps=2,那么我们新的batch size=10/2=5,我们需要运行两次,才能在内存中放入10条数据,梯度更新的次数不变为100次,那么我们的train steps=200