-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathSch.jl
1734 lines (1574 loc) · 66.3 KB
/
Sch.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module Sch
import Preferences: @load_preference
if @load_preference("distributed-package") == "DistributedNext"
import DistributedNext: Future, ProcessExitedException, RemoteChannel, RemoteException, myid, remote_do, remotecall_fetch, remotecall_wait, workers
else
import Distributed: Future, ProcessExitedException, RemoteChannel, RemoteException, myid, remote_do, remotecall_fetch, remotecall_wait, workers
end
import MemPool
import MemPool: DRef, StorageResource
import MemPool: poolset, storage_capacity, storage_utilized
import Random: randperm
import Base: @invokelatest
import ..Dagger
import ..Dagger: Context, Processor, Thunk, WeakThunk, ThunkFuture, DTaskFailedException, Chunk, WeakChunk, OSProc, AnyScope, DefaultScope, LockedObject
import ..Dagger: order, dependents, noffspring, istask, inputs, unwrap_weak_checked, affinity, tochunk, timespan_start, timespan_finish, procs, move, chunktype, processor, get_processors, get_parent, execute!, rmprocs!, task_processor, constrain, cputhreadtime
import ..Dagger: @dagdebug, @safe_lock_spin1
import DataStructures: PriorityQueue, enqueue!, dequeue_pair!, peek
import ..Dagger
const OneToMany = Dict{Thunk, Set{Thunk}}
include("util.jl")
include("fault-handler.jl")
include("dynamic.jl")
mutable struct ProcessorCacheEntry
gproc::OSProc
proc::Processor
next::ProcessorCacheEntry
ProcessorCacheEntry(gproc::OSProc, proc::Processor) = new(gproc, proc)
end
Base.isequal(p1::ProcessorCacheEntry, p2::ProcessorCacheEntry) =
p1.proc === p2.proc
function Base.show(io::IO, entry::ProcessorCacheEntry)
entries = 1
next = entry.next
while next !== entry
entries += 1
next = next.next
end
print(io, "ProcessorCacheEntry(pid $(entry.gproc.pid), $(entry.proc), $entries entries)")
end
const Signature = Vector{Any}
"""
ComputeState
The internal state-holding struct of the scheduler.
Fields:
- `uid::UInt64` - Unique identifier for this scheduler instance
- `waiting::OneToMany` - Map from downstream `Thunk` to upstream `Thunk`s that still need to execute
- `waiting_data::Dict{Union{Thunk,Chunk},Set{Thunk}}` - Map from input `Chunk`/upstream `Thunk` to all unfinished downstream `Thunk`s, to retain caches
- `ready::Vector{Thunk}` - The list of `Thunk`s that are ready to execute
- `cache::WeakKeyDict{Thunk, Any}` - Maps from a finished `Thunk` to it's cached result, often a DRef
- `valid::WeakKeyDict{Thunk, Nothing}` - Tracks all `Thunk`s that are in a valid scheduling state
- `running::Set{Thunk}` - The set of currently-running `Thunk`s
- `running_on::Dict{Thunk,OSProc}` - Map from `Thunk` to the OS process executing it
- `thunk_dict::Dict{Int, WeakThunk}` - Maps from thunk IDs to a `Thunk`
- `node_order::Any` - Function that returns the order of a thunk
- `worker_time_pressure::Dict{Int,Dict{Processor,UInt64}}` - Maps from worker ID to processor pressure
- `worker_storage_pressure::Dict{Int,Dict{Union{StorageResource,Nothing},UInt64}}` - Maps from worker ID to storage resource pressure
- `worker_storage_capacity::Dict{Int,Dict{Union{StorageResource,Nothing},UInt64}}` - Maps from worker ID to storage resource capacity
- `worker_loadavg::Dict{Int,NTuple{3,Float64}}` - Worker load average
- `worker_chans::Dict{Int, Tuple{RemoteChannel,RemoteChannel}}` - Communication channels between the scheduler and each worker
- `procs_cache_list::Base.RefValue{Union{ProcessorCacheEntry,Nothing}}` - Cached linked list of processors ready to be used
- `signature_time_cost::Dict{Signature,UInt64}` - Cache of estimated CPU time (in nanoseconds) required to compute calls with the given signature
- `signature_alloc_cost::Dict{Signature,UInt64}` - Cache of estimated CPU RAM (in bytes) required to compute calls with the given signature
- `transfer_rate::Ref{UInt64}` - Estimate of the network transfer rate in bytes per second
- `halt::Base.Event` - Event indicating that the scheduler is halting
- `lock::ReentrantLock` - Lock around operations which modify the state
- `futures::Dict{Thunk, Vector{ThunkFuture}}` - Futures registered for waiting on the result of a thunk.
- `errored::WeakKeyDict{Thunk,Bool}` - Indicates if a thunk's result is an error.
- `thunks_to_delete::Set{Thunk}` - The list of `Thunk`s ready to be deleted upon completion.
- `chan::RemoteChannel{Channel{Any}}` - Channel for receiving completed thunks.
"""
struct ComputeState
uid::UInt64
waiting::OneToMany
waiting_data::Dict{Union{Thunk,Chunk},Set{Thunk}}
ready::Vector{Thunk}
cache::WeakKeyDict{Thunk, Any}
valid::WeakKeyDict{Thunk, Nothing}
running::Set{Thunk}
running_on::Dict{Thunk,OSProc}
thunk_dict::Dict{Int, WeakThunk}
node_order::Any
worker_time_pressure::Dict{Int,Dict{Processor,UInt64}}
worker_storage_pressure::Dict{Int,Dict{Union{StorageResource,Nothing},UInt64}}
worker_storage_capacity::Dict{Int,Dict{Union{StorageResource,Nothing},UInt64}}
worker_loadavg::Dict{Int,NTuple{3,Float64}}
worker_chans::Dict{Int, Tuple{RemoteChannel,RemoteChannel}}
procs_cache_list::Base.RefValue{Union{ProcessorCacheEntry,Nothing}}
signature_time_cost::Dict{Signature,UInt64}
signature_alloc_cost::Dict{Signature,UInt64}
transfer_rate::Ref{UInt64}
halt::Base.Event
lock::ReentrantLock
futures::Dict{Thunk, Vector{ThunkFuture}}
errored::WeakKeyDict{Thunk,Bool}
thunks_to_delete::Set{Thunk}
chan::RemoteChannel{Channel{Any}}
end
const UID_COUNTER = Threads.Atomic{UInt64}(1)
function start_state(deps::Dict, node_order, chan)
state = ComputeState(Threads.atomic_add!(UID_COUNTER, UInt64(1)),
OneToMany(),
deps,
Vector{Thunk}(undef, 0),
WeakKeyDict{Thunk, Any}(),
WeakKeyDict{Thunk, Nothing}(),
Set{Thunk}(),
Dict{Thunk,OSProc}(),
Dict{Int, WeakThunk}(),
node_order,
Dict{Int,Dict{Processor,UInt64}}(),
Dict{Int,Dict{Union{StorageResource,Nothing},UInt64}}(),
Dict{Int,Dict{Union{StorageResource,Nothing},UInt64}}(),
Dict{Int,NTuple{3,Float64}}(),
Dict{Int, Tuple{RemoteChannel,RemoteChannel}}(),
Ref{Union{ProcessorCacheEntry,Nothing}}(nothing),
Dict{Signature,UInt64}(),
Dict{Signature,UInt64}(),
Ref{UInt64}(1_000_000),
Base.Event(),
ReentrantLock(),
Dict{Thunk, Vector{ThunkFuture}}(),
WeakKeyDict{Thunk,Bool}(),
Set{Thunk}(),
chan)
for k in sort(collect(keys(deps)), by=node_order)
if istask(k)
waiting = Set{Thunk}(Iterators.filter(istask, k.syncdeps))
if isempty(waiting)
push!(state.ready, k)
else
state.waiting[k] = waiting
end
state.valid[k] = nothing
end
end
state
end
"""
SchedulerOptions
Stores DAG-global options to be passed to the Dagger.Sch scheduler.
# Arguments
- `single::Int=0`: (Deprecated) Force all work onto worker with specified id.
`0` disables this option.
- `proclist=nothing`: (Deprecated) Force scheduler to use one or more
processors that are instances/subtypes of a contained type. Alternatively, a
function can be supplied, and the function will be called with a processor as
the sole argument and should return a `Bool` result to indicate whether or not
to use the given processor. `nothing` enables all default processors.
- `allow_errors::Bool=true`: Allow thunks to error without affecting
non-dependent thunks.
- `checkpoint=nothing`: If not `nothing`, uses the provided function to save
the final result of the current scheduler invocation to persistent storage, for
later retrieval by `restore`.
- `restore=nothing`: If not `nothing`, uses the provided function to return the
(cached) final result of the current scheduler invocation, were it to execute.
If this returns a `Chunk`, all thunks will be skipped, and the `Chunk` will be
returned. If `nothing` is returned, restoring is skipped, and the scheduler
will execute as usual. If this function throws an error, restoring will be
skipped, and the error will be displayed.
"""
Base.@kwdef struct SchedulerOptions
single::Union{Int,Nothing} = nothing
proclist = nothing
allow_errors::Union{Bool,Nothing} = false
checkpoint = nothing
restore = nothing
end
"""
ThunkOptions
Stores Thunk-local options to be passed to the Dagger.Sch scheduler.
# Arguments
- `single::Int=0`: (Deprecated) Force thunk onto worker with specified id. `0`
disables this option.
- `proclist=nothing`: (Deprecated) Force thunk to use one or more processors
that are instances/subtypes of a contained type. Alternatively, a function can
be supplied, and the function will be called with a processor as the sole
argument and should return a `Bool` result to indicate whether or not to use
the given processor. `nothing` enables all default processors.
- `time_util::Dict{Type,Any}`: Indicates the maximum expected time utilization
for this thunk. Each keypair maps a processor type to the utilization, where
the value can be a real (approximately the number of nanoseconds taken), or
`MaxUtilization()` (utilizes all processors of this type). By default, the
scheduler assumes that this thunk only uses one processor.
- `alloc_util::Dict{Type,UInt64}`: Indicates the maximum expected memory
utilization for this thunk. Each keypair maps a processor type to the
utilization, where the value is an integer representing approximately the
maximum number of bytes allocated at any one time.
- `occupancy::Dict{Type,Real}`: Indicates the maximum expected processor
occupancy for this thunk. Each keypair maps a processor type to the
utilization, where the value can be a real between 0 and 1 (the occupancy
ratio, where 1 is full occupancy). By default, the scheduler assumes that this
thunk has full occupancy.
- `allow_errors::Bool=true`: Allow this thunk to error without affecting
non-dependent thunks.
- `checkpoint=nothing`: If not `nothing`, uses the provided function to save
the result of the thunk to persistent storage, for later retrieval by
`restore`.
- `restore=nothing`: If not `nothing`, uses the provided function to return the
(cached) result of this thunk, were it to execute. If this returns a `Chunk`,
this thunk will be skipped, and its result will be set to the `Chunk`. If
`nothing` is returned, restoring is skipped, and the thunk will execute as
usual. If this function throws an error, restoring will be skipped, and the
error will be displayed.
- `storage::Union{Chunk,Nothing}=nothing`: If not `nothing`, references a
`MemPool.StorageDevice` which will be passed to `MemPool.poolset` internally
when constructing `Chunk`s (such as when constructing the return value). The
device must support `MemPool.CPURAMResource`. When `nothing`, uses
`MemPool.GLOBAL_DEVICE[]`.
- `storage_root_tag::Any=nothing`: If not `nothing`,
specifies the MemPool storage leaf tag to associate with the thunk's result.
This tag can be used by MemPool's storage devices to manipulate their behavior,
such as the file name used to store data on disk."
- `storage_leaf_tag::MemPool.Tag,Nothing}=nothing`: If not `nothing`,
specifies the MemPool storage leaf tag to associate with the thunk's result.
This tag can be used by MemPool's storage devices to manipulate their behavior,
such as the file name used to store data on disk."
- `storage_retain::Bool=false`: The value of `retain` to pass to
`MemPool.poolset` when constructing the result `Chunk`.
"""
Base.@kwdef struct ThunkOptions
single::Union{Int,Nothing} = nothing
proclist = nothing
time_util::Union{Dict{Type,Any},Nothing} = nothing
alloc_util::Union{Dict{Type,UInt64},Nothing} = nothing
occupancy::Union{Dict{Type,Real},Nothing} = nothing
allow_errors::Union{Bool,Nothing} = nothing
checkpoint = nothing
restore = nothing
storage::Union{Chunk,Nothing} = nothing
storage_root_tag = nothing
storage_leaf_tag::Union{MemPool.Tag,Nothing} = nothing
storage_retain::Bool = false
end
"""
Base.merge(sopts::SchedulerOptions, topts::ThunkOptions) -> ThunkOptions
Combine `SchedulerOptions` and `ThunkOptions` into a new `ThunkOptions`.
"""
function Base.merge(sopts::SchedulerOptions, topts::ThunkOptions)
select_option = (sopt, topt) -> isnothing(topt) ? sopt : topt
single = select_option(sopts.single, topts.single)
allow_errors = select_option(sopts.allow_errors, topts.allow_errors)
proclist = select_option(sopts.proclist, topts.proclist)
ThunkOptions(single,
proclist,
topts.time_util,
topts.alloc_util,
topts.occupancy,
allow_errors,
topts.checkpoint,
topts.restore,
topts.storage,
topts.storage_root_tag,
topts.storage_leaf_tag,
topts.storage_retain)
end
Base.merge(sopts::SchedulerOptions, ::Nothing) =
ThunkOptions(sopts.single,
sopts.proclist,
nothing,
nothing,
sopts.allow_errors)
"""
populate_defaults(opts::ThunkOptions, Tf, Targs) -> ThunkOptions
Returns a `ThunkOptions` with default values filled in for a function of type
`Tf` with argument types `Targs`, if the option was previously unspecified in
`opts`.
"""
function populate_defaults(opts::ThunkOptions, Tf, Targs)
function maybe_default(opt::Symbol)
old_opt = getproperty(opts, opt)
if old_opt !== nothing
return old_opt
else
return Dagger.default_option(Val(opt), Tf, Targs...)
end
end
ThunkOptions(
maybe_default(:single),
maybe_default(:proclist),
maybe_default(:time_util),
maybe_default(:alloc_util),
maybe_default(:occupancy),
maybe_default(:allow_errors),
maybe_default(:checkpoint),
maybe_default(:restore),
maybe_default(:storage),
maybe_default(:storage_root_tag),
maybe_default(:storage_leaf_tag),
maybe_default(:storage_retain),
)
end
# Eager scheduling
include("eager.jl")
const WORKER_MONITOR_LOCK = Threads.ReentrantLock()
const WORKER_MONITOR_TASKS = Dict{Int,Task}()
const WORKER_MONITOR_CHANS = Dict{Int,Dict{UInt64,RemoteChannel}}()
function init_proc(state, p, log_sink)
ctx = Context(Int[]; log_sink)
timespan_start(ctx, :init_proc, (;uid=state.uid, worker=p.pid), nothing)
# Initialize pressure and capacity
gproc = OSProc(p.pid)
lock(state.lock) do
state.worker_time_pressure[p.pid] = Dict{Processor,UInt64}()
state.worker_storage_pressure[p.pid] = Dict{Union{StorageResource,Nothing},UInt64}()
state.worker_storage_capacity[p.pid] = Dict{Union{StorageResource,Nothing},UInt64}()
#= FIXME
for storage in get_storage_resources(gproc)
pressure, capacity = remotecall_fetch(gproc.pid, storage) do storage
storage_pressure(storage), storage_capacity(storage)
end
state.worker_storage_pressure[p.pid][storage] = pressure
state.worker_storage_capacity[p.pid][storage] = capacity
end
=#
state.worker_loadavg[p.pid] = (0.0, 0.0, 0.0)
end
if p.pid != 1
lock(WORKER_MONITOR_LOCK) do
wid = p.pid
if !haskey(WORKER_MONITOR_TASKS, wid)
t = Threads.@spawn begin
try
# Wait until this connection is terminated
remotecall_fetch(sleep, wid, typemax(UInt64))
catch err
# TODO: Report other kinds of errors? IOError, etc.
#if !(err isa ProcessExitedException)
#end
finally
lock(WORKER_MONITOR_LOCK) do
d = WORKER_MONITOR_CHANS[wid]
for uid in keys(d)
try
put!(d[uid], (wid, OSProc(wid), nothing, (ProcessExitedException(wid), nothing)))
catch
end
end
empty!(d)
delete!(WORKER_MONITOR_CHANS, wid)
delete!(WORKER_MONITOR_TASKS, wid)
end
end
end
errormonitor_tracked("worker monitor $wid", t)
WORKER_MONITOR_TASKS[wid] = t
WORKER_MONITOR_CHANS[wid] = Dict{UInt64,RemoteChannel}()
end
WORKER_MONITOR_CHANS[wid][state.uid] = state.chan
end
end
# Setup worker-to-scheduler channels
inp_chan = RemoteChannel(p.pid)
out_chan = RemoteChannel(p.pid)
lock(state.lock) do
state.worker_chans[p.pid] = (inp_chan, out_chan)
end
# Setup dynamic listener
dynamic_listener!(ctx, state, p.pid)
timespan_finish(ctx, :init_proc, (;uid=state.uid, worker=p.pid), nothing)
end
function _cleanup_proc(uid, log_sink)
empty!(CHUNK_CACHE) # FIXME: Should be keyed on uid!
proc_states(uid) do states
for (proc, state) in states
istate = state.state
istate.done[] = true
notify(istate.reschedule)
end
empty!(states)
end
end
function cleanup_proc(state, p, log_sink)
ctx = Context(Int[]; log_sink)
wid = p.pid
timespan_start(ctx, :cleanup_proc, (;uid=state.uid, worker=wid), nothing)
lock(WORKER_MONITOR_LOCK) do
if haskey(WORKER_MONITOR_CHANS, wid)
delete!(WORKER_MONITOR_CHANS[wid], state.uid)
end
end
# If the worker process is still alive, clean it up
if wid in workers()
try
remotecall_wait(_cleanup_proc, wid, state.uid, log_sink)
catch ex
# We allow ProcessExitedException's, which means that the worker
# shutdown halfway through cleanup.
if !(ex isa ProcessExitedException)
rethrow()
end
end
end
timespan_finish(ctx, :cleanup_proc, (;uid=state.uid, worker=wid), nothing)
end
"Process-local condition variable (and lock) indicating task completion."
const TASK_SYNC = Threads.Condition()
"Process-local set of running task IDs."
const TASKS_RUNNING = Set{Int}()
"Process-local dictionary tracking per-processor total time utilization."
const PROCESSOR_TIME_UTILIZATION = Dict{UInt64,Dict{Processor,Ref{UInt64}}}()
# TODO: "Process-local count of actively-executing Dagger tasks per processor type."
"""
MaxUtilization
Indicates a thunk that uses all processors of a given type.
"""
struct MaxUtilization end
function compute_dag(ctx, d::Thunk; options=SchedulerOptions())
if options === nothing
options = SchedulerOptions()
end
ctx.options = options
if options.restore !== nothing
try
result = options.restore()
if result isa Chunk
return result
elseif result !== nothing
throw(ArgumentError("Invalid restore return type: $(typeof(result))"))
end
catch err
report_catch_error(err, "Scheduler restore failed")
end
end
chan = RemoteChannel(()->Channel(typemax(Int)))
deps = dependents(d)
ord = order(d, noffspring(deps))
node_order = x -> -get(ord, x, 0)
state = start_state(deps, node_order, chan)
master = OSProc(myid())
timespan_start(ctx, :scheduler_init, (;uid=state.uid), master)
try
scheduler_init(ctx, state, d, options, deps)
finally
timespan_finish(ctx, :scheduler_init, (;uid=state.uid), master)
end
value, errored = try
scheduler_run(ctx, state, d, options)
finally
# Always try to tear down the scheduler
timespan_start(ctx, :scheduler_exit, (;uid=state.uid), master)
try
scheduler_exit(ctx, state, options)
catch err
@error "Error when tearing down scheduler" exception=(err,catch_backtrace())
finally
timespan_finish(ctx, :scheduler_exit, (;uid=state.uid), master)
end
end
if errored
throw(value)
end
return value
end
function scheduler_init(ctx, state::ComputeState, d::Thunk, options, deps)
# setup thunk_dict mappings
for node in filter(istask, keys(deps))
state.thunk_dict[node.id] = WeakThunk(node)
for dep in deps[node]
state.thunk_dict[dep.id] = WeakThunk(dep)
end
end
# Initialize workers
@sync for p in procs_to_use(ctx)
Threads.@spawn begin
try
init_proc(state, p, ctx.log_sink)
catch err
@error "Error initializing worker $p" exception=(err,catch_backtrace())
remove_dead_proc!(ctx, state, p)
end
end
end
# Halt scheduler on Julia exit
atexit() do
notify(state.halt)
end
# Listen for new workers
Threads.@spawn begin
try
monitor_procs_changed!(ctx, state)
catch err
@error "Error assigning workers" exception=(err,catch_backtrace())
end
end
end
function scheduler_run(ctx, state::ComputeState, d::Thunk, options)
@dagdebug nothing :global "Initializing scheduler" uid=state.uid
safepoint(state)
# Loop while we still have thunks to execute
while !isempty(state.ready) || !isempty(state.running)
if !isempty(state.ready)
# Nothing running, so schedule up to N thunks, 1 per N workers
schedule!(ctx, state)
end
check_integrity(ctx)
isempty(state.running) && continue
timespan_start(ctx, :take, (;uid=state.uid), nothing)
@dagdebug nothing :take "Waiting for results"
chan_value = take!(state.chan) # get result of completed thunk
timespan_finish(ctx, :take, (;uid=state.uid), nothing)
if chan_value isa RescheduleSignal
continue
end
pid, proc, thunk_id, (res, metadata) = chan_value
@dagdebug thunk_id :take "Got finished task"
gproc = OSProc(pid)
safepoint(state)
lock(state.lock) do
thunk_failed = false
if res isa Exception
if unwrap_nested_exception(res) isa ProcessExitedException
@warn "Worker $(pid) died, rescheduling work"
# Remove dead worker from procs list
timespan_start(ctx, :remove_procs, (;uid=state.uid, worker=pid), nothing)
remove_dead_proc!(ctx, state, gproc)
timespan_finish(ctx, :remove_procs, (;uid=state.uid, worker=pid), nothing)
timespan_start(ctx, :handle_fault, (;uid=state.uid, worker=pid), nothing)
handle_fault(ctx, state, gproc)
timespan_finish(ctx, :handle_fault, (;uid=state.uid, worker=pid), nothing)
return # effectively `continue`
else
if something(ctx.options.allow_errors, false) ||
something(unwrap_weak_checked(state.thunk_dict[thunk_id]).options.allow_errors, false)
thunk_failed = true
else
throw(res)
end
end
end
node = unwrap_weak_checked(state.thunk_dict[thunk_id])
if metadata !== nothing
state.worker_time_pressure[pid][proc] = metadata.time_pressure
#to_storage = fetch(node.options.storage)
#state.worker_storage_pressure[pid][to_storage] = metadata.storage_pressure
#state.worker_storage_capacity[pid][to_storage] = metadata.storage_capacity
state.worker_loadavg[pid] = metadata.loadavg
sig = signature(state, node)
state.signature_time_cost[sig] = (metadata.threadtime + get(state.signature_time_cost, sig, 0)) ÷ 2
state.signature_alloc_cost[sig] = (metadata.gc_allocd + get(state.signature_alloc_cost, sig, 0)) ÷ 2
if metadata.transfer_rate !== nothing
state.transfer_rate[] = (state.transfer_rate[] + metadata.transfer_rate) ÷ 2
end
end
state.cache[node] = res
state.errored[node] = thunk_failed
if node.options !== nothing && node.options.checkpoint !== nothing
try
@invokelatest node.options.checkpoint(node, res)
catch err
report_catch_error(err, "Thunk checkpoint failed")
end
end
timespan_start(ctx, :finish, (;uid=state.uid, thunk_id), (;thunk_id, result=res))
finish_task!(ctx, state, node, thunk_failed)
timespan_finish(ctx, :finish, (;uid=state.uid, thunk_id), (;thunk_id, result=res))
delete_unused_tasks!(state)
end
safepoint(state)
end
# Final value is ready
value = state.cache[d]
errored = get(state.errored, d, false)
if !errored
if options.checkpoint !== nothing
try
options.checkpoint(value)
catch err
report_catch_error(err, "Scheduler checkpoint failed")
end
end
end
return value, errored
end
function scheduler_exit(ctx, state::ComputeState, options)
@dagdebug nothing :global "Tearing down scheduler" uid=state.uid
@sync for p in procs_to_use(ctx)
Threads.@spawn cleanup_proc(state, p, ctx.log_sink)
end
lock(state.lock) do
close(state.chan)
notify(state.halt)
# Notify any waiting tasks
for (_, futures) in state.futures
for future in futures
put!(future, SchedulingException("Scheduler exited"); error=true)
end
end
empty!(state.futures)
end
# Let the context procs handler clean itself up
lock(ctx.proc_notify) do
notify(ctx.proc_notify)
end
@dagdebug nothing :global "Tore down scheduler" uid=state.uid
end
function procs_to_use(ctx, options=ctx.options)
return if options.single !== nothing
@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."
struct SchedulingException <: Exception
reason::String
end
function Base.show(io::IO, se::SchedulingException)
print(io, "SchedulingException ($(se.reason))")
end
const CHUNK_CACHE = Dict{Chunk,Dict{Processor,Any}}()
function schedule!(ctx, state, procs=procs_to_use(ctx))
lock(state.lock) do
safepoint(state)
@assert length(procs) > 0
# Remove processors that aren't yet initialized
procs = filter(p -> haskey(state.worker_chans, Dagger.root_worker_id(p)), procs)
populate_processor_cache_list!(state, procs)
# Schedule tasks
to_fire = Dict{Tuple{OSProc,<:Processor},Vector{Tuple{Thunk,<:Any,<:Any,UInt64,UInt32}}}()
failed_scheduling = Thunk[]
# Select a new task and get its options
task = nothing
@label pop_task
if task !== nothing
timespan_finish(ctx, :schedule, (;uid=state.uid, thunk_id=task.id), (;thunk_id=task.id))
end
if isempty(state.ready)
@goto fire_tasks
end
task = pop!(state.ready)
timespan_start(ctx, :schedule, (;uid=state.uid, thunk_id=task.id), (;thunk_id=task.id))
if haskey(state.cache, task)
if haskey(state.errored, task)
# An error was eagerly propagated to this task
finish_failed!(state, task)
else
# This shouldn't have happened
iob = IOBuffer()
println(iob, "Scheduling inconsistency: Task being scheduled is already cached!")
println(iob, " Task: $(task.id)")
println(iob, " Cache Entry: $(typeof(state.cache[task]))")
ex = SchedulingException(String(take!(iob)))
state.cache[task] = ex
state.errored[task] = true
end
@goto pop_task
end
opts = merge(ctx.options, task.options)
sig = signature(state, task)
# Calculate scope
scope = if task.f isa Chunk
task.f.scope
else
if task.options.proclist !== nothing
# proclist overrides scope selection
AnyScope()
else
DefaultScope()
end
end
for (_,input) in task.inputs
input = unwrap_weak_checked(input)
chunk = if istask(input)
state.cache[input]
elseif input isa Chunk
input
else
nothing
end
chunk isa Chunk || continue
scope = constrain(scope, chunk.scope)
if scope isa Dagger.InvalidScope
ex = SchedulingException("Scopes are not compatible: $(scope.x), $(scope.y)")
state.cache[task] = ex
state.errored[task] = true
set_failed!(state, task)
@goto pop_task
end
end
fallback_threshold = 1024 # TODO: Parameterize this threshold
if length(procs) > fallback_threshold
@goto fallback
end
local_procs = unique(vcat([collect(Dagger.get_processors(gp)) for gp in procs]...))
if length(local_procs) > fallback_threshold
@goto fallback
end
inputs = map(last, collect_task_inputs(state, task))
opts = populate_defaults(opts, chunktype(task.f), map(chunktype, inputs))
local_procs, costs = estimate_task_costs(state, local_procs, task, inputs)
scheduled = false
# Move our corresponding ThreadProc to be the last considered
if length(local_procs) > 1
sch_threadproc = Dagger.ThreadProc(myid(), Threads.threadid())
sch_thread_idx = findfirst(proc->proc==sch_threadproc, local_procs)
if sch_thread_idx !== nothing
deleteat!(local_procs, sch_thread_idx)
push!(local_procs, sch_threadproc)
end
end
for proc in local_procs
gproc = get_parent(proc)
can_use, scope = can_use_proc(state, task, gproc, proc, opts, scope)
if can_use
has_cap, est_time_util, est_alloc_util, est_occupancy =
has_capacity(state, proc, gproc.pid, opts.time_util, opts.alloc_util, opts.occupancy, sig)
if has_cap
# Schedule task onto proc
# FIXME: est_time_util = est_time_util isa MaxUtilization ? cap : est_time_util
proc_tasks = get!(to_fire, (gproc, proc)) do
Vector{Tuple{Thunk,<:Any,<:Any,UInt64,UInt32}}()
end
push!(proc_tasks, (task, scope, est_time_util, est_alloc_util, est_occupancy))
state.worker_time_pressure[gproc.pid][proc] =
get(state.worker_time_pressure[gproc.pid], proc, 0) +
est_time_util
@dagdebug task :schedule "Scheduling to $gproc -> $proc"
@goto pop_task
end
end
end
state.cache[task] = SchedulingException("No processors available, try widening scope")
state.errored[task] = true
set_failed!(state, task)
@goto pop_task
# Fast fallback algorithm, used when the smarter cost model algorithm
# would be too expensive
@label fallback
selected_entry = nothing
entry = state.procs_cache_list[]
cap, extra_util = nothing, nothing
procs_found = false
# N.B. if we only have one processor, we need to select it now
can_use, scope = can_use_proc(state, task, entry.gproc, entry.proc, opts, scope)
if can_use
has_cap, est_time_util, est_alloc_util, est_occupancy =
has_capacity(state, entry.proc, entry.gproc.pid, opts.time_util, opts.alloc_util, opts.occupancy, sig)
if has_cap
selected_entry = entry
else
procs_found = true
entry = entry.next
end
else
entry = entry.next
end
while selected_entry === nothing
if entry === state.procs_cache_list[]
# Exhausted all procs
if procs_found
push!(failed_scheduling, task)
else
state.cache[task] = SchedulingException("No processors available, try widening scope")
state.errored[task] = true
set_failed!(state, task)
end
@goto pop_task
end
can_use, scope = can_use_proc(state, task, entry.gproc, entry.proc, opts, scope)
if can_use
has_cap, est_time_util, est_alloc_util, est_occupancy =
has_capacity(state, entry.proc, entry.gproc.pid, opts.time_util, opts.alloc_util, opts.occupancy, sig)
if has_cap
# Select this processor
selected_entry = entry
else
# We could have selected it otherwise
procs_found = true
entry = entry.next
end
else
# Try next processor
entry = entry.next
end
end
@assert selected_entry !== nothing
# Schedule task onto proc
gproc, proc = entry.gproc, entry.proc
est_time_util = est_time_util isa MaxUtilization ? cap : est_time_util
proc_tasks = get!(to_fire, (gproc, proc)) do
Vector{Tuple{Thunk,<:Any,<:Any,UInt64,UInt32}}()
end
push!(proc_tasks, (task, scope, est_time_util, est_alloc_util, est_occupancy))
# Proceed to next entry to spread work
state.procs_cache_list[] = state.procs_cache_list[].next
@goto pop_task
# Fire all newly-scheduled tasks
@label fire_tasks
for gpp in keys(to_fire)
fire_tasks!(ctx, to_fire[gpp], gpp, state)
end
append!(state.ready, failed_scheduling)
end
end
"""
Monitors for workers being added/removed to/from `ctx`, sets up or tears down
per-worker state, and notifies the scheduler so that work can be reassigned.
"""
function monitor_procs_changed!(ctx, state)
# Load current set of procs
old_ps = procs_to_use(ctx)
while !state.halt.set
# Wait for the notification that procs have changed
lock(ctx.proc_notify) do
wait(ctx.proc_notify)
end
timespan_start(ctx, :assign_procs, (;uid=state.uid), nothing)
# Load new set of procs
new_ps = procs_to_use(ctx)
# Initialize new procs
diffps = setdiff(new_ps, old_ps)
for p in diffps
init_proc(state, p, ctx.log_sink)
# Empty the processor cache list and force reschedule
lock(state.lock) do
state.procs_cache_list[] = nothing
end
put!(state.chan, RescheduleSignal())
end
# Cleanup removed procs
diffps = setdiff(old_ps, new_ps)
for p in diffps
cleanup_proc(state, p, ctx.log_sink)
# Empty the processor cache list
lock(state.lock) do
state.procs_cache_list[] = nothing
end
end
timespan_finish(ctx, :assign_procs, (;uid=state.uid), nothing)
old_ps = new_ps
end
end
function remove_dead_proc!(ctx, state, proc, options=ctx.options)
@assert options.single !== proc.pid "Single worker failed, cannot continue."
rmprocs!(ctx, [proc])
delete!(state.worker_time_pressure, proc.pid)
delete!(state.worker_storage_pressure, proc.pid)
delete!(state.worker_storage_capacity, proc.pid)
delete!(state.worker_loadavg, proc.pid)
delete!(state.worker_chans, proc.pid)
state.procs_cache_list[] = nothing
end
function finish_task!(ctx, state, node, thunk_failed)
pop!(state.running, node)
delete!(state.running_on, node)
if thunk_failed
set_failed!(state, node)
end
if node.cache
node.cache_ref = state.cache[node]
end
schedule_dependents!(state, node, thunk_failed)
fill_registered_futures!(state, node, thunk_failed)
to_evict = cleanup_syncdeps!(state, node)
if node.f isa Chunk
# FIXME: Check the graph for matching chunks
push!(to_evict, node.f)
end
if haskey(state.waiting_data, node) && isempty(state.waiting_data[node])
delete!(state.waiting_data, node)
end
#evict_all_chunks!(ctx, to_evict)
end
function delete_unused_tasks!(state)
to_delete = Thunk[]
for thunk in state.thunks_to_delete
if task_unused(state, thunk)
# Finished and nobody waiting on us, we can be deleted
push!(to_delete, thunk)
end
end
for thunk in to_delete
# Delete all cached data
task_delete!(state, thunk)
pop!(state.thunks_to_delete, thunk)
end
end
function delete_unused_task!(state, thunk)
if task_unused(state, thunk)
# Will not be accessed further, delete all cached data
task_delete!(state, thunk)
return true
else
return false
end
end
task_unused(state, thunk) =
haskey(state.cache, thunk) && !haskey(state.waiting_data, thunk)
function task_delete!(state, thunk)
delete!(state.cache, thunk)
delete!(state.errored, thunk)
delete!(state.valid, thunk)
delete!(state.thunk_dict, thunk.id)
end
function evict_all_chunks!(ctx, to_evict)
if !isempty(to_evict)
@sync for w in map(p->p.pid, procs_to_use(ctx))