小编Pen*_*uin的帖子

如何在 PyTorch 中释放 GPU 内存

我有一个句子列表,我正在尝试使用以下代码使用多个模型来计算其困惑度:

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 …

python memory pytorch huggingface-transformers

27
推荐指数
2
解决办法
5万
查看次数

我在 GitHub 上开发了一个私人仓库,然后将其公开。我可以让我的活动可见吗?

我有一个私人仓库,工作了 6 个月。今天我提交论文后终于公开了。是否可以使活动(那些绿色方块)可见?我尝试单击contribution setting并收到消息Visitors will now see your public and anonymized private contributions,但活动仍然不显示。

更新1:

我注意到只记录了我在 GitHub(网站,而不是从我的机器推送代码)上所做的更改。也就是说,仅readme显示我经常在网站上更新的文件。

更新2:

我跑去git --no-pager log -s --format="%ae"查看哪些电子邮件用于提交,并得到以下信息:有些电子邮件是primaryGitHub 下的电子邮件,有些是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,但这不会在活动中显示。

github repo

16
推荐指数
1
解决办法
3410
查看次数

HTTP 错误 503:尝试下载 MNIST 数据时服务不可用

我正在尝试运行我一周前在 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)

python mnist pytorch google-colaboratory

13
推荐指数
1
解决办法
8335
查看次数

如何使用huggingface掩码语言模型计算句子的困惑度?

我有几个屏蔽语言模型(主要是 Bert、Roberta、Albert、Electra)。我还有一个句子数据集。我怎样才能得到每个句子的困惑度?

\n

从这里的Huggingface 文档中,他们提到困惑度“对于像 BERT 这样的屏蔽语言模型来说没有很好的定义”,尽管我仍然看到人们以某种​​方式计算它。

\n

例如,在这个SO问题中,他们使用函数计算它

\n
def 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\'

\n

我用我的几个模型尝试过:

\n
from transformers import pipeline, BertForMaskedLM, BertForMaskedLM, AutoTokenizer, RobertaForMaskedLM, …
Run Code Online (Sandbox Code Playgroud)

nlp transformer-model pytorch bert-language-model huggingface-transformers

8
推荐指数
1
解决办法
9023
查看次数

Huggingface 的“resume_from_checkpoint”有效吗?

我目前将我的教练设置为:

\n
training_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_dirI 有训练师保存的几个文件:

\n
[\'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将从最后一个检查点继续训练模型:

\n

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, …

pytorch huggingface-transformers huggingface

8
推荐指数
1
解决办法
1万
查看次数

VS code 随机决定向下滚动

我刚开始使用 VS Code,但遇到了这个问题。我只是在一行上编写代码,滑块自行决定向下到单元格的底部。当我关闭 VS 代码并返回时,它停止这样做,但几分钟后它会做同样的事情。
更新 1
看起来“command + a”出于某种原因也在向下滚动单元格。我检查了键绑定,但它不在那里。此外,有时当我单击某一行时,它会向下滚动页面,但我无法复制它。这是非常随机的。

更新 2
我断开了鼠标的连接,并且还禁用了除 Python 之外的所有扩展。问题还在继续。似乎有一些线条导致滑块向上或向下(通常向下到单元格的底部)。它不仅用于单击,我还尝试在笔记本电脑上的那些随机行上使用“左”/“右”键,并且滑块也在做同样的事情。尽管如此,当我关闭 VS 代码并将其重新打开时,这些相同的行不会引起任何问题。
更新 3
我完全卸载了 vs code 并重新安装了它。问题依然存在。
更新 4
我开始认为它可能与空白有关。有一行导致了问题(我点击它并自动滚动到底部),当我删除它上面的空行时,它停止了。当我再次看到它时,我会尝试复制它。

python visual-studio-code

7
推荐指数
1
解决办法
538
查看次数

如何加载预训练的 PyTorch 模型?

我下面这个关于保存和载入检查站指南。然而,有些事情是不对的。我的模型会训练并且参数会在训练阶段正确更新。但是,加载检查点时似乎出现了问题。也就是说,不再更新参数。

我的型号:

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)

python pytorch

7
推荐指数
0
解决办法
303
查看次数

学习率调度器和优化器之间有什么关系?

如果我有一个模型:

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)

python pytorch

7
推荐指数
1
解决办法
3597
查看次数

通过计算雅可比行列式有效地使用 PyTorch 的 autograd 与张量

在我之前的问题中,我发现了如何将 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)

python pytorch

7
推荐指数
1
解决办法
493
查看次数

如何创建交互式脑形图?

networkx我正在和中从事可视化项目plotly。有没有一种方法可以创建一个类似于人脑的 3D 图形,networkx然后将其可视化plotly(因此它将是交互式的)? 在此输入图像描述

这个想法是将节点放在外面(或者如果更容易的话只显示节点)并对一组节点进行不同的着色,如上图所示

python networkx plotly

7
推荐指数
2
解决办法
1850
查看次数