Skip to content

Adding a calling convention encoding for VM module functions. - #3091

Merged
benvanik merged 1 commit into
mainfrom
benvanik-native-modules-wip
Sep 10, 2020
Merged

benvanik merged 1 commit into
mainfrom
benvanik-native-modules-wip

Conversation

@benvanik

@benvanik benvanik commented Sep 8, 2020 •

Copy link
Copy Markdown
Collaborator

This will allow consistent (and efficient) cross-environment marshaling of
VM-visible types (so just ints or ref ptrs), including JIT'ing or codegen
of marshaling functions. There's no real user visible changes here when
using the VM invocation API as all of this is implementation details of
the VM ISA.

Adding iree_vm_native_module to wrap up all the boilerplate for C modules.
native_module_test.h demonstrates usage (simple static functions, imported
functions, and statefullness).

Future changes will rebase module_abi_cc.h on top of this (so that all
modules share code), add a tool for generating .h/c marshaling code based
on vm.import files, and add some ABI register access helpers.

Performance is slightly improved here for callers but the major benefit is
isolating bytecode-related things to bytecode-related code and keeping the
rest of the VM interfaces generalized to make LLVM IR/C/etc module interop
much easier.

@benvanik benvanik added enhancement ➕ New feature or request runtime Relating to the IREE runtime library performance ⚡ Performance/optimization related work across the compiler and runtime labels Sep 8, 2020
@benvanik benvanik added this to the 2020Q3 Core milestone Sep 8, 2020
@google-cla google-cla Bot added the cla: yes label Sep 8, 2020
@benvanik
benvanik requested a review from ScottTodd September 8, 2020 18:45
@antiagainst

Copy link
Copy Markdown
Member

Ship it! :D

@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.

Generally LGTM. Had a few comments thinking through some versioning and forward/backwards compatibility details between modules.

Comment thread iree/vm/module.h
Comment on lines +119 to +120
// Users of this field must verify the version prefix in the first byte before
// using the declaration.

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.

Checking my understanding: someone could in the future add a new calling convention version by starting the string with any character other than '0'. They could then do whatever they wanted in the remainder of the message, like using f/F for floats, base64 encoding some other data, using libffi, etc.
Am I missing something? (Seems pretty standard, just trying to plan ahead for any code involving forward-compatibility)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yep. The only real cases where we'd end up with issues is when trying to use things across shared library boundaries and those shared libraries are updated out of sync or trying to run bytecode modules with the new FFI on older runtimes. This doesn't preclude backwards compatibility in those cases - whoever is deploying the model can still use the old calling convention until all existing deployments of the runtime are updated.

I suspect for most things (like libffi) we'll just use this same string and map it to libffi strings.

Thankfully, we're a ways away from having a stable ABI or binary representation, and this is mostly just here to make it possible to support them rather than being the final form :)

Comment thread iree/vm/module.h
// - 'i': int32_t integer (i32)
// - 'I': int64_t integer (i64)
// - 'r': ref-counted type pointer (!vm.ref<?>)
// - '[' ... ']': variadic list of flattened tuples of a specified type

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.

Are there pessimistic cases to watch for where the function signature ends up with thousands of elements, like 0ii[iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii...ii].i? What does this end up looking like for functions that operate on large tensors/buffers? (Or should such cases be using vm.ref<?> anyway?)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Tensors/buffers/byte ranges/etc are all taken care of by refs. These are just the raw function arguments/results (like a C function).

The [] annotation denotes a variable span - everything else is fixed. So if you had a function in MLIR that literally took a thousand ints then your signature here would have a thousand i's, though a more optimal encoding would be to make it [i]. The solution is to not make bad APIs and catch yourself when you're in MLIR and writing out @my_fn(%arg0 : i32, %arg1 : i32, ... %arg1000 : i32) ;)

Comment thread iree/vm/module.h
Comment on lines +147 to +149
// Callees can assume that callers have properly allocated and setup the
// argument and result buffers and need not verify them. This works only because
// the calling convention format is directly queried from the callee module.

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.

Reading through this file and its comments in isolation, I'm wondering here how different modules resolve which calling convention version to use, if they both potentially support (multiple?) different versions.

