equinox icon indicating copy to clipboard operation
equinox copied to clipboard

```error_if``` support for functions and levels

Open knyazer opened this issue 8 months ago • 3 comments

Hi Patrick,

I recently thought about an interesting feature that you might find useful to implement as part of Equinox.

The idea is to allow error_if to consume functions, so that one could include some 'heavy' checks inside the error_if, and, besides that, would be nice to have an ability to skip these heavy checks. Syntax could look similar to python logging:

eqx.set_error_level(eqx.error.LOW)

x = eqx.error_if(x, really_slow_function, "Mega-critical error!", priority=eqx.error.HIGH)
x = eqx.error_if(x, x == 0, "Something not good, but recoverable", priority=eqx.error.LOW)

# besides, instead of global flags, maybe it makes sense to implement returning nan's in the same fashion?
# would also be great to pass a value with which we want to continue execution.

# so this line should raise an exception when LOW, but replace with 0.0 when HIGH
x = eqx.error_if(x, x == 1, "Try to finish execution", priority=eqx.error.LOW, replace_with=0.0)

Then eqx.set_error_level would have to force retracing of all the functions that use eqx.error_if.

You might think that added complexity is not worth it: you might be right. In my case, I would appreciate having this functionality for two reasons:

  • Debug/Release switch: so that, when I am using the code in production, I don't conduct expensive checks, but during debug I do. For example, I was recently implementing an algorithm with some complex geometry computations, and there is a simple way to check whether it is correct, but for this I need to use another algorithm that is ~3 times slower. I would care if during development/debugging I discover a case when I have an incorrect result of the fast algorithm, but incorrect result is not that critical: it would lead to some minor problems, but it would be recoverable. And I would prefer during debug that the program is stopped when such an issue encountered. But during release I would prefer my code to not crash if recoverable error is encountered, and also have better performance.
  • Pseudo try/except: use eqx.error_if(... , replace_with=...) as a jittable version of simple error handling.

WDYT?

knyazer avatar Oct 11 '23 19:10 knyazer