Your code snippet works fine if I add loss.backward(), so I guess you might be trying to call .backward() on another (detached) tensor?
Could you compare the posted code snippet and update it to reproduce this error, please?