-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimegrid.py
1575 lines (1352 loc) · 52.9 KB
/
primegrid.py
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
#!/usr/bin/env python3
import os
import re
import json
import sys
import subprocess
import time
import argparse
import math
import glob
import asyncio
import tempfile
import shutil
import signal
import traceback
import json
import numpy as np
import scipy.stats
import logging
logger = logging.getLogger(__name__)
DEBUG = logger.debug
INFO = logger.info
WARNING = logger.warning
ERROR = logger.error
CRITICAL = logger.critical
cputasks = [
re.compile(r'^primegrid_llr'),
re.compile(r'setiathome'),
re.compile(r'rosetta_')
]
gputasks = [
re.compile(r'cudaPPSsieve'),
re.compile(r'primegrid_genefer'),
]
selftasks = [
re.compile(re.escape('primegrid.py')),
re.compile(re.escape(sys.argv[0]))
]
PROC = "/proc"
LLR_RE = re.compile('[\n\r\b]+')
DIGITS = re.compile(r'\d+$')
original_sigint_handler = signal.getsignal(signal.SIGINT)
def call(*args, **kwargs):
DEBUG(" ".join([a for arg in args for a in arg]))
subprocess.call(*args, **kwargs)
def acse(*args, **kwargs):
#DEBUG(" ".join(args))
return asyncio.create_subprocess_exec(*args, **kwargs)
def slurp(*args):
path = os.path.join(*args)
return open(path, 'r').read().rstrip()
def slurp_output(*args, **kwargs):
r = subprocess.run(args, capture_output=True, **kwargs)
return r.stdout.decode('ascii')
def dump(thing):
DEBUG(json.dumps(thing, indent=2, sort_keys=True))
def is_self(pid, cmdline):
#DEBUG(str(pid) + " " + str(len(cmdline)) + ": " + cmdline)
for e in selftasks:
if e.search(cmdline) is not None and pid != os.getpid():
ERROR("Another copy of this script is running on PID " + str(pid))
sys.exit(1)
def ps_aux(f):
for i in os.listdir(PROC):
m = DIGITS.match(i)
if m is not None:
pid = int(i)
try:
cmd = " ".join((slurp(PROC, i, 'cmdline').split('\0')))
except IOError as e:
continue
if len(cmd) == 0:
continue
f(pid, cmd)
def argmin(d):
return min(d, key=d.get)
class NSet:
__slots__ = ('s','d')
def __init__(self, i=None):
if isinstance(i, set):
self.s = set(i)
self.d = {
x.n:x for x in i
}
elif isinstance(i, dict):
self.s = set(i.values())
self.d = dict(i)
elif i is None:
self.s = set()
self.d = dict()
else:
raise ValueError()
def add(self, x):
assert x not in self.s
assert x not in self.d.values()
self.s.add(x)
self.d[x.n] = x
def __getitem__(self, key):
return self.d[key]
def __len__(self, key):
return len(self.s)
def __setitem__(self, key, value):
assert key == value.n
self.add(value)
def __contains__(self, item):
return item in self.s or item in self.d
def __delitem__(self, item):
if item in self.d:
#self.s.remove(d[item])
del self.d[item]
else:
raise KeyError()
def remove(self, item):
if item in self.s:
self.s.remove(item)
del self.d[item.n]
else:
raise KeyError()
def without(self, item):
new = self.__class__(self)
if item in self.s:
new.remove(item)
elif item in self.d:
del new[item]
else:
raise KeyError()
return new
def union(self, *others):
return self.__class__(self.s.union(*[o.s for o in others]))
def difference(self, *others):
return self.__class__(self.s.difference(*[o.s for o in others]))
def minimum(self):
precision = 0.0001
ub = 1+precision
lb = 1-precision
minweight = math.inf
minprocs = self.s
for i in self.s:
w = i.weight()
if w < (minweight * lb):
minprocs = [i]
minweight = w
elif w > (minweight * lb) and (w < minweight * ub):
minprocs.append(i)
minprocs = sorted(minprocs, key=lambda x: x.n)
return minprocs[0]
def sorted(self):
return sorted(self.s, key=lambda x: x.n)
def __iter__(self):
return self.s.__iter__()
def __len__(self):
return self.s.__len__()
class ProcessorSet(NSet):
def without_core(self, core):
new = ProcessorSet(self)
new.d = {
n:p for n,p in new.d.items()
if p.core != core
}
new.s = {
p for p in p
if p.core != core
}
return new
def cores(self):
return CoreSet({
p.core for p in self.s
})
def weight(self):
return sum([p.weight() for p in self.s])
def as_string(self):
return ','.join(map(str, new.d.keys()))
def get_cur_freq(self):
fs = [p.get_cur_freq() for p in self.s]
return sum(fs)//len(fs)
def get_min_freq(self):
fs = [p.get_min_freq() for p in self.s]
return max(fs)
def get_max_freq(self):
fs = [p.get_max_freq() for p in self.s]
return min(fs)
def get_lim_freq(self):
fs = [p.get_lim_freq() for p in self.s]
return min(fs)
def set_lim_freq(self, khz):
for p in self.s:
p.set_lim_freq(khz)
def detect_throttle(self):
throttled = False
for p in self.s:
if p.detect_throttle():
throttled = True
return throttled
class CoreSet(NSet):
def processors(self):
ps = ProcessorSet()
return ps.union(*[
c.processors for c in self.s
])
def packages(self):
return PackageSet({
c.pkg for p in self.s
})
def minimum_core_processor(self):
""" Return the freest processor on the freest core """
return self.minimum().processors.minimum()
class PackageSet(NSet):
def processors(self):
ps = ProcessorSet()
return ps.union(*[
pkg.processors for pkg in self.s
])
def cores(self):
cs = CoreSet()
return cs.union(*[
pkg.cores for pkg in self.s
])
def recursive_minimum(self):
""" Return the freest processor on the freest core on the freest processor """
return self.minimum().cores.minimum_core_processor()
class Numbered:
def __init__(self, n):
self.n = n
def __hash__(self):
return hash((self.__class__, self.n))
class Processor(Numbered):
def init_topology(self):
self.topology.processors.add(self)
self.core_n = int(slurp(self.directory,"topology/core_id"))
if not self.core_n in self.topology.cores:
Core(self.core_n, self.topology)
self.core = self.topology.cores[self.core_n]
self.core.processors.add(self)
self.pkg_n = int(slurp(self.directory,
"topology/physical_package_id"))
if not self.pkg_n in self.topology.pkgs:
Package(self.pkg_n, self.topology)
self.pkg = self.topology.pkgs[self.pkg_n]
self.pkg.processors.add(self)
self.core.bind_package(self.pkg)
def init_regulator(self):
self.max_freq_fn = self.directory + '/cpufreq/cpuinfo_max_freq'
self.min_freq_fn = self.directory + '/cpufreq/cpuinfo_min_freq'
self.lim_freq_fn = self.directory + '/cpufreq/scaling_max_freq'
self.cur_freq_fn = self.directory + '/cpufreq/scaling_cur_freq'
self.max_freq = self.get_max_freq()
self.min_freq = self.get_min_freq()
self.ctc = None
self.ptc = None
self.ctc_fn = (self.directory
+ '/thermal_throttle/core_throttle_count')
self.ptc_fn = (self.directory
+ '/thermal_throttle/package_throttle_count')
if os.path.isfile(self.ctc_fn):
self.ctc = int(slurp(self.ctc_fn))
if os.path.isfile(self.ptc_fn):
self.ptc = int(slurp(self.ptc_fn))
def __init__(self, n, topology):
super().__init__(n)
self.topology = topology
self.threads = dict()
self.directory = self.topology.base + "/cpu" + str(self.n)
self.init_topology()
self.init_regulator()
def siblings(self):
assert self in self.core.processors
r = {p for p in self.core.processors
if p is not self }
return r
def weight(self):
return sum(self.threads.values())
def assign(self, tid, weight):
self.threads[tid] = weight
#DEBUG("Processor " + str(self.n) + " weight " + str(self.weight()))
def unassign(self, tid):
del self.threads[tid]
def get_max_freq(self):
return int(slurp(self.max_freq_fn))
def get_min_freq(self):
return int(slurp(self.min_freq_fn))
def get_lim_freq(self):
return int(slurp(self.lim_freq_fn))
def set_lim_freq(self, khz):
khzstr = str(int(khz))
with open(self.lim_freq_fn, 'w') as limit:
limit.write(khzstr)
limit.flush()
time.sleep(0.01)
got = self.get_lim_freq()
if (got != int(khzstr)):
ERROR(f"Couldn't set frequency limit to {khzstr}, got {got}")
def get_cur_freq(self):
return int(slurp(self.cur_freq_fn))
def is_idle(self):
lines = slurp('/proc/stat').splitlines()
for line in lines:
if line.startswith('cpu' + str(self.n)):
fields = line.split()
fields = [int(f) for f in fields[1:]]
total = sum(fields)
idle = fields[3]
if idle/total > 0.75:
return True
else:
return False
ERROR("Couldn't determin if processor is idle...")
def detect_throttle(self):
throttled = False
if self.ctc is not None:
new_ctc = int(slurp(self.ctc_fn))
if new_ctc > self.ctc:
self.ctc = new_ctc
DEBUG(f"Processor {self.n} core throttle count increased!")
throttled = True
if self.ptc is not None:
new_ptc = int(slurp(self.ptc_fn))
if new_ptc > self.ptc:
self.ptc = new_ptc
DEBUG(f"Processor {self.n} package throttle count increased!")
throttled = True
if self.ctc is None and self.ptc is None:
if not self.is_idle():
cur_freq = self.core.get_cur_freq()
lim_freq = self.core.get_lim_freq()
if cur_freq < lim_freq - 200000:
INFO("Core {} frequency is {:.2f}. It's probably throttling."
.format(self.core.n, cur_freq/1000000))
throttled = True
return throttled
class Core(Numbered):
def __init__(self, n, topology):
super().__init__(n)
self.processors = ProcessorSet()
self.topology = topology
self.topology.cores.add(self)
self.pkg = None
def bind_package(self, pkg):
if self.pkg is None:
self.pkg = pkg
self.pkg.cores.add(self)
else:
assert pkg is self.pkg
assert self.n in self.pkg.cores
def weight(self):
return self.processors.weight()
def get_freeest_processor(self):
return self.processors.minimum()
class Package(Numbered):
def __init__(self, n, topology):
super().__init__(n)
self.processors = ProcessorSet()
self.cores = CoreSet()
self.topology = topology
self.topology.pkgs.add(self)
def weight(self):
return self.processors.weight()
class Topology:
"""400-level maths"""
base = "/sys/devices/system/cpu"
def __init__(self):
self.cores = CoreSet()
self.processors = ProcessorSet()
self.pkgs = PackageSet()
self.read_topology()
def read_each(self, f):
for i in os.listdir(self.base):
m = re.match(r'cpu(\d+)', i)
if m is not None:
f(m)
def read_topology(self):
def processor(i):
processor_n = int(i[1])
Processor(processor_n, self)
self.read_each(processor)
def siblings(i):
processor_siblings = slurp(self.base,i[0],"topology/thread_siblings_list")
#TODO: make sure this checks out
self.read_each(siblings)
for pkg in self.pkgs.sorted():
INFO("Package {}:".format(pkg.n))
for core in pkg.cores.sorted():
INFO(" Core {}:".format(core.n))
assert pkg is core.pkg
for p in core.processors.sorted():
INFO(" Processor {}:".format(p.n))
assert pkg is p.pkg
assert core is p.core
def get_freeest_processor(self):
return self.pkgs.recursive_minimum()
class GPU:
irqs = "/proc/irq"
affinity_file = "smp_affinity_list"
def __init__(self, topology):
self.read_irq()
self.read_processors()
self.topology = topology
def read_irq(self):
self.gpu_irq = None
for i in os.listdir(irqs):
if os.path.isdir(os.path.join(irqs, i)):
if os.path.isdir(os.path.join(irqs, i, 'nvidia')):
self.gpu_irq = i
def read_processors(self):
affinity = slurp(self.irqs, self.gpu_irq, self.affinity_file)
self.processors = ProcessorSet({
self.topology.processors[int(n)]
for n in re.split('[,-]', affinity)
})
def cores(self):
return self.processor().core
def set_core(self, gpu_irq, core):
with open(os.path.join(self.irqs, gpu_irq, self.affinity_file), 'w') as affinity:
affinity.write(','.join([str(i) for i in core.processors.keys()]))
affinity.flush()
def non_gpu_cores(self):
return self.topology.cores.difference(self.processors.cores())
def non_gpu_processors(self):
return self.non_gpu_cores().processors()
class Thread:
def __init__(self, job, tid, weight):
self.job = job
self.tid = tid
self.weight = weight
self.processors = None
def assign_free(self, processors):
self.processors = processors
for p in self.processors:
p.assign(self.tid, self.weight/len(self.processors))
self.affine()
def assign(self, processor, ahs):
if ahs:
self.processors = processor.core.processors
else:
self.processors = {processor}
self.assign_free(self.processors)
def affine(self):
procs = ','.join([str(p.n) for p in self.processors])
taskset = ['taskset', '-p', '-c']
call(taskset + [procs, str(self.tid)], stdout=subprocess.DEVNULL)
#call(taskset + [procs, str(self.tid)])
def unassign(self):
for p in self.processors:
p.unassign(self.tid)
class Job:
kind = None
def __init__(self, pid, schedule):
self.pid = pid
self.schedule = schedule
self.topology = schedule.topology
self.state = 'new'
self.threads = self.get_threads()
def get_threads(self):
tids = list(os.listdir(os.path.join(PROC, str(self.pid), 'task')))
#DEBUG(repr(tids))
threads = []
for i in range(0, len(tids)):
if i == 0:
weight = 1.0
else:
weight = 0.9
threads.append(Thread(self, tids[i], weight))
#DEBUG("Threads: " + str(len(threads)))
return threads
class GPUJob(Job):
kind = 'gpu'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight = 0.2
def assign(self, processor, ahs):
if ahs:
self.processors = processor.siblings()
else:
self.processors = {processor}
for p in self.processors:
p.assign(self.pid, self.weight/len(self.processors))
self.affine()
def affine(self):
procs = ','.join([str(p.n) for p in self.processors])
taskset = ['taskset', '-a', '-p', '-c']
call(taskset + [procs, str(self.pid)])
if self.schedule.options.realtime_gpu:
call(['chrt', '-a', '-f', '-p', '1', str(self.pid)])
def assign_whole_process(self):
if len(self.topology.pkgs) == 1:
self.pkg = self.topology.pkgs.minimum()
p = self.pkg.cores.minimum_core_processor()
ahs = self.schedule.options.allow_hyperthread_swapping
self.assign(p, ahs)
else: # TODO: make this work in the SMP case
self.processors = set()
distribute = assign_whole_process
def undistribute(self):
DEBUG("GPU job " + str(self.pid) + " finished")
for p in self.processors:
p.unassign(self.pid)
class CPUJob(Job):
kind = 'cpu'
def spread_process_threads(self):
self.pkg = self.topology.pkgs.minimum()
ahs = self.schedule.options.allow_hyperthread_swapping
for t in self.threads:
p = self.pkg.cores.minimum_core_processor()
t.assign(p, ahs)
def clump_process_threads(self):
self.pkg = self.topology.pkgs.minimum()
ahs = self.schedule.options.allow_hyperthread_swapping
i = 0
while i < len(self.threads):
p = self.pkg.cores.minimum_core_processor()
sibs = list(p.core.processors)
j = 0
while j < len(sibs) and i < len(self.threads):
t = self.threads[i]
t.assign(sibs[j], ahs)
j = j + 1
i = i + 1
def free_process_threads(self):
for t in self.threads:
t.assign_free(self.topology.processors)
def distribute_process_threads(self):
layout = self.schedule.options.layout
if layout == 'spread':
self.spread_process_threads()
elif layout == 'clump':
self.clump_process_threads()
elif layout == 'free':
self.free_process_threads()
else:
raise NotImplementedError("Bad layout name: " + layout)
distribute = distribute_process_threads
def undistribute(self):
#DEBUG("CPU job " + str(self.pid) + " finished")
for t in self.threads:
t.unassign()
def matches_one_of(what, res):
for r in res:
if r.search(what) is not None:
return True
return False
class Schedule:
def __init__(self, options, topology):
self.jobs = set()
self.alive = set()
self.dead = set()
self.new = set()
self.options = options
self.topology = topology
@property
def cpu_jobs(self):
return { j for j in self.jobs if j.kind=="cpu" }
@property
def gpu_jobs(self):
return { j for j in self.jobs if j.kind=="gpu" }
@property
def jobs_by_pid(self):
return {
j.pid: j for j in self.jobs
}
def get_new_jobs(self):
known = self.jobs_by_pid
alive = dict()
new = set()
def maybe_new_job(pid, kind):
if pid in known:
alive[pid] = known[pid]
else:
DEBUG("NEW %s PROC: %d" % (kind.__name__, pid))
new.add(kind(pid, self))
def cpu_gpu_scan(pid, cmd):
if matches_one_of(cmd, gputasks):
maybe_new_job(pid, GPUJob)
elif matches_one_of(cmd, cputasks):
maybe_new_job(pid, CPUJob)
else:
pass
ps_aux(cpu_gpu_scan)
self.alive = set(alive.values())
self.dead = self.jobs.difference(self.alive)
self.jobs = self.alive.union(new)
self.new = new
def distribute(self):
for j in self.dead:
j.undistribute()
self.dead = set()
for j in self.new:
j.distribute()
self.alive = self.jobs
self.new = set()
class NoHardware(Exception):
pass
class IntelCoreTemp:
def __init__(self):
self.files = "/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_input"
self.get_max_temp()
def get_max_temp(self):
file_list = glob.glob(self.files)
temps = []
for f in file_list:
t = float(slurp(f)) / 1000.0
temps.append(t)
if len(temps) < 1:
raise NoHardware()
return max(temps)
class AcpiTz:
def __init__(self):
self.files = "/sys/devices/virtual/thermal/thermal_zone*/temp"
self.get_max_temp()
def get_max_temp(self):
file_list = glob.glob(self.files)
temps = []
for f in file_list:
t = float(slurp(f)) / 1000.0
temps.append(t)
if len(temps) < 1:
raise NoHardware()
return max(temps)
class Sensors:
def __init__(self):
self.exe = "/usr/bin/sensors"
def get_max_temp(self):
temps = []
if not os.path.isfile(self.exe):
raise NoHardware()
read = json.loads(slurp_output(self.exe, '-j'))
for device_name, device_data in read.items():
for sensor_name, sensor_data in device_data.items():
if not isinstance(sensor_data, dict):
continue
for k, v in sensor_data.items():
if k.startswith("temp") and k.endswith("input"):
temps.append(v)
if len(temps) < 1:
raise NoHardware()
return max(temps)
class PID:
def __init__(self, unit, options):
self.unit = unit
self.options = options
if self.options.target_temp == 'max':
self.auto_target = True
self.target = 100.0
else:
self.auto_target = False
self.target = float(self.options.target_temp)
self.interval = self.options.interval
self.i = 0.0
self.prev_undershoot = 0.0
gain = options.gain * 1000.0 # C / Khz
self.p_scale = gain # C / Khz
self.i_scale = gain / options.i_time
self.d_scale = gain * options.d_time
self.cur_freq = self.unit.processors.get_cur_freq()
def detect_throttle(self):
return self.unit.processors.detect_throttle()
def read(self):
self.cur_freq = self.unit.processors.get_cur_freq()
def get_undershoot(self, cur_temp):
return self.target - cur_temp
def update(self, u):
cur_freq = self.cur_freq
max_freq = self.unit.processors.get_max_freq()
min_freq = self.unit.processors.get_min_freq()
new_freq = max(min(cur_freq + u, max_freq), min_freq)
self.unit.processors.set_lim_freq(new_freq)
INFO("Unit {} Frequency {:.2f}->{:.2f}Ghz"
.format(self.unit.n,
cur_freq/1000000, new_freq/1000000))
def regulate(self, cur_temp):
undershoot = self.get_undershoot(cur_temp)
if self.detect_throttle():
self.i = -100.0
if self.auto_target:
self.target -= 1 # reduce target by 1C
INFO("Temp target reduced to {}C".format(self.target))
p = undershoot
diff = undershoot - self.prev_undershoot
d = diff / self.interval # in degrees/second
self.i += undershoot * self.interval # in degree.seconds
u = (p * self.p_scale
+ self.i * self.i_scale
+ d * self.i_scale
)
DEBUG("T={}/{} P={} I={} D={} U={:.0f}Mhz".format(cur_temp, self.target, p, self.i, d, u/1000))
self.update(u)
self.prev_undershoot = undershoot
class SimpleRegulator:
def __init__(self, unit, options):
self.unit = unit
self.options = options
if self.options.target_temp == 'max':
self.auto_target = True
self.target = 100.0
else:
self.auto_target = False
self.target = float(self.options.target_temp)
self.gain = options.gain * 1000.0 # C / Khz
self.max_freq = self.unit.processors.get_max_freq()
self.min_freq = self.unit.processors.get_min_freq()
self.lim = self.unit.processors.get_cur_freq()
def detect_throttle(self):
return self.unit.processors.detect_throttle()
def read(self):
pass
def get_undershoot(self, cur_temp):
return self.target - cur_temp
def update(self, u):
cur_freq = self.lim
new_freq = max(min(cur_freq + u, self.max_freq), self.min_freq)
self.unit.processors.set_lim_freq(new_freq)
self.lim = new_freq
INFO("Unit {} Frequency {:.2f}->{:.2f}Ghz"
.format(self.unit.n,
cur_freq/1000000, new_freq/1000000))
def regulate(self, cur_temp):
undershoot = self.get_undershoot(cur_temp)
if self.detect_throttle():
DEBUG("CPU Throttling detected.")
if self.auto_target:
self.target -= 1 # reduce target by 1C
INFO("Temp target reduced to {}C".format(self.target))
self.update(-self.gain)
return
if undershoot < 0:
DEBUG(f"Unit {self.unit.n} Undershoot: {undershoot} "
f"Over target temp, reducing frequency."
)
self.update(-self.gain)
elif undershoot > 0:
DEBUG(f"Unit {self.unit.n} Undershoot: {undershoot} "
f"Under target temp, increasing frequency."
)
self.update(self.gain)
class Thermo:
def pick_sensor(self):
try_sensors = [
IntelCoreTemp,
AcpiTz,
Sensors
]
self.sensor = None
for try_sensor in try_sensors:
try:
self.sensor = try_sensor()
except NoHardware:
continue
break
if self.sensor is None:
ERROR("Couldn't find a CPU temperature sensor on your platform. "
"Try loading the coretemp kernel module for Intel Core processors. "
"You can also try setting up lm-sensors. "
)
if self.options.target_temp:
exit(1)
def __init__(self, options, topology):
self.options = options
self.topology = topology
self.pick_sensor()
if options.pid:
regulator = PID
else:
regulator = SimpleRegulator
if self.options.target_temp is not None:
for pkg in self.topology.pkgs:
pkg.pid = regulator(pkg, self.options)
else:
self.target = None
def get_max_temp(self):
return self.sensor.get_max_temp()
def tick(self):
if self.options.target_temp is None:
return
cur_temp = self.get_max_temp()
#INFO("Current temperature: {:.1f}".format(cur_temp))
for pkg in self.topology.pkgs:
pkg.pid.read()
for pkg in self.topology.pkgs:
pkg.pid.regulate(cur_temp)
class Gridder:
def __init__(self, options):
self.options = options
self.topology = Topology()
self.schedule = Schedule(options, self.topology)
self.thermo = Thermo(options, self.topology)
self.always_big = self.options.interval >= 10.0
self.c = 0
def watch(self):
while True:
self.small_tick()
if self.always_big or self.c % 10 == 0:
self.big_tick()
time.sleep(self.options.interval)
self.c += 1
DEBUG("-------")
def big_tick(self):
self.schedule.get_new_jobs()
self.schedule.distribute()
def small_tick(self):
self.thermo.tick()
def tick(self):
self.small_tick()
self.big_tick()
def run(self):
if self.options.zero_latency:
latency = open('/dev/cpu_dma_latency', 'wb', buffering=0)
latency.write(b'\0\0\0\0')
latency.flush()
self.watch()
BIT = re.compile(r'bit: (\d+) / (\d+).+?Time per bit: ([\d.]+) ms')
THUSFAR = re.compile(r'bit: (\d+) / (\d+).+?thusfar: ([\d.]+) sec')
class Llr:
def __init__(self, threads, candidate, exe):
self.threads = threads
self.candidate = candidate
self.exe = exe
self.proc = None
self.bufout = ""
self.total = None
self.secs = None
async def start(self):
assert self.proc is None
self.temp = tempfile.mkdtemp(prefix="benchmark-llr-")
assert os.path.isdir(self.temp)
self.proc = await acse(
self.exe,
'-w' + self.temp,
'-d',
'-q' + self.candidate,
'-oThreadsPerTest=' + str(self.threads),
'-oCumulativeTiming=1',
stdout=asyncio.subprocess.PIPE,
stderr=None,
)
self.started = time.time()
def eta(self):
self.total = self.tpb * self.bits
#DEBUG("Estimated total time: {:.1f}h ({:.0f}s)".format(self.total/3600, self.total))
def parse(self, line):
m = BIT.search(line)
if m:
self.bit = int(m.group(1))
self.bits = int(m.group(2))
self.tpb = float(m.group(3))/1000
self.secs = time.time() - self.started
self.eta()