Checking my understanding again with an example:

  1. ModuleA wants to call SomeFunction from ModuleB
  2. ModuleA imports SomeFunction from ModuleB and gets its function signature with a calling convention
  3. ModuleA checks that it understands/supports that calling convention, with error handling if needed (e.g. if ModuleB is newer and uses a newer version that ModuleA wasn't compiled knowing about, or ModuleB is ancient and uses a deprecated version that ModuleA has already dropped)
  4. ModuleA prepares argument and result buffers according to the calling convention and calls SomeFunction
  5. ModuleB handles the call, trusting that the input and output buffers are as expected

In case versions differ, ModuleA may need to understand multiple versions.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yep! I'm going to copy that sequence into the docs :)

I don't think it's worth the complexity to have modules expose multiple calling conventions, though they could (in the module ctor check the runtime version and then respond to queries differently). When exported functions change (either changed arguments or changed behavior) it's up to the exporter to ensure they aren't breaking anyone potentially importing the older version and expecting something different. At least we will get nice load-time error messages when the calling convention strings don't match, but there's no saving someone from themselves if they want to create version skew.

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.

Yeah, exposing multiple calling conventions seems messy. Brainstorming some more to see if there are design flaws here...

One case: An Android app has runtime code pinned to a specific version and some newer module coming over the network (my_super_smart_model_v4 totally needs a module for something). The app could ask the server for a compatible version of the module in that case, and the server could have multiple versions (trimmed for size to respect limited network bandwidth) available. If the newer module actually requires the new calling convention, then the app should handle that failures (by prompting the user to update it, etc.).

Another case: A device (Android phone, embedded system, etc.) has an old module stored in read-only-memory somewhere in its firmware. User-space code has a newer runtime library and wants to use newer features (new calling convention has X% less overhead or includes direct support for some critical type like bfloat16, etc.). In order to use the old module and the new features, the application would need to support both calling conventions?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Similar to how an app may want to fetch a precompiled/signed AOT module for the appropriate platform they could do the same along this aspect.

Using older modules with newer runtimes (backwards compatibility of the module format) is much easier to support - the module would say it has a particular version and then the runtime can choose a different code path for v0 vs. v1.

I think on the whole I don't see this changing much in a way that would break compatibility and require a version bump. It's similar to protos/flatbuffers/etc; adding new things is easy (supporting new types) as that won't break backwards compat, but changing the behavior of existing things is hard (requires version bump and common understanding).

Comment thread iree/vm/native_module.h Outdated
iree_vm_native_function_target_t target;
} iree_vm_native_function_ptr_t;

// Describes an native module implementation by way of descriptor tables.

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.

Suggested change
// Describes an native module implementation by way of descriptor tables.
// Describes a native module implementation by way of descriptor tables.

nit: "a" native module

Comment on lines +29 to +31
// Test suite that uses module_a and module_b defined in native_module_test.h.
// Both modules are put in a context and the module_b.entry function can be
// executed with RunFunction.

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.

This is great, nice to see some code using simple modules! This demystifies some of the layers for me, having often just seen code always import the HAL module, for example.

Comment thread iree/vm/bytecode_module.c Outdated
Comment on lines +671 to +674
// there's not a good way around it. In the grand scheme of things users
// should be keeping their calls across this boundary relatively fat (compared
// to the real work they do), so this only needs to be fast enough to blend
// into the noise.

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.

Good points here, thanks for the comment. I'm in agreement that calls across the boundary should be handled carefully. Is there anything more we can do here to help these costs appear clearly under profiling? We can also make sure any of our samples demonstrate best practices well. Maybe we could even put together some counter-examples or optimization walkthroughs ("here's poor API usage and a trace file", "if you make these changes, the trace and benchmarks now look like this instead").

@benvanik
benvanik force-pushed the benvanik-native-modules-wip branch 5 times, most recently from 089983d to b2b592d Compare September 9, 2020 00:08
Comment thread iree/vm/bytecode_module.c Outdated
// there's not a good way around it. In the grand scheme of things users
// should be keeping their calls across this boundary relatively fat (compared
// to the real work they do), so this only needs to be fast enough to blend
// into the noise.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It should be pretty easy to spot with the new native modules design as time spent in the shim function (iree_vm_native_function_shim_t) provided. The shim does the arg/result buffers <-> C/py/etc conversions and the target (iree_vm_native_function_target_t) is the actual implementation, so if you spot time in the shim you know that's what's costing you. Of course, your function would have to be pretty small (on the order of dozens of instructions) or pretty hot (called 100mil times/sec), and neither are good fits for imported functions. Adding a note here.

Comment thread iree/vm/module.h
// - 'i': int32_t integer (i32)
// - 'I': int64_t integer (i64)
// - 'r': ref-counted type pointer (!vm.ref<?>)
// - '[' ... ']': variadic list of flattened tuples of a specified type

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Tensors/buffers/byte ranges/etc are all taken care of by refs. These are just the raw function arguments/results (like a C function).

