Maybe like this is better:
import torch
a = torch.tensor([0.0], requires_grad=True)
b = torch.tensor([0.0], requires_grad=True)

cosa = torch.cos(a)
cosb = torch.cos(b)

y1 = cosa + cosb
y2 = torch.cat([
    cosa, cosb
], dim=0)

y2.sum().backward() 

print("a has grad ", a.requires_grad)
print("a grad", a.grad)