V.3.3: Error: Grad only applies to real scalar-output functions

Hi!
Thank you for this question, it really made me think.
For now, I have a quick fix, but I want to inquire further about the reasons of this error next week with the team.
Your code is indeed almost right. I checked your Hamiltonian (cost_h) against ours and they match, except for one thing. Your code outputs elements of the form Z(i) @ Z(i) and ours gives Identity(0) instead. For some reason, using Z(0) @ Z(0) instead of Identity(0) gives rise to complex values hence the Error occurs and our evaluator is not capable of discarding the imaginary part (like python does if you run the code locally in your machine).
Take this into account when you are creating your Hamiltonian and it should work.

Let me know if this was helpful.