The [] annotation denotes a variable span - everything else is fixed. So if you had a function in MLIR that literally took a thousand ints then your signature here would have a thousand i's, though a more optimal encoding would be to make it [i]. The solution is to not make bad APIs and catch yourself when you're in MLIR and writing out @my_fn(%arg0 : i32, %arg1 : i32, ... %arg1000 : i32) ;)

Comment thread iree/vm/module.h
Comment on lines +119 to +120
// Users of this field must verify the version prefix in the first byte before
// using the declaration.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yep. The only real cases where we'd end up with issues is when trying to use things across shared library boundaries and those shared libraries are updated out of sync or trying to run bytecode modules with the new FFI on older runtimes. This doesn't preclude backwards compatibility in those cases - whoever is deploying the model can still use the old calling convention until all existing deployments of the runtime are updated.

I suspect for most things (like libffi) we'll just use this same string and map it to libffi strings.

Thankfully, we're a ways away from having a stable ABI or binary representation, and this is mostly just here to make it possible to support them rather than being the final form :)

Comment thread iree/vm/module.h
Comment on lines +147 to +149
// Callees can assume that callers have properly allocated and setup the
// argument and result buffers and need not verify them. This works only because
// the calling convention format is directly queried from the callee module.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yep! I'm going to copy that sequence into the docs :)

I don't think it's worth the complexity to have modules expose multiple calling conventions, though they could (in the module ctor check the runtime version and then respond to queries differently). When exported functions change (either changed arguments or changed behavior) it's up to the exporter to ensure they aren't breaking anyone potentially importing the older version and expecting something different. At least we will get nice load-time error messages when the calling convention strings don't match, but there's no saving someone from themselves if they want to create version skew.

@benvanik
benvanik force-pushed the benvanik-native-modules-wip branch 3 times, most recently from 62b4395 to a875b62 Compare September 9, 2020 00:49
@benvanik
benvanik marked this pull request as ready for review September 9, 2020 00:51
@benvanik
benvanik requested a review from ScottTodd September 9, 2020 00:51
@benvanik

benvanik commented Sep 9, 2020

Copy link
Copy Markdown
Collaborator Author

Test failures are legit (happen only with a single variadic tuple list of argument types) - variadic tuples are supported via some gnarly old code that can now be cleaned up much better with the new cconv types.

@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 (once tests are passing again :P)

Comment thread iree/vm/module.h
Comment on lines +147 to +149
// Callees can assume that callers have properly allocated and setup the
// argument and result buffers and need not verify them. This works only because
// the calling convention format is directly queried from the callee module.

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.

Yeah, exposing multiple calling conventions seems messy. Brainstorming some more to see if there are design flaws here...

One case: An Android app has runtime code pinned to a specific version and some newer module coming over the network (my_super_smart_model_v4 totally needs a module for something). The app could ask the server for a compatible version of the module in that case, and the server could have multiple versions (trimmed for size to respect limited network bandwidth) available. If the newer module actually requires the new calling convention, then the app should handle that failures (by prompting the user to update it, etc.).

Another case: A device (Android phone, embedded system, etc.) has an old module stored in read-only-memory somewhere in its firmware. User-space code has a newer runtime library and wants to use newer features (new calling convention has X% less overhead or includes direct support for some critical type like bfloat16, etc.). In order to use the old module and the new features, the application would need to support both calling conventions?

@benvanik
benvanik force-pushed the benvanik-native-modules-wip branch from a875b62 to e5e58e7 Compare September 10, 2020 01:11
This will allow consistent (and efficient) cross-environment marshaling of
VM-visible types (so just ints or ref ptrs), including JIT'ing or codegen
of marshaling functions.

Adding iree_vm_native_module to wrap up all the boilerplate for C modules.
native_module_test.h demonstrates usage (simple static functions, imported
functions, and statefullness).

Future changes will rebase module_abi_cc.h on top of this (so that all
modules share code), add a tool for generating .h/c marshaling code based
on vm.import files, and add some ABI register access helpers.

Performance is slightly improved here for callers but the major benefit is
isolating bytecode-related things to bytecode-related code and keeping the
rest of the VM interfaces generalized to make LLVM IR/C/etc module interop
much easier.
@benvanik
benvanik force-pushed the benvanik-native-modules-wip branch from e5e58e7 to 825b848 Compare September 10, 2020 16:46
@benvanik
benvanik merged commit dcef285 into main Sep 10, 2020
@benvanik
benvanik deleted the benvanik-native-modules-wip branch September 10, 2020 17:01
@hanhanW hanhanW mentioned this pull request Sep 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement ➕ New feature or request performance ⚡ Performance/optimization related work across the compiler and runtime runtime Relating to the IREE runtime library

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants