Skip to content

IREE Java TFLite Bindings - #5361

Merged
KoolJBlack merged 7 commits into
iree-org:mainfrom
KoolJBlack:tflite-java-bindings
Apr 22, 2021
Merged

KoolJBlack merged 7 commits into
iree-org:mainfrom
KoolJBlack:tflite-java-bindings

Conversation

@KoolJBlack

Copy link
Copy Markdown
Contributor

IREE Java TFLite Bindings

Implementation of the IREE Java TFLIte API. This API is designed to provide a similar interface and as much compatibility as possible with Tensorflow's Interpreter.java, but there are a few key unsupported features:

  • Delegates and the NNAPI
  • Advanced interpreter options
  • Interrupting or canceling inference before its complete
  • Tensor method signatures

In addition, some features aren't fully fleshed out yet or tested:

  • Dynamic shape support
  • String input/output

This compatibility layer will only accept java.nio.Buffer type classes as input. Javadoc details how to convert from non buffer based inputs into buffers and vice versa.

For API brevity, all features/methods IREE cannot support aren't included in this shim. Comments are updated to reflect differences in the behavior of the underlying IREE runtime.

Includes Java classes for the API as well as an Android implementation test. Built by Gradle.

@KoolJBlack KoolJBlack added the bindings/java Java+JNI wrapping IREE's C API label Apr 8, 2021
@KoolJBlack
KoolJBlack requested review from ScottTodd and benvanik April 8, 2021 23:07
@google-cla google-cla Bot added the cla: yes label Apr 8, 2021
@benvanik

benvanik commented Apr 8, 2021

Copy link
Copy Markdown
Collaborator

Wow, this looks freaking fantastic! I'll do a full review later tonight!

One early comment is to remove the IREE_CHECKs and replace them with throwing JNI exceptions or IREE_DCHECK if they are debug-only. CHECK will be going away soon: #5238.

@ScottTodd ScottTodd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking good :D

Comment thread CMakeLists.txt Resolved
Comment thread CMakeLists.txt Resolved
Comment thread bindings/tflite/java/build.gradle Resolved
Comment thread bindings/tflite/java/build.gradle Resolved
@KoolJBlack

Copy link
Copy Markdown
Contributor Author

@benvanik to clarify your earlier comment about IREE_CHECK. Essentially these runtime checks to ensure the Tensor/Interpreter have been initialized properly before interacting with them. Even outside of debug-only, the code will still fail without the check.

According to #5238, we can't generate any crashes in native code? That leaves me with the only alternative to throw Java errors through JNI. It would look like jni_utils from tensorflow

@benvanik

Copy link
Copy Markdown
Collaborator

@benvanik to clarify your earlier comment about IREE_CHECK. Essentially these runtime checks to ensure the Tensor/Interpreter have been initialized properly before interacting with them. Even outside of debug-only, the code will still fail without the check.

According to #5238, we can't generate any crashes in native code? That leaves me with the only alternative to throw Java errors through JNI. It would look like jni_utils from tensorflow

(a little rambling here mostly because I realized I was a too terse with that statement - sorry about that :)

Correct - you shouldn't generate crashes in native code (you of course can, but you can't use crashes as flow control in production code :). A CHECK (which is always enabled regardless of debug/release) will cause the entire app to just blink out of existence and leave no information for the user. Some apps will have native backtrace hooks (like crashpad) and may be able to get the unsymbolized stack trace, but it's really not a great way to report an error especially if it's one that the user can encounter.

You can return status codes or throw exceptions - I always use status codes, but exceptions are more java normal, and in some cases if you need to handle exceptions on the JNI side anyway it's nice to have a consistent handling mechanism. You can use DCHECK (which is disabled in release builds) but note that DCHECK is only to be used for precondition checks and such where you are asserting your behavior (as the developer of the code) is correct. For anything coming from a user of the API you don't want DCHECKs as the user won't see them unless they are in a debug build and even if they do they'll get the same app-mysteriously-disappears-and-now-spend-8-hours-trying-to-get-a-symbolicated-stack-trace issue. I've also seen lots of code where people try to get clever and assert/DCHECK/etc right before they then gracefully handle the error and return but instead of helping it just means you can never test your failure handling in debug builds.

For generating exceptions you can either do it via JNI on the native side or return a status code of some kind (bool, int, etc) and then throw the exception from your java code. Ideally you validate calls as much as you can on the java side and avoid calling down into native code at all if there would be an error, but that's not always reasonable as sometimes you'd have to have a non-trivial amount of duplication to detect an error may occur instead of just letting it happen.

For much of the usage in this PR you can simply change your CHECK_NE(foo, NULL) to if (!foo) return MY_JNI_STATUS_ERROR_MUMBLE_SENTINEL; as you are already returning status codes from most of your functions. The Java side can then check if the code returned from the native call is that and throw an exception - the no need for any exception construction in the native code (which is a pain).

As an example, returning a 0 for nativeCreateOutput can indicate an error to the java side which can then throw an exception:
https://github.com/google/iree/pull/5361/files#diff-275e2db9a14df8ebb307e9b017a1f76f0bc005a9c00808415303e086e5bbad4cR56-R61

Exception handling can be tricky - there are times when exceptions may be thrown by calls you make from within JNI. For example things like NewDirectByteBuffer can throw OutOfMemoryError. FindClass will actually throw NoClassDefFoundError - in which case your CHECK is going to prevent that nice useful message from ever being seen as you'll crash before control returns back to Java for it to print the message. This has some good examples: https://www.developer.com/open-source/exception-handling-in-jni/. For example on the GetFieldID/etc stuff as in https://github.com/google/iree/pull/5361/files#diff-275e2db9a14df8ebb307e9b017a1f76f0bc005a9c00808415303e086e5bbad4cR30-R38 you'll want to be checking the JNIEnv for whether an exception was thrown (GetFieldID can throw NoSuchFieldError, etc) and returning NULL to try to get back up to Java ASAP.

You can see a list of what JNI stuff throws here in quite possibly the ugliest website ever: https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

HTH and happy to chat more - sorry for not giving more background :)

@benvanik

Copy link
Copy Markdown
Collaborator

oh and most of that was just general stuff - for the specific instances in here where you are CHECKing that the pointer passed in was right those are perfect DCHECKs: there are no cases where a user can call the private native methods - only you can - and you should have checked in Java before coming in. The best way to handle errors like that though is to prevent them: if it's impossible for a user to ever get an instance of your java object that has a null/uninitialized native handle then you never have to check. Not possible if you're matching tflite that uses constructors for things - in those cases you pretty much have to just throw exceptions.

@KoolJBlack
KoolJBlack force-pushed the tflite-java-bindings branch 3 times, most recently from af32794 to a67f32d Compare April 13, 2021 01:09
@KoolJBlack
KoolJBlack force-pushed the tflite-java-bindings branch from a67f32d to 1241b64 Compare April 13, 2021 01:18
@KoolJBlack
KoolJBlack requested a review from ScottTodd April 13, 2021 17:11

@benvanik benvanik left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking good! Just some minor bits about a few lines of code you can remove and an extra check or two.

@ScottTodd ScottTodd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM from me, pending Ben's recent comments being resolved
Nice work!

@KoolJBlack
KoolJBlack merged commit 5bf3994 into iree-org:main Apr 22, 2021
@KoolJBlack
KoolJBlack deleted the tflite-java-bindings branch September 9, 2021 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bindings/java Java+JNI wrapping IREE's C API

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants