Ali_Mirzaeyan:

x = torch.tensor([2., 2], requires_grad=True)
y = x**2 + x
z = y.sum()
z.backward()
print(x.grad)
with torch.no_grad():
x = x+1
z.backward()
print(x.grad)


Regarding your first code part, you need to do the forward pass before calling z.backward() the second time. So the following code:
x = torch.tensor([2., 2], requires_grad=True)
y = x**2 + x
z = y.sum()
z.backward()
print(x.grad)

with torch.no_grad():
   x = x+1

y = x**2 + x
z = y.sum()
z.backward()
print(x.grad)

However, since you have placed the new x in the with torch.no_grad() block, therefore no gradiaents can be computed, and it gives the following Error (which is expected):
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn