-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add an example demonstrating input-output aliasing with the FFI #25042
Open
dfm
wants to merge
2
commits into
jax-ml:main
Choose a base branch
from
dfm:ffi-example-input-output-alias
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+290
−311
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
/* Copyright 2024 The JAX Authors. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
==============================================================================*/ | ||
|
||
#include <cstdint> | ||
#include <mutex> | ||
#include <string_view> | ||
#include <unordered_map> | ||
|
||
#include "nanobind/nanobind.h" | ||
#include "xla/ffi/api/ffi.h" | ||
|
||
namespace nb = nanobind; | ||
namespace ffi = xla::ffi; | ||
|
||
// ---------- | ||
// Attributes | ||
// ---------- | ||
// | ||
// An example demonstrating the different ways that attributes can be passed to | ||
// the FFI. | ||
// | ||
// For example, we can pass arrays, variadic attributes, and user-defined types. | ||
// Full support of user-defined types isn't yet supported by XLA, so that | ||
// example will be added in the future. | ||
|
||
ffi::Error ArrayAttrImpl(ffi::Span<const int32_t> array, | ||
ffi::ResultBufferR0<ffi::S32> res) { | ||
int64_t total = 0; | ||
for (int32_t x : array) { | ||
total += x; | ||
} | ||
res->typed_data()[0] = total; | ||
return ffi::Error::Success(); | ||
} | ||
|
||
XLA_FFI_DEFINE_HANDLER_SYMBOL(ArrayAttr, ArrayAttrImpl, | ||
ffi::Ffi::Bind() | ||
.Attr<ffi::Span<const int32_t>>("array") | ||
.Ret<ffi::BufferR0<ffi::S32>>()); | ||
|
||
ffi::Error DictionaryAttrImpl(ffi::Dictionary attrs, | ||
ffi::ResultBufferR0<ffi::S32> secret, | ||
ffi::ResultBufferR0<ffi::S32> count) { | ||
auto maybe_secret = attrs.get<int64_t>("secret"); | ||
if (maybe_secret.has_error()) { | ||
return maybe_secret.error(); | ||
} | ||
secret->typed_data()[0] = maybe_secret.value(); | ||
count->typed_data()[0] = attrs.size(); | ||
return ffi::Error::Success(); | ||
} | ||
|
||
XLA_FFI_DEFINE_HANDLER_SYMBOL(DictionaryAttr, DictionaryAttrImpl, | ||
ffi::Ffi::Bind() | ||
.Attrs() | ||
.Ret<ffi::BufferR0<ffi::S32>>() | ||
.Ret<ffi::BufferR0<ffi::S32>>()); | ||
|
||
// ------- | ||
// Counter | ||
// ------- | ||
// | ||
// An example demonstrating how an FFI call can maintain "state" between calls | ||
// | ||
// In this case, the ``Counter`` call simply accumulates the number of times it | ||
// was executed, but this pattern can also be used for more advanced use cases. | ||
// For example, this pattern is used in jaxlib for: | ||
// | ||
// 1. The GPU solver linear algebra kernels which require an expensive "handler" | ||
// initialization, and | ||
// 2. The ``triton_call`` function which caches the compiled triton modules | ||
// after their first use. | ||
|
||
ffi::Error CounterImpl(int64_t index, ffi::ResultBufferR0<ffi::S32> out) { | ||
static std::mutex mutex; | ||
static auto &cache = *new std::unordered_map<int64_t, int32_t>(); | ||
{ | ||
const std::lock_guard<std::mutex> lock(mutex); | ||
auto it = cache.find(index); | ||
if (it != cache.end()) { | ||
out->typed_data()[0] = ++it->second; | ||
} else { | ||
cache.insert({index, 0}); | ||
out->typed_data()[0] = 0; | ||
} | ||
} | ||
return ffi::Error::Success(); | ||
} | ||
|
||
XLA_FFI_DEFINE_HANDLER_SYMBOL( | ||
Counter, CounterImpl, | ||
ffi::Ffi::Bind().Attr<int64_t>("index").Ret<ffi::BufferR0<ffi::S32>>()); | ||
|
||
// -------- | ||
// Aliasing | ||
// -------- | ||
// | ||
// This example demonstrates how input-output aliasing works. The handler | ||
// doesn't do anything except to check that the input and output pointers | ||
// address the same data. | ||
|
||
ffi::Error AliasingImpl(ffi::AnyBuffer input, | ||
ffi::Result<ffi::AnyBuffer> output) { | ||
if (input.element_type() != output->element_type() || | ||
input.element_count() != output->element_count()) { | ||
return ffi::Error::InvalidArgument( | ||
"The input and output data types and sizes must match."); | ||
} | ||
if (input.untyped_data() != output->untyped_data()) { | ||
return ffi::Error::InvalidArgument( | ||
"When aliased, the input and output buffers should point to the same " | ||
"data."); | ||
} | ||
return ffi::Error::Success(); | ||
} | ||
|
||
XLA_FFI_DEFINE_HANDLER_SYMBOL( | ||
Aliasing, AliasingImpl, | ||
ffi::Ffi::Bind().Arg<ffi::AnyBuffer>().Ret<ffi::AnyBuffer>()); | ||
|
||
// Boilerplate for exposing handlers to Python | ||
NB_MODULE(_cpu_examples, m) { | ||
m.def("registrations", []() { | ||
nb::dict registrations; | ||
registrations["array_attr"] = | ||
nb::capsule(reinterpret_cast<void *>(ArrayAttr)); | ||
registrations["dictionary_attr"] = | ||
nb::capsule(reinterpret_cast<void *>(DictionaryAttr)); | ||
|
||
registrations["counter"] = nb::capsule(reinterpret_cast<void *>(Counter)); | ||
|
||
registrations["aliasing"] = nb::capsule(reinterpret_cast<void *>(Aliasing)); | ||
|
||
return registrations; | ||
}); | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, how I'd love to see it converted to FFI state :)