Skip to content
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

Wrong result when the same array appears in both sides of = #151

Open
maphdze opened this issue Aug 8, 2022 · 2 comments
Open

Wrong result when the same array appears in both sides of = #151

maphdze opened this issue Aug 8, 2022 · 2 comments
Labels

Comments

@maphdze
Copy link

maphdze commented Aug 8, 2022

When the same array appears in both side of =, the result from Tullio is strange

using Tullio
a = [1,2]
b = [1 2;3 4]
a = b * a
println(a) # [5,11]
a = [1,2]
@tullio a[x] = b[x,y] * a[y]
println(a) # [5,23]

It seems only the first component is right. When calculate the second componet, the first component is already updated to 5, and the second component is calculated by 3*5+4*2=23.
When there are some complicated operations which have to be seprated into several steps, to avoid extra allocation, I prefer to use the same array repeatedly, and sometimes wrong results may occur like above.

@mcabbott
Copy link
Owner

This writes the following function:

# @tullio a[x] = b[x,y] * a[y] verbose=2

function 𝒜𝒸𝓉!(::Type, ℛ::AbstractArray{𝒯}, b, a, 𝒶𝓍x, 𝒶𝓍y, ♻️ = nothing, 💀 = true) where 𝒯
    for x in 𝒶𝓍x
        𝒜𝒸𝒸 = if ♻️ === nothing
                zero(𝒯)
            else
                ℛ[x]
            end
        for y in 𝒶𝓍y
            𝒜𝒸𝒸 = 𝒜𝒸𝒸 + b[x, y] * a[y]
        end
        ℛ[x] = 𝒜𝒸𝒸
    end
end

This is called like 𝒜𝒸𝓉!(typeof(a), a, b, a, axes(a,1), axes(b,2)), and so the loop overwrites values of a that it needs later.

I guess it would be nice to make this an error, by checking for aliasing.

It should still be safe to re-use an array, as long as you are reading and writing at the same point, not different ones. (E.g. things like a .= a .+ 1 are safe, of course.)

@maphdze
Copy link
Author

maphdze commented Aug 26, 2022

Thanks for your response! I think it would be nice to throw an error/warning when reading and writing the same array at different point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants