"Break" the forward function using hook

I want to “break” the inference if a condition is met and just return a random output, and I want to do it without changing the code in the forward function.

So, something that came up in my mind is using a forward hook. But is there any function/API to “break” the forward function via hook? Or is there any better approach to do it?

Going off your hook idea, you could raise an error inside the forward hook for your module and catch it out side.

Ah… you are right… I believe it will work. Thank you!