Flux.jl/src/compiler/loops.jl

85 lines
1.8 KiB
Julia
Raw Normal View History

2016-08-29 14:17:54 +00:00
type Delay
name::Symbol
end
function liftloops!(ex, params)
e = Flow.normedges(ex)
hidden = intersect((b.args[1] for b in ex.args), params)
edges = Dict(h => gensym("edge") for h in hidden)
for b in ex.args
b.args[2] = MacroTools.postwalk(x -> get(edges, x, x), b.args[2])
end
for (h, e) in edges
unshift!(ex.args, :($e = $(Delay(h))($h)))
end
return ex
end
2016-08-31 01:37:53 +00:00
function hasloops(model)
g = graph(model)
g == nothing && return false
iscyclic(g) && return true
result = false
map(m -> hasloops(m) && (result = true), g)
return result
end
function atomise(model)
postwalk(graph(model)) do v
hasloops(value(v)) || return v
spliceinputs(atomise(value(v)), inputs(v)...)
end
end
2016-08-29 14:17:54 +00:00
2016-08-31 01:37:53 +00:00
hinput(n) = vertex(getindex, constant(ModelInput(1)), constant(n))
2016-08-29 14:17:54 +00:00
2016-08-31 01:37:53 +00:00
function unroll!(delay::IVertex, n)
prewalk!(delay[1]) do v
v === delay ? hinput(n) : v
2016-08-29 15:23:43 +00:00
end
end
2016-08-31 01:37:53 +00:00
function break!(g::IVertex)
g = bumpinputs(g)
2016-08-29 15:23:43 +00:00
loops = []
2016-08-31 01:37:53 +00:00
g = prewalk!(g) do v
2016-08-29 15:23:43 +00:00
isa(value(v), Delay) || return v
2016-08-31 01:37:53 +00:00
n = length(loops)+1
push!(loops, unroll!(v, n))
hinput(n)
2016-08-29 15:23:43 +00:00
end
2016-08-31 01:37:53 +00:00
cse(vertex(tuple, vertex(tuple, loops...), g))
2016-08-29 14:17:54 +00:00
end
2016-08-31 01:37:53 +00:00
# r = Recurrent(10, 10)
# r = Chain(Dense(10,10), Recurrent(10,10))
# r = Chain(Recurrent(10,10),Recurrent(10,10))
# break!(atomise(r)) |> syntax |> prettify |> display
2016-08-29 14:17:54 +00:00
2016-08-31 01:37:53 +00:00
# @model type Recurrent
# Wx; Wh; B
# hidden
#
# function (x)
# hidden = σ( Wx*x + Wh*hidden + B )
# end
# end
#
# Recurrent(in::Integer, out::Integer; init = initn) =
# Recurrent(init(out, in), init(out, out), init(out), zeros(out))
2016-08-29 14:17:54 +00:00
@model type Recurrent
2016-08-31 01:37:53 +00:00
model
2016-08-29 14:17:54 +00:00
hidden
function (x)
2016-08-31 01:37:53 +00:00
hidden = σ(model(vcat(x, hidden)))
2016-08-29 14:17:54 +00:00
end
end
2016-08-31 01:37:53 +00:00
Recurrent(in::Integer, out::Integer; init = initn) =
Recurrent(Dense(in + out, out, init = init), zeros(out))
2016-08-29 14:17:54 +00:00
Base.show(io::IO, r::Recurrent) =
print(io, "Flux.Recurrent(...)")