Pytorch tensorboard add_graph Type Error

I’m newbie. I get a Type Error when I use tensorboard in pytorch . Here is my code:

import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, dropout=0.1, max_len=5000):
        super(PositionalEncoding, self).__init__()
        self.dropout = nn.Dropout(p=dropout)

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        self.register_buffer("pe", pe)

    def forward(self, x):
        x = x +[:x.size(0), :]
        return self.dropout(x)

class TransformerModel(nn.Module):

    def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):
        super(TransformerModel, self).__init__()
        from torch.nn.modules.transformer import TransformerEncoder, TransformerEncoderLayer
        # from torch.nn import TransformerEncoder, TransformerEncoderLayer
        self.model_type = "Transformer"
        self.src_mask = None
        self.pos_encoder = PositionalEncoding(ninp, dropout)
        print(f"pos encoder type is {type(self.pos_encoder)},")
        encoder_layers = TransformerEncoderLayer(d_model=ninp, nhead=nhead, dim_feedforward=nhid, dropout=dropout)
        self.transformer_encoder = TransformerEncoder(encoder_layer=encoder_layers, num_layers=nlayers)
        self.encoder = nn.Embedding(num_embeddings=ntoken, embedding_dim=ninp)
        self.ninp = ninp
        self.decoder = nn.Linear(ninp, ntoken)


    def _generate_square_subsequent_mask(self, sz):
        mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
        mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
        return mask

    def init_weights(self):
        initrange = 0.1, initrange), initrange)

    def forward(self, src):
        if self.src_mask is None or self.src_mask.size(0) != len(src):
            device = src.device
            mask = self._generate_square_subsequent_mask(len(src)).to(device)
            self.src_mask = mask

        src = self.encoder(src) * math.sqrt(self.ninp)

        src = self.pos_encoder(src)
        output = self.transformer_encoder(src, self.src_mask)
        output = self.decoder(output)
        return output

# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")

embedding_size = 200
nhid = 200
nlayers = 2
nhead = 2
dropout = 0.2
model = TransformerModel(ntokens, embedding_size, nhead, nhid, nlayers, dropout).to(device)

writer = SummaryWriter()

The seq2seq code is from []. why I get Type Error when add_graph(model). this is my error

TypeError: 'NoneType' object is not iterable

some traceback:

    self._get_file_writer().add_graph(graph(model, input_to_model, verbose))
    trace = torch.jit.trace(model, args)
    check_tolerance, _force_outplace, _module_class)
    example_inputs = make_tuple(example_inputs)
    return tuple(example_inputs)
TypeError: 'NoneType' object is not iterable

Tangential question: Did you have to install tensorboard separately to get pytorch to use it? With pip or conda? THanks!

I have installed tensorboard with pip.

pip install tesorboard

this work in tesorboard.

import torch
import torchvision
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from import DataLoader

writer = SummaryWriter()

transforms = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
trainset = datasets.MNIST("mnist_train", train=True, download=False, transform=transforms)
trainloader = DataLoader(trainset, batch_size=64, shuffle=True)
model = torchvision.models.resnet50(False)

model.conv1 = torch.nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
images, labels = next(iter(trainloader))
grid = torchvision.utils.make_grid(images)

writer.add_image('images', grid, 0)
writer.add_graph(model, images)

import numpy as np

for n_iter in range(100):
    writer.add_scalar("Loss/train", np.random.random(), n_iter)
    writer.add_scalar("Loss/test", np.random.random(), n_iter)
    writer.add_scalar("Accuracy/train", np.random.random(), n_iter)
    writer.add_scalar("Accuracy/test", np.random.random(), n_it

Is anyone looking at this?
add_graph is defined as -

def add_graph(self, model, input_to_model=None, verbose=False):

So this states that the second argument input_to_model is optional, so when we do not provide any value to it, it throws an error.

Is this a bug? Should it be raised somewhere else?


I’m experiencing the same issue for a very simple network as well.

I am also experiencing this problem…

1 Like

Same problem here with
pytorch 1.7.01
tensorboard 2.4.0

1 Like