If I am praying and I suddenly forget which rakaat I am on, what do I have to do?

1- If your doubt is in the Maghreb or Fajr prayer then your prayer is invalid and you must start over. Yes if you have ظن like 70% or 80% in which Rak’a you are then you can go by your ظن

2- If you are in Dhuhr, Asr or Isha’ and you don’t know in which unit you are you must restart the prayer (unless you have ظن so you act on it). If you doubt you are in the 3rd or 4th then you assume you are in the 4th and finish prayer, then stand up and offer 1 rak’a called صلاة الاحتياط