pytorch基础知识

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值