This should work:
losses = []
for inst_id in range(batch_size):
  start_index = int(obj_classes[inst_id].data[0]) * self.class_period
  end_index   = start_index + self.class_period
  losses.append(-labels[inst_id, start_index:end_index] * F.softmax(preds[inst_id, start_index:end_index]).log()).sum())
loss = torch.sum(torch.cat(losses))
loss /= batch_size

(unverified, may have some typos)
The reason is that as soon as you do loss = torch.zeros(1) you are creating a Tensor that is not connected to the computational graph at all. You need to be creating the loss Variable that maintains it’s connection to the computation graph.