我有一个句子列表,我正在尝试使用以下代码使用多个模型来计算其困惑度:
from transformers import AutoModelForMaskedLM, AutoTokenizer
import torch
import numpy as np
model_name = 'cointegrated/rubert-tiny'
model = AutoModelForMaskedLM.from_pretrained(model_name).cuda()
tokenizer = AutoTokenizer.from_pretrained(model_name)
def score(model, tokenizer, sentence):
tensor_input = tokenizer.encode(sentence, return_tensors='pt')
repeat_input = tensor_input.repeat(tensor_input.size(-1)-2, 1)
mask = torch.ones(tensor_input.size(-1) - 1).diag(1)[:-2]
masked_input = repeat_input.masked_fill(mask == 1, tokenizer.mask_token_id)
labels = repeat_input.masked_fill( masked_input != tokenizer.mask_token_id, -100)
with torch.inference_mode():
loss = model(masked_input.cuda(), labels=labels.cuda()).loss
return np.exp(loss.item())
print(score(sentence='London is the capital of Great Britain.', model=model, tokenizer=tokenizer))
# 4.541251105675365
Run Code Online (Sandbox Code Playgroud)
大多数模型都运行良好,但有些句子似乎会抛出错误:
RuntimeError: CUDA out of memory. Tried to allocate 10.34 …
我有一个私人仓库,工作了 6 个月。今天我提交论文后终于公开了。是否可以使活动(那些绿色方块)可见?我尝试单击contribution setting
并收到消息Visitors will now see your public and anonymized private contributions
,但活动仍然不显示。
更新1:
我注意到只记录了我在 GitHub(网站,而不是从我的机器推送代码)上所做的更改。也就是说,仅readme
显示我经常在网站上更新的文件。
更新2:
我跑去git --no-pager log -s --format="%ae"
查看哪些电子邮件用于提交,并得到以下信息:有些电子邮件是primary
GitHub 下的电子邮件,有些是43555163+Penguin@users.noreply.github.com
,有些是Penguin@Penguin-MacBook-Pro.local
,有些是Penguin@econ2-204-32-dhcp.int.university_name.edu
。
另外,正如我在下面的评论之一中提到的,如果我转到我的存储库并专门查看提交,我可以看到类似以下内容的内容Penguin authored and Penguin committed on May 27 1 parent 1d71ac3 commit cb95c2870de67383ee653849b4c7b40a062f5fd3
:但这并没有显示在我的活动中。
最后,一些评论提到在 GitHub 上创建一个新的存储库并推送我之前的提交(在以某种方式过滤电子邮件之后,我不太明白)。然而,我已经Stargazers
在这个仓库上有几个并且想保留它们。通过创建一个新的仓库,我相信这些将会消失。
更新3:
我曾经git filter-repo
将所有电子邮件更改为我的主要电子邮件,现在当我致电时,我以前的所有提交电子邮件似乎都是我的主要电子邮件git --no-pager log -s --format="%ae"
。但是,我仍然没有看到活动显示。例如,如果我转到我的存储库,我可以看到其中一项提交显示Penguin authored and Penguin committed on Apr 8
,但这不会在活动中显示。
我正在尝试运行我一周前在 Google Colab 上编写的代码(并且有效),但由于某种原因我现在收到此错误。
#libraries
import torch
import torchvision
from torchvision import datasets, transforms
import torch.nn as nn
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST(root='./data', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size_train, shuffle=True)
test_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST(root='./data', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])),
batch_size=batch_size_test, shuffle=True)
Run Code Online (Sandbox Code Playgroud)
输出:
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ./data/MNIST/raw/train-images-idx3-ubyte.gz
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
<ipython-input-3-03d990013546> in <module>()
6 torchvision.transforms.ToTensor(),
7 torchvision.transforms.Normalize(
----> 8 (0.1307,), (0.3081,))
9 ])),
10 batch_size=batch_size_train, shuffle=True)
11 frames
/usr/lib/python3.7/urllib/request.py in http_error_default(self, req, …
Run Code Online (Sandbox Code Playgroud) 我有几个屏蔽语言模型(主要是 Bert、Roberta、Albert、Electra)。我还有一个句子数据集。我怎样才能得到每个句子的困惑度?
\n从这里的Huggingface 文档中,他们提到困惑度“对于像 BERT 这样的屏蔽语言模型来说没有很好的定义”,尽管我仍然看到人们以某种方式计算它。
\n例如,在这个SO问题中,他们使用函数计算它
\ndef score(model, tokenizer, sentence, mask_token_id=103):\n tensor_input = tokenizer.encode(sentence, return_tensors=\'pt\')\n repeat_input = tensor_input.repeat(tensor_input.size(-1)-2, 1)\n mask = torch.ones(tensor_input.size(-1) - 1).diag(1)[:-2]\n masked_input = repeat_input.masked_fill(mask == 1, 103)\n labels = repeat_input.masked_fill( masked_input != 103, -100)\n loss,_ = model(masked_input, masked_lm_labels=labels)\n result = np.exp(loss.item())\n return result\n\nscore(model, tokenizer, \'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0\') # returns 45.63794545581973\n
Run Code Online (Sandbox Code Playgroud)\n但是,当我尝试使用我得到的代码时TypeError: forward() got an unexpected keyword argument \'masked_lm_labels\'
。
我用我的几个模型尝试过:
\nfrom transformers import pipeline, BertForMaskedLM, BertForMaskedLM, AutoTokenizer, RobertaForMaskedLM, …
Run Code Online (Sandbox Code Playgroud) nlp transformer-model pytorch bert-language-model huggingface-transformers
我目前将我的教练设置为:
\ntraining_args = TrainingArguments(\n output_dir=f"./results_{model_checkpoint}",\n evaluation_strategy="epoch",\n learning_rate=5e-5,\n per_device_train_batch_size=4,\n per_device_eval_batch_size=4,\n num_train_epochs=2,\n weight_decay=0.01,\n push_to_hub=True,\n save_total_limit = 1,\n resume_from_checkpoint=True,\n)\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=tokenized_qa["train"],\n eval_dataset=tokenized_qa["validation"],\n tokenizer=tokenizer,\n data_collator=DataCollatorForMultipleChoice(tokenizer=tokenizer),\n compute_metrics=compute_metrics\n)\n
Run Code Online (Sandbox Code Playgroud)\n训练结束后,我的output_dir
I 有训练师保存的几个文件:
[\'README.md\',\n \'tokenizer.json\',\n \'training_args.bin\',\n \'.git\',\n \'.gitignore\',\n \'vocab.txt\',\n \'config.json\',\n \'checkpoint-5000\',\n \'pytorch_model.bin\',\n \'tokenizer_config.json\',\n \'special_tokens_map.json\',\n \'.gitattributes\']\n
Run Code Online (Sandbox Code Playgroud)\n从文档来看,似乎resume_from_checkpoint
将从最后一个检查点继续训练模型:
resume_from_checkpoint (str or bool, optional) \xe2\x80\x94 If a str, local path to a saved checkpoint as saved by a previous instance of Trainer. If a bool and equals True, …
我刚开始使用 VS Code,但遇到了这个问题。我只是在一行上编写代码,滑块自行决定向下到单元格的底部。当我关闭 VS 代码并返回时,它停止这样做,但几分钟后它会做同样的事情。
更新 1。
看起来“command + a”出于某种原因也在向下滚动单元格。我检查了键绑定,但它不在那里。此外,有时当我单击某一行时,它会向下滚动页面,但我无法复制它。这是非常随机的。
更新 2。
我断开了鼠标的连接,并且还禁用了除 Python 之外的所有扩展。问题还在继续。似乎有一些线条导致滑块向上或向下(通常向下到单元格的底部)。它不仅用于单击,我还尝试在笔记本电脑上的那些随机行上使用“左”/“右”键,并且滑块也在做同样的事情。尽管如此,当我关闭 VS 代码并将其重新打开时,这些相同的行不会引起任何问题。
更新 3。
我完全卸载了 vs code 并重新安装了它。问题依然存在。
更新 4。
我开始认为它可能与空白有关。有一行导致了问题(我点击它并自动滚动到底部),当我删除它上面的空行时,它停止了。当我再次看到它时,我会尝试复制它。
我下面这个关于保存和载入检查站指南。然而,有些事情是不对的。我的模型会训练并且参数会在训练阶段正确更新。但是,加载检查点时似乎出现了问题。也就是说,不再更新参数。
我的型号:
import torch
import torch.nn as nn
import torch.optim as optim
PATH = 'test.pt'
class model(nn.Module):
def __init__(self):
super(model, self).__init__()
self.a = torch.nn.Parameter(torch.rand(1, requires_grad=True))
self.b = torch.nn.Parameter(torch.rand(1, requires_grad=True))
self.c = torch.nn.Parameter(torch.rand(1, requires_grad=True))
#print(self.a, self.b, self.c)
def load(self):
try:
checkpoint = torch.load(PATH)
print('\nloading pre-trained model...')
self.a = checkpoint['a']
self.b = checkpoint['b']
self.c = checkpoint['c']
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
print(self.a, self.b, self.c)
except: #file doesn't exist yet
pass
@property
def b_opt(self):
return torch.tanh(self.b)*2
def train(self):
print('training...')
for epoch in range(3):
print(self.a, self.b, …
Run Code Online (Sandbox Code Playgroud) 如果我有一个模型:
import torch
import torch.nn as nn
import torch.optim as optim
class net_x(nn.Module):
def __init__(self):
super(net_x, self).__init__()
self.fc1=nn.Linear(2, 20)
self.fc2=nn.Linear(20, 20)
self.out=nn.Linear(20, 4)
def forward(self, x):
x=self.fc1(x)
x=self.fc2(x)
x=self.out(x)
return x
nx = net_x()
Run Code Online (Sandbox Code Playgroud)
然后我定义我的输入、优化器(使用lr=0.1
)、调度程序(使用base_lr=1e-3
)和训练:
r = torch.tensor([1.0,2.0])
optimizer = optim.Adam(nx.parameters(), lr = 0.1)
scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=1e-3, max_lr=0.1, step_size_up=1, mode="triangular2", cycle_momentum=False)
path = 'opt.pt'
for epoch in range(10):
optimizer.zero_grad()
net_predictions = nx(r)
loss = torch.sum(torch.randint(0,10,(4,)) - net_predictions)
loss.backward()
optimizer.step()
scheduler.step()
print('loss:' , loss)
#save state …
Run Code Online (Sandbox Code Playgroud) 在我之前的问题中,我发现了如何将 PyTorch 的 autograd 与张量一起使用:
import torch
from torch.autograd import grad
import torch.nn as nn
import torch.optim as optim
class net_x(nn.Module):
def __init__(self):
super(net_x, self).__init__()
self.fc1=nn.Linear(1, 20)
self.fc2=nn.Linear(20, 20)
self.out=nn.Linear(20, 4) #a,b,c,d
def forward(self, x):
x=torch.tanh(self.fc1(x))
x=torch.tanh(self.fc2(x))
x=self.out(x)
return x
nx = net_x()
#input
t = torch.tensor([1.0, 2.0, 3.2], requires_grad = True) #input vector
t = torch.reshape(t, (3,1)) #reshape for batch
#method
dx = torch.autograd.functional.jacobian(lambda t_: nx(t_), t)
dx = torch.diagonal(torch.diagonal(dx, 0, -1), 0)[0] #first vector
#dx = …
Run Code Online (Sandbox Code Playgroud)