-
Notifications
You must be signed in to change notification settings - Fork 132
MLX backend POC #1365
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
Open
williambdean
wants to merge
56
commits into
pymc-devs:main
Choose a base branch
from
williambdean:mlx-poc
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.
+1,388
−3
Open
MLX backend POC #1365
Changes from 2 commits
Commits
Show all changes
56 commits
Select commit
Hold shift + click to select a range
d25f214
mlx poc
williambdean edacc0e
add test for dot
williambdean 052fdc2
restore pytorch
williambdean a9ecad0
wrap in mx.array
williambdean e690bff
modify the pytorch jit
williambdean ad29c17
move file
williambdean ba29b37
dont wrap
williambdean 8716870
attempt to fix github action
williambdean 9bf7edf
change the rtol
williambdean 96ba116
add init file
williambdean e116fa1
skip if not installed
williambdean 5d5f754
remove torch related code / comments
williambdean b8cee3f
simplify the fgraph_convert
williambdean d057453
assert type
williambdean ae202e6
simplify the internal
williambdean f1941fe
remove the language
williambdean 7c8eae7
Adding operations in pytensor
cetagostini 67a74fb
add extension
williambdean fb5eb52
make compare function
williambdean 516b595
rename function
williambdean 67bb8da
correct the function name
williambdean 82bb964
tests for elemwise
williambdean 877d79f
Changes
cetagostini fafedd6
Toma tu tomate William
cetagostini 60acb8d
Pushing changes with the core shit.
cetagostini 242aba7
add more tests
williambdean 6cb47fc
additional tests
williambdean bc98e09
test for switch with mlx
williambdean 4d5b34b
Pushing code
cetagostini 5abd32d
Changes
cetagostini 12daeac
A lot of new code
cetagostini ac93949
almost there baby william
cetagostini a19cbc8
Another push small
cetagostini 5c97bc8
fix for all
williambdean 2fc81bc
fix for carlos
williambdean e6437cc
just return the compiled func
williambdean c3a3e1a
A change for willy may!
cetagostini e7cf10e
FINALLY BABY LETS PARTY! (IF YOU ARE READING THIS MAKE MORE PRs)
cetagostini 880dd5c
refactor to use getattr
williambdean 1e6addd
bring argmax test
williambdean aabbb78
use deepcopy
williambdean 0812c55
move some tests
williambdean 294c271
THE SUPER BLOCKWISEE YA YA YA YA JUUUUU
cetagostini 9d3eca8
Merge branch 'mlx-poc' of https://github.com/williambdean/pytensor in…
cetagostini 9f31ab1
Guys, I'm getting sad. We need help yisus!!!!!
cetagostini 37440ff
WILLIAM YOU NEED TO GO ANOTHER MILE! GO ON MY MATEEEEEEE, GO PHILLIES!
cetagostini 4e4923f
RETURN, WHAT A SHAME! Sad times are coming.
cetagostini 6b27dc4
AI COULD BE COOL? OR WE ARE JUST FUCKING AROUND?
cetagostini e308f83
AI RULES BABY MY MATE
cetagostini 3744a18
test conv1d case
williambdean b41cab0
I'm going for pizzas, it was an incredible day!
cetagostini 323fa9d
Merge branch 'mlx-poc' of https://github.com/williambdean/pytensor in…
cetagostini 9766975
SUUUUUUUUU!!!!!! LIFE IS GOING WELL. MLX FOR MEDIA MIX MODELS BAY
cetagostini 5ffc5ef
pre-commit
cetagostini 597f84e
Almost working
cetagostini fb8fd2f
Last PR sampling working
cetagostini 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 hidden or 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 hidden or 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,5 @@ | ||
# isort: off | ||
from pytensor.link.mlx.dispatch.basic import mlx_funcify, mlx_typify | ||
|
||
import pytensor.link.mlx.dispatch.math | ||
# isort: on |
This file contains hidden or 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,61 @@ | ||
from functools import singledispatch | ||
from types import NoneType | ||
|
||
import mlx.core as mx | ||
import numpy as np | ||
|
||
from pytensor.compile.ops import DeepCopyOp | ||
from pytensor.graph.fg import FunctionGraph | ||
from pytensor.link.utils import fgraph_to_python | ||
|
||
|
||
@singledispatch | ||
def mlx_typify(data, **kwargs): | ||
raise NotImplementedError(f"mlx_typify is not implemented for {type(data)}") | ||
|
||
|
||
@mlx_typify.register(np.ndarray) | ||
@mlx_typify.register(mx.array) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
def mlx_typify_tensor(data, dtype=None, **kwargs): | ||
return mx.array(data, dtype=dtype) | ||
|
||
|
||
@mlx_typify.register(slice) | ||
@mlx_typify.register(NoneType) | ||
@mlx_typify.register(np.number) | ||
def mlx_typify_no_conversion_needed(data, **kwargs): | ||
return data | ||
|
||
|
||
@singledispatch | ||
def mlx_funcify(op, node=None, storage_map=None, **kwargs): | ||
"""Create a MLX compatible function from an PyTensor `Op`.""" | ||
raise NotImplementedError( | ||
f"No MLX conversion for the given `Op`: {op}.\nCheck out `https://github.com/pymc-devs/pytensor/issues/1350` for progress or to request we prioritize this operation" | ||
) | ||
|
||
|
||
@mlx_funcify.register(FunctionGraph) | ||
def mlx_funcify_FunctionGraph( | ||
fgraph, | ||
node=None, | ||
fgraph_name="mlx_funcified_fgraph", | ||
conversion_func=mlx_funcify, | ||
**kwargs, | ||
): | ||
built_kwargs = {"conversion_func": conversion_func, **kwargs} | ||
return fgraph_to_python( | ||
fgraph, | ||
conversion_func, | ||
type_conversion_fn=mlx_typify, | ||
fgraph_name=fgraph_name, | ||
**built_kwargs, | ||
) | ||
|
||
|
||
@mlx_funcify.register(DeepCopyOp) | ||
def mlx_funcify_DeepCopyOp(op, **kwargs): | ||
def deepcopyop(x): | ||
return x.copy() | ||
|
||
return deepcopyop |
This file contains hidden or 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,12 @@ | ||
import mlx.core as mx | ||
|
||
from pytensor.link.mlx.dispatch import mlx_funcify | ||
from pytensor.tensor.math import Dot | ||
|
||
|
||
@mlx_funcify.register(Dot) | ||
def mlx_funcify_Dot(op, **kwargs): | ||
def dot(x, y): | ||
return mx.matmul(x, y) | ||
|
||
return dot |
This file contains hidden or 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,113 @@ | ||
from pytensor.link.basic import JITLinker | ||
from pytensor.link.utils import unique_name_generator | ||
|
||
|
||
class MLXLinker(JITLinker): | ||
"""A `Linker` that JIT-compiles NumPy-based operations using Apple's MLX.""" | ||
|
||
def __init__(self, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
self.gen_functors = [] | ||
|
||
def fgraph_convert( | ||
self, | ||
fgraph, | ||
order, | ||
input_storage, | ||
output_storage, | ||
storage_map, | ||
**kwargs, | ||
): | ||
"""Convert a PyTensor FunctionGraph to an MLX-compatible function. | ||
|
||
Parameters | ||
---------- | ||
fgraph : FunctionGraph | ||
The function graph to convert | ||
order : list | ||
The order in which to compute the nodes | ||
input_storage : list | ||
Storage for the input variables | ||
output_storage : list | ||
Storage for the output variables | ||
storage_map : dict | ||
Map from variables to their storage | ||
|
||
Returns | ||
------- | ||
callable | ||
An MLX-compatible function | ||
""" | ||
from pytensor.link.mlx.dispatch import mlx_funcify | ||
|
||
# We want to have globally unique names | ||
# across the entire pytensor graph, not | ||
# just the subgraph | ||
generator = unique_name_generator(["mlx_linker"]) | ||
|
||
# Ensure that torch is aware of the generated | ||
# code so we can compile without graph breaks | ||
def conversion_func_register(*args, **kwargs): | ||
functor = mlx_funcify(*args, **kwargs) | ||
name = kwargs["unique_name"](functor) | ||
self.gen_functors.append((f"_{name}", functor)) | ||
return functor | ||
|
||
built_kwargs = { | ||
"unique_name": generator, | ||
"conversion_func": conversion_func_register, | ||
**kwargs, | ||
} | ||
return mlx_funcify( | ||
fgraph, | ||
input_storage=input_storage, | ||
storage_map=storage_map, | ||
**built_kwargs, | ||
) | ||
|
||
def jit_compile(self, fn): | ||
"""JIT compile an MLX function. | ||
|
||
Parameters | ||
---------- | ||
fn : callable | ||
The function to compile | ||
|
||
Returns | ||
------- | ||
callable | ||
The compiled function | ||
""" | ||
import mlx.core as mx | ||
|
||
return mx.compile(fn) | ||
|
||
def create_thunk_inputs(self, storage_map): | ||
"""Create inputs for the MLX thunk. | ||
|
||
Parameters | ||
---------- | ||
storage_map : dict | ||
Map from variables to their storage | ||
|
||
Returns | ||
------- | ||
list | ||
The inputs for the thunk | ||
""" | ||
from numpy.random import Generator, RandomState | ||
|
||
from pytensor.link.mlx.dispatch import mlx_typify | ||
|
||
thunk_inputs = [] | ||
for n in self.fgraph.inputs: | ||
sinput = storage_map[n] | ||
# Handle random number generators specially | ||
if isinstance(sinput[0], RandomState | Generator): | ||
new_value = mlx_typify( | ||
sinput[0], dtype=getattr(sinput[0], "dtype", None) | ||
) | ||
sinput[0] = new_value | ||
thunk_inputs.append(sinput) | ||
Comment on lines
+61
to
+69
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since we don't have Random stuff yet we shouldn't include the code |
||
|
||
return thunk_inputs |
This file contains hidden or 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 hidden or 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,19 @@ | ||
import numpy as np | ||
|
||
import pytensor | ||
from pytensor.tensor.type import matrix | ||
|
||
|
||
def test_mlx_dot(): | ||
x = matrix("x") | ||
y = matrix("y") | ||
|
||
out = x.dot(y) | ||
fn = pytensor.function([x, y], out, mode="MLX") | ||
|
||
test_x = np.random.normal(size=(3, 2)) | ||
test_y = np.random.normal(size=(2, 4)) | ||
np.testing.assert_allclose( | ||
fn(test_x, test_y), | ||
np.dot(test_x, test_y), | ||
) |
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.
Uh oh!
There was an error while loading. Please reload this page.