Repository navigation
Closed
Description
Describe the bug
I try to compile a function but I have and error on the while line. without the "compile flag" it works but it is slow...
To Reproduce
Include code snippet
import mlx.core as mx
import numpy as np
@mx.compile
def isotonic_regression(y, weight):
n = y.shape[0]
# Initialize the solution with the values of y
solution = y
if n <= 1:
return solution
# Perform isotonic regression
n -= 1
while True:
pooled = False
i = 0
while i < n:
k = i
# Find the longest decreasing subsequence starting at i
while mx.logical_and((n > k) , mx.greater_equal(mx.array(solution[k]),mx.array(solution[k + 1]))):
k += 1
# If we have a decreasing subsequence, we need to pool (average) the subsequence
if mx.not_equal(mx.array(solution[i]),mx.array(solution[k])):
# Compute the weighted average of the subsequence
numerator = mx.sum(solution[i:k + 1] * weight[i:k + 1])
denominator = mx.sum(weight[i:k + 1])
pooled_value = numerator / denominator
solution[i:k + 1] = pooled_value
pooled = True
i = k + 1
if not pooled:
break
return solution
y = mx.array([3.0, 1.0, 4.0, 3.0, 1.5, 2.0])
weight = mx.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
isotonic_regression(y, weight)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
[/var/folders/4w/xmf8nmhs51j4vjsttzcxmmm00000gn/T/ipykernel_33677/3658025634.py](http://localhost:8888/var/folders/4w/xmf8nmhs51j4vjsttzcxmmm00000gn/T/ipykernel_33677/3658025634.py) in <cell line: 0>()
2 weight = mx.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
3
----> 4 isotonic_regression(y, weight)
[/var/folders/4w/xmf8nmhs51j4vjsttzcxmmm00000gn/T/ipykernel_33677/2839085623.py](http://localhost:8888/var/folders/4w/xmf8nmhs51j4vjsttzcxmmm00000gn/T/ipykernel_33677/2839085623.py) in isotonic_regression(y, weight)
20 k = i
21 # Find the longest decreasing subsequence starting at i
---> 22 while mx.logical_and((n > k) , mx.greater_equal(mx.array(solution[k]),mx.array(solution[k + 1]))):
23 k += 1
24
ValueError: [eval] Attempting to eval an array during function transformations like compile or vmap is not allowed.Desktop (please complete the following information):
- OS Version: [e.g. MacOS 15.1.1]
- Version [e.g. 0.21.0]
Metadata
Metadata
Assignees
Labels
No labels
Activity
awni commentedon Dec 9, 2024
You can't have control flow in Python using MLX arrays inside a compiled MLX function. Control flow in Python is an implicit graph evaluation:
You can read more about this in the documentation on
evalandcompile.Maybe it makes sense to compile just the inner computation without the control flow... not sure.
guillaume-osmo commentedon Dec 9, 2024
So the trick is to use masking to avoid if conditions
awni commentedon Dec 9, 2024
Yes if you can do it that way that is much better.