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

respect scopping rules in for #310

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/ReactantCore/src/ReactantCore.jl
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,15 @@ function trace_for(mod, expr)
:tuple, :(Reactant.promote_to(Reactant.TracedRNumber{Int}, 0)), external_syms...
)

cond_val(s) = :(@isdefined($s) ? $s : Reactant.MissingTracedValue())

locals = Expr[
[Expr(:(=), s, cond_val(s)) for s in external_syms]...,
:(args = $(args_init)),
]

reactant_code_block = quote
let args = $(args_init)
let $(locals...)
cond_fn =
$(all_syms) -> begin
local num_iters = div($limit - $start, $step, RoundDown)
Expand All @@ -180,7 +187,7 @@ function trace_for(mod, expr)
end

return quote
if any($(is_traced), $(Expr(:tuple, all_syms.args[(begin + 1):end]...)))
if any($(is_traced), $(Expr(:tuple, cond_val.(all_syms.args[(begin + 1):end])...)))
$(reactant_code_block)
else
$(expr)
Expand Down
13 changes: 9 additions & 4 deletions src/ControlFlow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,21 @@ function ReactantCore.traced_while(

result_0 = in_tys

operands = MLIR.IR.Value[v.mlir_data for v in traced_args]
operands = MLIR.IR.Value[v.mlir_data for v in traced_args if v isa TracedType]

while_compiled = MLIR.Dialects.stablehlo.while_(
operands; result_0, cond=cond_reg, body=body_reg
)

return map(enumerate(traced_args)) do (i, res)
res.mlir_data = MLIR.IR.result(while_compiled, i)
return res
residx = 1
for res in traced_args
if res isa TracedType
res.mlir_data = MLIR.IR.result(while_compiled, residx)
residx += 1
end
end

return traced_args
end

function take_region(compiled_fn)
Expand Down
15 changes: 15 additions & 0 deletions test/control_flow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -565,3 +565,18 @@ end

@test @jit(for_ref_outer(x_ra)) ≈ for_ref_outer(x)
end

function for_inner_scope(x)
@trace for i in 1:10
s = sum(x)
x = x / s
end
return x
end

@testset "for: inner scope" begin
x = randn(Float64, 10)
x_ra = Reactant.to_rarray(x)

@test @jit(for_inner_scope(x_ra)) ≈ for_inner_scope(x)
end
Loading