Flux.jl/src/compiler/loops.jl

90 lines
2.0 KiB
Julia
Raw Normal View History

2016-08-29 14:17:54 +00:00
type Delay
name::Symbol
default::Nullable{Param}
2016-08-29 14:17:54 +00:00
end
Delay(name) = Delay(name, nothing)
2016-08-29 14:17:54 +00:00
function liftloops!(ex, params)
2016-10-26 10:19:45 +00:00
ex = Flow.normedges(ex)
2016-08-29 14:17:54 +00:00
hidden = intersect((b.args[1] for b in ex.args), params)
edges = Dict(h => gensym("edge") for h in hidden)
2016-10-26 10:19:45 +00:00
declared = Dict(h => false for h in hidden)
liftvar(s) = get(declared, s, false) ? s : get(edges, s, s)
2016-08-29 14:17:54 +00:00
for b in ex.args
2016-10-26 10:19:45 +00:00
b.args[2] = MacroTools.postwalk(liftvar, b.args[2])
declared[b.args[1]] = true
2016-08-29 14:17:54 +00:00
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-10-25 22:10:35 +00:00
hiddeninput(n) = vertex(Split(n), inputnode(1))
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
2016-10-25 22:10:35 +00:00
v === delay ? hiddeninput(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 = []
defaults = []
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))
push!(defaults, get(value(v).default))
2016-10-25 22:10:35 +00:00
hiddeninput(n)
2016-08-29 15:23:43 +00:00
end
2016-10-25 23:49:32 +00:00
cse(group(group(loops...), g)), defaults
2016-08-29 14:17:54 +00:00
end
2016-10-25 23:49:32 +00:00
function unroll(model, n)
graph, defaults = break!(atomise(model))
outputs = [spliceinputs(graph, group(map(constant, defaults)...), inputnode(1))]
detuple(outputs[end])
for i = 2:n
push!(outputs, spliceinputs(graph, outputs[end][1], inputnode(i)))
end
state = outputs[end][1]
outputs = map(x -> x[2], outputs)
@> group(state, group(outputs...)) detuple
end
2016-10-25 20:10:04 +00:00
2016-10-12 15:28:16 +00:00
@net type Recurrent
2016-10-26 10:34:17 +00:00
Wxh; Whh; Why
2016-08-29 14:17:54 +00:00
hidden
2016-09-06 12:06:30 +00:00
2016-08-29 14:17:54 +00:00
function (x)
2016-10-26 10:34:17 +00:00
hidden = σ( Wxh*x + Whh*hidden )
y = Why*hidden
2016-08-29 14:17:54 +00:00
end
end
2016-10-26 10:34:17 +00:00
Recurrent() = Recurrent((rand(i,i) for i = 1:4)...)
# syntax(x) = syntax(Flow.dl(x), bindconst = true)
2016-08-29 14:17:54 +00:00
2016-10-26 10:34:17 +00:00
# r = Recurrent()
# unroll(r,10) |> cse |> syntax |> prettify |> display