This is an archive of the discontinued LLVM Phabricator instance.

[mlir][python] Directly implement sequence protocol on Sliceable.
ClosedPublic

Authored by stellaraccident on Feb 13 2022, 10:58 PM.

Details

Summary
  • While annoying, this is the only way to get C++ exception handling out of the happy path for normal iteration.
  • Implements sq_length and sq_item for the sequence protocol (used for iteration, including list() construction).
  • Implements mp_subscript for general use (i.e. foo[1] and foo[1:1]).
  • For constructing a list(op.results), this reduces the time from ~4-5us to ~1.5us on my machine (give or take measurement overhead) and eliminates C++ exceptions, which is a worthy goal in itself.

Diff Detail

Event Timeline

stellaraccident requested review of this revision.Feb 13 2022, 10:58 PM
ftynse accepted this revision.Feb 14 2022, 1:26 AM
ftynse added inline comments.
mlir/lib/Bindings/Python/PybindUtils.h
237

Don't we want a non-empty error message here?

255

Ditto.

303

I suppose this cast can never throw (self is always an instance of Derived * if CRTP is used properly), but it may warrant a comment.

326–328

Can't we just do if(PySlice_Check(rawSubscript)) instead of casting and catching an exception?

This revision is now accepted and ready to land.Feb 14 2022, 1:26 AM
phawkins accepted this revision.Feb 14 2022, 6:49 AM

Thanks! I have little to add beyond @ftynse 's comments.

mlir/lib/Bindings/Python/PybindUtils.h
291–294

You might consider linking to https://github.com/pybind/pybind11/issues/2842 and you might also consider commenting on that issue linking to your solution, since I'm sure others may have the same need.

jpienaar added inline comments.
mlir/lib/Bindings/Python/PybindUtils.h
237

The kind of error set is an index error, OOC is there any other index error than OOB?

ftynse added inline comments.Feb 14 2022, 7:58 AM
mlir/lib/Bindings/Python/PybindUtils.h
237

It still has a message:

>>> a = [1,2,3]
>>> a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
stellaraccident marked 6 inline comments as done.
stellaraccident edited the summary of this revision. (Show Details)

Address comments.

mlir/lib/Bindings/Python/PybindUtils.h
237

Indeed. I was mis-remembering that this reports with an actual message.

303

I had added a comment with rationale above the block of functions.

326–328

Done - and just used the underlying C API vs pybind11::slice. It is trivial.

Made some non-trivial changes. Another look?

ftynse accepted this revision.Feb 14 2022, 8:53 AM

Still LGTM. Some test coverage that we actually raise the errors we expect wouldn't hurt.

Add exception test.

This revision was landed with ongoing or failed builds.Feb 14 2022, 9:45 AM
This revision was automatically updated to reflect the committed changes.