python - pytorch cnn模型在loss.backward()处停止而没有任何提示?

标签 python nlp pytorch

我的目标是进行五类文本分类

我正在使用 cnnbase 模型运行 bert 微调,但我的项目在 loss.backward() 处停止,而 cmd 中没有任何提示。

我的程序在 rnn base 中成功运行,例如 lstmrcnn

但是当我运行一些 cnnbase 模型时,出现了一个奇怪的错误。

我的 cnn 模型代码:

import torch
import torch.nn as nn
import torch.nn.functional as F
# from ..Models.Conv import Conv1d
from transformers.modeling_bert import BertPreTrainedModel, BertModel
n_filters = 200
filter_sizes = [2,3,4]
class BertCNN(BertPreTrainedModel):
    def __init__(self, config):
        super(BertPreTrainedModel, self).__init__(config)
        self.num_filters = n_filters
        self.filter_sizes = filter_sizes
        self.bert = BertModel(config)
        for param in self.bert.parameters():
            param.requires_grad = True
        self.convs = nn.ModuleList(
            [nn.Conv2d(1, self.num_filters, (k, config.hidden_size))
                for k in self.filter_sizes])
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.fc_cnn = nn.Linear(self.num_filters *
                                len(self.filter_sizes), config.num_labels)

    def conv_and_pool(self, x, conv):
        x = F.relu(conv(x)).squeeze(3)
        x = F.max_pool1d(x, x.size(2)).squeeze(2)
        return x

    def forward(self, input_ids,
                attention_mask=None, token_type_ids=None, head_mask=None):
        outputs = self.bert(input_ids,
                            attention_mask=attention_mask,
                            token_type_ids=token_type_ids,
                            head_mask=head_mask)
        encoder_out, text_cls = outputs
        out = encoder_out.unsqueeze(1)
        out = torch.cat([self.conv_and_pool(out, conv)
                         for conv in self.convs], 1)
        out = self.dropout(out)
        out = self.fc_cnn(out)
        return out

我的火车代码:

        for step, batch in enumerate(data):
            self.model.train()
            batch = tuple(t.to(self.device) for t in batch)
            input_ids, input_mask, segment_ids, label_ids = batch
            print("input_ids, input_mask, segment_ids, label_ids SIZE: \n")   
            print(input_ids.size(), input_mask.size(),segment_ids.size(), label_ids.size()) 
            # torch.Size([2, 80]) torch.Size([2, 80]) torch.Size([2, 80]) torch.Size([2])
            logits = self.model(input_ids, segment_ids, input_mask)
            print("logits and label ids size: ",logits.size(), label_ids.size())
            # torch.Size([2, 5]) torch.Size([2])
            loss = self.criterion(output=logits, target=label_ids)
            if len(self.n_gpu) >= 2:
                loss = loss.mean()
            if self.gradient_accumulation_steps > 1:
                loss = loss / self.gradient_accumulation_steps
            if self.fp16:
                with amp.scale_loss(loss, self.optimizer) as scaled_loss:
                    scaled_loss.backward()
                clip_grad_norm_(amp.master_params(self.optimizer), self.grad_clip)
            else:
                loss.backward() # I debug find that the program stop at this line without any error prompt

enter image description here

将批量大小更改为 1 bug依然出现

第1步的logits:

logits 张量([[ 0.8831, -0.0368, -0.2206, -2.3484, -1.3595]], device='cuda:1', grad_fn=)

第1步损失:

张量(1.5489, device='cuda:1', grad_fn=NllLossBackward>)

但是为什么loss.backward()不能呢?

最佳答案

我尝试在linux平台上运行我的程序,并且运行成功。

所以很有可能是os不同造成的

之前的操作系统:win 10

关于python - pytorch cnn模型在loss.backward()处停止而没有任何提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59245714/

相关文章:

python - 具有复杂 numpy 数组和 native 数据类型的 numba TypingError

python - pyinstaller 好像找不到数据文件

python - 通过 Gensim 查找未见文档的主题

python - PyTorch 和 Numpy 中的张量输入选择逻辑分歧

python - PyTorch:如何打印网络中每一层的输出 blob 大小?

python - 通过索引列表选择pytorch张量元素

python - 使用python获取列表中的最大重复项索引

python - 在某个字符之后从字符串中提取数字

javascript - 使用 node.js 和自然语言处理来处理多个词组

自然语言处理 : Is Gazetteer a cheat