-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
scheduler.jl
425 lines (378 loc) · 14.8 KB
/
scheduler.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
module Sch
using Distributed
import MemPool: DRef
import ..Dagger: Context, Processor, Thunk, Chunk, OSProc, order, free!, dependents, noffspring, istask, inputs, affinity, tochunk, @dbg, @logmsg, timespan_start, timespan_end, unrelease, procs, move, choose_processor, execute!, rmprocs!, addprocs!
include("fault-handler.jl")
const OneToMany = Dict{Thunk, Set{Thunk}}
"""
ComputeState
The internal state-holding struct of the scheduler.
Fields
- dependents::OneToMany - The result of calling `dependents` on the DAG
- finished::Set{Thunk} - The set of completed `Thunk`s
- waiting::OneToMany - Map from parent `Thunk` to child `Thunk`s that still need to execute
- waiting_data::OneToMany - Map from child `Thunk` to all parent `Thunk`s, accumulating over time
- ready::Vector{Thunk} - The list of `Thunk`s that are ready to execute
- cache::Dict{Thunk, Any} - Maps from a finished `Thunk` to it's cached result, often a DRef
- running::Set{Thunk} - The set of currently-running `Thunk`s
- thunk_dict::Dict{Int, Any} - Maps from thunk IDs to a `Thunk`
"""
struct ComputeState
dependents::OneToMany
finished::Set{Thunk}
waiting::OneToMany
waiting_data::OneToMany
ready::Vector{Thunk}
cache::Dict{Thunk, Any}
running::Set{Thunk}
thunk_dict::Dict{Int, Any}
end
"""
SchedulerOptions
Stores DAG-global options to be passed to the Dagger.Sch scheduler.
# Arguments
- `single::Int=0`: Force all work onto worker with specified id. `0` disables this option.
- `proctypes::Vector{Type{<:Processor}}=Type[]`: Force scheduler to use one or
more processors that are instances/subtypes of a contained type. Leave this
vector empty to disable.
"""
Base.@kwdef struct SchedulerOptions
single::Int = 0
proctypes::Vector{Type} = Type[]
end
"""
ThunkOptions
Stores Thunk-local options to be passed to the Dagger.Sch scheduler.
# Arguments
- `single::Int=0`: Force thunk onto worker with specified id. `0` disables this option.
- `proctypes::Vector{Type{<:Processor}}=Type[]`: Force thunk to use one or
more processors that are instances/subtypes of a contained type. Leave this
vector empty to disable.
"""
Base.@kwdef struct ThunkOptions
single::Int = 0
proctypes::Vector{Type} = Type[]
end
"Combine `SchedulerOptions` and `ThunkOptions` into a new `ThunkOptions`."
function merge(sopts::SchedulerOptions, topts::ThunkOptions)
single = topts.single != 0 ? topts.single : sopts.single
proctypes = vcat(sopts.proctypes, topts.proctypes)
ThunkOptions(single, proctypes)
end
function cleanup(ctx)
end
function compute_dag(ctx, d::Thunk; options=SchedulerOptions())
if options === nothing
options = SchedulerOptions()
end
ctx.options = options
master = OSProc(myid())
@dbg timespan_start(ctx, :scheduler_init, 0, master)
chan = Channel{Any}(32)
deps = dependents(d)
ord = order(d, noffspring(deps))
node_order = x -> -get(ord, x, 0)
state = start_state(deps, node_order)
# start off some tasks
# Note: worker_state may be different things for different contexts. Don't touch it out here!
procs_state = assign_new_procs!(ctx, state, chan, node_order)
@dbg timespan_end(ctx, :scheduler_init, 0, master)
# Loop while we still have thunks to execute
while !isempty(state.ready) || !isempty(state.running)
if isempty(state.running) && !isempty(state.ready)
# Nothing running, so schedule up to N thunks, 1 per N workers
for p in procs_to_use(ctx)
isempty(state.ready) && break
task = pop_with_affinity!(ctx, state.ready, p, false)
if task !== nothing
fire_task!(ctx, task, p, state, chan, node_order)
end
end
end
# This is a bit redundant as the @async task below does basically the
# same job Without it though, testing of process modification becomes
# non-deterministic (due to sleep in CI environment) which is why it is
# still here.
procs_state = assign_new_procs!(ctx, state, chan, node_order, procs_state)
if isempty(state.running)
# the block above fired only meta tasks
continue
end
check_integrity(ctx)
# Check periodically for new workers in a parallel task so that we
# don't accidentally end up having to wait for `take!(chan)` on some
# large task before new workers are put to work. Locking is used to
# stop this task as soon as something pops out from the channel to
# minimize risk that the task schedules thunks simultaneously as the
# main task (after future refactoring).
newtasks_lock = ReentrantLock()
@async while !isempty(state.ready) || !isempty(state.running)
sleep(1)
islocked(newtasks_lock) && return
procs_state = lock(newtasks_lock) do
assign_new_procs!(ctx, state, chan, node_order, procs_state)
end
end
proc, thunk_id, res = take!(chan) # get result of completed thunk
lock(newtasks_lock) # This waits for any assign_new_procs! above to complete and then shuts down the task
if isa(res, CapturedException) || isa(res, RemoteException)
if check_exited_exception(res)
@warn "Worker $(proc.pid) died on thunk $thunk_id, rescheduling work"
# Remove dead worker from procs list
remove_dead_proc!(ctx, proc)
handle_fault(ctx, state, state.thunk_dict[thunk_id], proc, chan, node_order)
continue
else
throw(res)
end
end
node = state.thunk_dict[thunk_id]
@logmsg("WORKER $(proc.pid) - $node ($(node.f)) input:$(node.inputs)")
state.cache[node] = res
@dbg timespan_start(ctx, :scheduler, thunk_id, master)
immediate_next = finish_task!(state, node, node_order)
if !isempty(state.ready) && !shall_remove_proc(ctx, proc)
thunk = pop_with_affinity!(Context(procs_to_use(ctx)), state.ready, proc, immediate_next)
if thunk !== nothing
fire_task!(ctx, thunk, proc, state, chan, node_order)
end
end
@dbg timespan_end(ctx, :scheduler, thunk_id, master)
end
state.cache[d]
end
function procs_to_use(ctx, options=ctx.options)
return if options.single !== 0
@assert options.single in vcat(1, workers()) "Sch option `single` must specify an active worker ID."
OSProc[OSProc(options.single)]
else
procs(ctx)
end
end
check_integrity(ctx) = @assert !isempty(procs_to_use(ctx)) "No suitable workers available in context."
# Main responsibility of this function is to check if new procs have been pushed to the context
function assign_new_procs!(ctx, state, chan, node_order, assignedprocs=[])
ps = procs_to_use(ctx)
# Must track individual procs to handle the case when procs are removed
for p in setdiff(ps, assignedprocs)
isempty(state.ready) && break
task = pop_with_affinity!(ctx, state.ready, p, false)
if task !== nothing
fire_task!(ctx, task, p, state, chan, node_order)
end
end
return ps
end
# Might be a good policy to not remove the proc if immediate_next
shall_remove_proc(ctx, proc) = proc ∉ procs_to_use(ctx)
function remove_dead_proc!(ctx, proc, options=ctx.options)
@assert options.single !== proc.pid "Single worker failed, cannot continue."
rmprocs!(ctx, [proc])
end
function pop_with_affinity!(ctx, tasks, proc, immediate_next)
# allow JIT specialization on Pairs
mapfirst(c) = first.(c)
if immediate_next
# fast path
if proc in mapfirst(affinity(tasks[end]))
return pop!(tasks)
end
end
# TODO: use the size
parent_affinity_procs = Vector(undef, length(tasks))
# parent_affinity_sizes = Vector(undef, length(tasks))
for i=length(tasks):-1:1
t = tasks[i]
aff = affinity(t)
aff_procs = mapfirst(aff)
if proc in aff_procs
deleteat!(tasks, i)
return t
end
parent_affinity_procs[i] = aff_procs
end
for i=length(tasks):-1:1
# use up tasks without affinities
# let the procs with the respective affinities pick up
# other tasks
aff_procs = parent_affinity_procs[i]
if isempty(aff_procs)
t = tasks[i]
deleteat!(tasks, i)
return t
end
if all(!(p in aff_procs) for p in procs(ctx))
# no proc is ever going to ask for it
t = tasks[i]
deleteat!(tasks, i)
return t
end
end
return nothing
end
function fire_task!(ctx, thunk, proc, state, chan, node_order)
@logmsg("W$(proc.pid) + $thunk ($(showloc(thunk.f, length(thunk.inputs)))) input:$(thunk.inputs) cache:$(thunk.cache) $(thunk.cache_ref)")
push!(state.running, thunk)
if thunk.cache && thunk.cache_ref !== nothing
# the result might be already cached
data = unrelease(thunk.cache_ref) # ask worker to keep the data around
# till this compute cycle frees it
if data !== nothing
@logmsg("cache hit: $(thunk.cache_ref)")
state.cache[thunk] = data
immediate_next = finish_task!(state, thunk, node_order; free=false)
if !isempty(state.ready)
thunk = pop_with_affinity!(ctx, state.ready, proc, immediate_next)
if thunk !== nothing
fire_task!(ctx, thunk, proc, state, chan, node_order)
end
end
return
else
thunk.cache_ref = nothing
@logmsg("cache miss: $(thunk.cache_ref) recomputing $(thunk)")
end
end
ids = map(thunk.inputs) do x
istask(x) ? x.id : nothing
end
if thunk.meta
# Run it on the parent node, do not move data.
p = OSProc(myid())
fetched = map(Iterators.zip(thunk.inputs,ids)) do (x, id)
@dbg timespan_start(ctx, :comm, (thunk.id, id), (thunk.f, id))
x = istask(x) ? state.cache[x] : x
@dbg timespan_end(ctx, :comm, (thunk.id, id), (thunk.f, id))
return x
end
@dbg timespan_start(ctx, :compute, thunk.id, thunk.f)
res = thunk.f(fetched...)
@dbg timespan_end(ctx, :compute, thunk.id, (thunk.f, typeof(res), sizeof(res)))
#push!(state.running, thunk)
state.cache[thunk] = res
immediate_next = finish_task!(state, thunk, node_order; free=false)
if !isempty(state.ready)
if immediate_next
thunk = pop!(state.ready)
else
thunk = pop_with_affinity!(ctx, state.ready, proc, immediate_next)
end
if thunk !== nothing
fire_task!(ctx, thunk, proc, state, chan, node_order)
end
end
return
end
data = map(thunk.inputs) do x
istask(x) ? state.cache[x] : x
end
state.thunk_dict[thunk.id] = thunk
toptions = thunk.options !== nothing ? thunk.options : ThunkOptions()
options = merge(ctx.options, toptions)
if options.single > 0
proc = OSProc(options.single)
end
async_apply(proc, thunk.id, thunk.f, data, chan, thunk.get_result, thunk.persist, thunk.cache, options, ids, ctx.log_sink)
end
function finish_task!(state, node, node_order; free=true)
if istask(node) && node.cache
node.cache_ref = state.cache[node]
end
immediate_next = false
for dep in sort!(collect(state.dependents[node]), by=node_order)
set = state.waiting[dep]
pop!(set, node)
if isempty(set)
pop!(state.waiting, dep)
push!(state.ready, dep)
immediate_next = true
end
# todo: free data
end
for inp in inputs(node)
if inp in keys(state.waiting_data)
s = state.waiting_data[inp]
if node in s
pop!(s, node)
end
if free && isempty(s)
if haskey(state.cache, inp)
_node = state.cache[inp]
free!(_node, force=false, cache=(istask(inp) && inp.cache))
pop!(state.cache, inp)
end
end
end
end
push!(state.finished, node)
pop!(state.running, node)
immediate_next
end
function start_state(deps::Dict, node_order)
state = ComputeState(
deps,
Set{Thunk}(),
OneToMany(),
OneToMany(),
Vector{Thunk}(undef, 0),
Dict{Thunk, Any}(),
Set{Thunk}(),
Dict{Int, Thunk}()
)
nodes = sort(collect(keys(deps)), by=node_order)
merge!(state.waiting_data, deps)
for k in nodes
if istask(k)
waiting = Set{Thunk}(Iterators.filter(istask,
inputs(k)))
if isempty(waiting)
push!(state.ready, k)
else
state.waiting[k] = waiting
end
end
end
state
end
@noinline function do_task(thunk_id, f, data, send_result, persist, cache, options, ids, log_sink)
ctx = Context(Processor[]; log_sink=log_sink)
proc = OSProc()
fetched = map(Iterators.zip(data,ids)) do (x, id)
@dbg timespan_start(ctx, :comm, (thunk_id, id), (f, id))
x = x isa Union{Chunk,Thunk} ? collect(ctx, x) : x
@dbg timespan_end(ctx, :comm, (thunk_id, id), (f, id))
return x
end
from_proc = proc
# TODO: Time choose_processor?
to_proc = choose_processor(from_proc, options, f, fetched)
fetched = map(Iterators.zip(fetched,ids)) do (x, id)
@dbg timespan_start(ctx, :move, (thunk_id, id), (f, id))
x = move(from_proc, to_proc, x)
@dbg timespan_end(ctx, :move, (thunk_id, id), (f, id))
return x
end
@dbg timespan_start(ctx, :compute, thunk_id, f)
res = nothing
result_meta = try
res = execute!(to_proc, f, fetched...)
(from_proc, thunk_id, send_result ? res : tochunk(res, to_proc; persist=persist, cache=persist ? true : cache)) #todo: add more metadata
catch ex
bt = catch_backtrace()
(from_proc, thunk_id, RemoteException(myid(), CapturedException(ex, bt)))
end
@dbg timespan_end(ctx, :compute, thunk_id, (f, typeof(res), sizeof(res)))
result_meta
end
@noinline function async_apply(p::OSProc, thunk_id, f, data, chan, send_res, persist, cache, options, ids, log_sink)
@async begin
try
put!(chan, remotecall_fetch(do_task, p.pid, thunk_id, f, data, send_res, persist, cache, options, ids, log_sink))
catch ex
bt = catch_backtrace()
put!(chan, (p, thunk_id, CapturedException(ex, bt)))
end
nothing
end
end
end # module Sch