Pytorch NN and communication between classes
I am new at python, and pytorch, and I have a problem understanding how it works.

    import torch.nn as nn
    import torch.nn.functional as F
    import torch.optim as optim

    class Net(nn.Module):
        def __init__(self):
            ..
        def forward(self, x):
            ..
            return x
    net = Net()


criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()




So, this is the code, and I draw what I understand from the code in the picture.
I have some questions:

A) Why could not I use nn.CrossEntropy instead of 'criterion' directly in the code? What difference does it make if I assign it to a variable? I get this error: bool value of Tensor with more than one value is ambiguous

B) Why when the class Net gets an object (nn) (I assumed when 'as' is used, an object is created), then class Net can simply use backward afterward? It is supposed to be part of nn, not Net. Could you please make sense of it for me?

C) While optim is a different object, how do the parameters, which were optimized by optim, can affect nn? I don't understand how they pass variable and update each other?

A) By setting it as a variable in one spot it helps make it easier to change the loss function in one location as opposed to having to type nn.MSELoss in many places as the code increases in size and complexity.  Less likely to make errors basically.
As for the error one would need more information to answer that bool error.  On what line what are the inputs etc.  Too little information to help there.

B) Net(nn.Module) inherits from nn.Module which will add the backwards to all the operations you add to the class.  See the docs for more info.

C) "net" is an object. net.parameters() is an iterator that iterates over all of the parameters in the net object.  So it's passed by reference as opposed to passing the parameters by value.
