I am trying to optimize over the value z and netG is trained GAN model.
Here is the code. I am getting an error. I want to min the loss between the generated images x and the z. something like this:
maxEpochs = 100
z = nn.Parameter(torch.rand(64,100,1,1), requires_grad=True).to(device)
opt = torch.optim.Adam([z]).to(device)

for e in range(maxEpochs):
    netG.eval()
    g_z = netG(z)
    generatedImages = fakeimages.to(device)
    loss = nn.MSELoss()(generatedImages, g_z)
    # calculate gradient
    opt.zero_grad()
    loss.backward()
    opt.step()

    losses['rec'].append(loss)
    if e % 100 == 0:
        print( '[%d] epoch: %0.5f, Loss: %0.5f' % (e, loss))

I am getting the error     

 ValueError("can't optimize a non-leaf Tensor")
Can anyone help me out in resolving the error?