-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnvidia_gpu_stress_test.py
2539 lines (2106 loc) · 104 KB
/
nvidia_gpu_stress_test.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
import os
import sys
import time
import argparse
import traceback
from datetime import datetime
from threading import Thread
from typing import List, Dict, Optional
import psutil
import cupy as cp
import numpy as np
import pynvml
import copy
from OpenGL.GL import *
def find_optimal_matrix_size(gpu_index: int, target_percent: float) -> tuple[int, dict]:
"""
Find optimal matrix size and parameters that cause approximately target_percent GPU utilization
using binary search approach
Args:
gpu_index (int): Index of the GPU to test
target_percent (float): Target GPU usage percentage
Returns:
tuple[int, dict]: Optimal matrix size and corresponding parameters
"""
def test_single_size(size: int, gpu_manager: Optional[GPUResourceManager] = None) -> tuple[float, dict]:
"""Test GPU utilization for a given matrix size and return utilization and best params"""
print(f"\nTesting size {size}")
try:
# Initialize or reuse GPU manager
if gpu_manager is None:
gpu_manager = GPUResourceManager(size, device_id=gpu_index)
# Force initialization of GPU resources
gpu_manager.initialize()
# Get device handle
try:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_index)
except Exception as e:
print(f"Error getting GPU handle: {e}")
return 0, None
# Test different parameter combinations
best_util = 0
best_params = None
# Reduced parameter combinations for faster testing
param_combinations = [
{'sleep_time': 0.001, 'chunk_size': size // 10, 'num_streams': 4, 'sync_frequency': 2},
{'sleep_time': 0.002, 'chunk_size': size // 8, 'num_streams': 4, 'sync_frequency': 2}
]
# Warm-up run
gpu_manager.perform_computation(param_combinations[0])
time.sleep(0.2)
for test_params in param_combinations:
utils = []
# Repetitions
rep_times = 3
for i in range(rep_times):
try:
gpu_manager.perform_computation(test_params)
readings = []
for _ in range(2): # Readings
current_util = pynvml.nvmlDeviceGetUtilizationRates(handle).gpu
readings.append(current_util)
time.sleep(0.1)
util = np.median(readings)
utils.append(util)
print(f"Params {test_params} - Run {i+1}: {util}%")
except Exception as e:
print(f"Error during computation {i+1}: {e}")
continue
if utils:
avg_util = np.median(utils) # Use median instead of mean
if abs(avg_util - target_percent) < abs(best_util - target_percent):
best_util = avg_util
best_params = test_params.copy()
print(f"New best params: {best_params} (util: {best_util:.1f}%)")
return best_util, best_params
except Exception as e:
print(f"\nError testing size {size}: {e}")
traceback.print_exc()
return 0, None
# Initialize NVML and get GPU info
try:
pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_index)
info = pynvml.nvmlDeviceGetMemoryInfo(handle)
total_memory = info.total / (1024**2) # Convert to MB
except Exception as e:
print(f"Error initializing NVML: {e}")
return 5000, {'sleep_time': 0.001, 'chunk_size': 500, 'num_streams': 4, 'sync_frequency': 2}
# Calculate maximum safe matrix size
bytes_per_element = 4 # float32
max_elements = (total_memory * 1024 * 1024 * 0.3) / (2 * bytes_per_element)
max_matrix_size = int(np.sqrt(max_elements))
# Binary search parameters
left = 1000 # Minimum size
right = min(10000, max_matrix_size) # Maximum size
best_size = 5000 # Default size
best_diff = float('inf')
best_util = 0
best_params = {'sleep_time': 0.001, 'chunk_size': 500, 'num_streams': 4, 'sync_frequency': 2}
gpu_manager = None
try:
# Binary search for optimal size
while left <= right:
size = (left + right) // 2
print(f"\nTesting matrix size: {size} (range: {left}-{right})")
# Create new GPU manager if needed
if gpu_manager is None or gpu_manager.matrix_size != size:
if gpu_manager is not None:
gpu_manager.cleanup()
gpu_manager = GPUResourceManager(size, device_id=gpu_index)
util, params = test_single_size(size, gpu_manager)
if util > 0:
diff = abs(util - target_percent)
if diff < best_diff:
best_diff = diff
best_size = size
best_util = util
best_params = params
print(f"New best size: {best_size} (util: {best_util:.1f}%)")
# Early termination if result is good enough
if diff <= 3.0: # More aggressive threshold
print(f"Found good enough result (diff: {diff:.1f}%), stopping search.")
break
# Adjust search range
if util < target_percent:
left = size + 500 # Larger step size
else:
right = size - 500
else:
right = size - 500
# Break if range becomes too small
if right - left < 500:
break
finally:
if gpu_manager is not None:
gpu_manager.cleanup()
print(f"\nSelected size: {best_size}")
print(f"Expected utilization: {best_util:.1f}%")
print(f"Parameters: {best_params}")
return best_size, best_params
class MultiVarPIDController:
"""Multi-variable PID Controller for GPU load management with fine-tuning mode"""
def __init__(self, target_percent, matrix_size):
# Control targets and limits
self.target = target_percent
self.matrix_size = matrix_size
# Fine-tuning mode parameters
self.fine_tuning = False
self.fine_tuning_threshold = 3.0 # Enter fine-tuning when error < 3%
self.stability_count = 0
self.required_stable_readings = 10 # Readings needed to enter fine-tuning
self.gain_reduction_factor = 0.2 # Reduce gains to 20% in fine-tuning mode
# Initialize gains and store original values
self._init_gains(target_percent)
self.original_gains = copy.deepcopy(self.gains)
# Initialize limits based on matrix size and target load
self._init_limits(matrix_size, target_percent)
# Add rate limiting
self.max_change_rates = {
'sleep': 0.001, # max change per update
'chunk': matrix_size // 100, # max change per update
'streams': 1, # max change per update
'sync': 1 # max change per update
}
# Initialize state variables
self.state = {
'sleep': {'integral': 0, 'last_error': 0, 'value': self._get_initial_sleep()},
'chunk': {'integral': 0, 'last_error': 0, 'value': self._get_initial_chunk()},
'streams': {'integral': 0, 'last_error': 0, 'value': self._get_initial_streams()},
'sync': {'integral': 0, 'last_error': 0, 'value': self._get_initial_sync()}
}
# Previous output values for rate limiting
self.prev_outputs = {
'sleep': self._get_initial_sleep(),
'chunk': self._get_initial_chunk(),
'streams': self._get_initial_streams(),
'sync': self._get_initial_sync()
}
self.last_time = time.time()
self.integral_limit = 50.0 # Reduced integral limit
def _init_gains(self, target_percent):
"""Initialize PID gains based on target load with more conservative values"""
if target_percent < 30: # Low load
self.gains = {
'sleep': {'kp': 0.008, 'ki': 0.0008, 'kd': 0.00008},
'chunk': {'kp': 0.08, 'ki': 0.008, 'kd': 0.0008},
'streams': {'kp': 0.02, 'ki': 0.002, 'kd': 0.0002},
'sync': {'kp': 0.06, 'ki': 0.006, 'kd': 0.0006}
}
elif target_percent < 70: # Medium load - much more conservative
self.gains = {
'sleep': {'kp': 0.005, 'ki': 0.0005, 'kd': 0.00005},
'chunk': {'kp': 0.05, 'ki': 0.005, 'kd': 0.0005},
'streams': {'kp': 0.02, 'ki': 0.002, 'kd': 0.0002},
'sync': {'kp': 0.04, 'ki': 0.004, 'kd': 0.0004}
}
else: # High load
self.gains = {
'sleep': {'kp': 0.003, 'ki': 0.0003, 'kd': 0.00003},
'chunk': {'kp': 0.03, 'ki': 0.003, 'kd': 0.0003},
'streams': {'kp': 0.04, 'ki': 0.004, 'kd': 0.0004},
'sync': {'kp': 0.02, 'ki': 0.002, 'kd': 0.0002}
}
def _init_limits(self, matrix_size, target_percent):
"""Initialize control variable limits based on matrix size and target load"""
# Base limits
self.limits = {
'sleep': (0.0001, 0.01),
'chunk': (max(50, matrix_size // 100), max(200, matrix_size // 4)),
'streams': (2, 16),
'sync': (1, 10)
}
# Adjust limits based on target load
if target_percent < 30:
self.limits['sleep'] = (0.0001, 0.005)
self.limits['chunk'] = (max(50, matrix_size // 100), max(100, matrix_size // 8))
self.limits['streams'] = (2, 8)
self.limits['sync'] = (1, 4)
elif target_percent > 70:
self.limits['sleep'] = (0.0001, 0.003)
self.limits['chunk'] = (max(100, matrix_size // 50), max(400, matrix_size // 2))
self.limits['streams'] = (4, 16)
self.limits['sync'] = (2, 10)
def _get_initial_sleep(self):
"""More conservative initial sleep times"""
if self.target < 30:
return 0.003
elif self.target < 70:
return 0.002
else:
return 0.001
def _get_initial_chunk(self):
"""More conservative initial chunk sizes"""
if self.target < 30:
return max(50, self.matrix_size // 40)
elif self.target < 70:
return max(100, self.matrix_size // 20)
else:
return max(200, self.matrix_size // 10)
def _get_initial_streams(self):
"""Get initial number of streams based on target load"""
if self.target < 30:
return 2
elif self.target < 70:
return 4
else:
return 8
def _get_initial_sync(self):
"""Get initial sync frequency based on target load"""
if self.target < 30:
return 1
elif self.target < 70:
return 2
else:
return 4
def _reduce_gains_for_fine_tuning(self):
"""Reduce PID gains for fine-tuning mode"""
for var_name in self.gains:
for gain_type in self.gains[var_name]:
self.gains[var_name][gain_type] = (
self.original_gains[var_name][gain_type] * self.gain_reduction_factor
)
print("Entering fine-tuning mode with reduced gains")
def _restore_original_gains(self):
"""Restore original PID gains"""
self.gains = copy.deepcopy(self.original_gains)
print("Exiting fine-tuning mode, restored original gains")
def compute(self, current_util, load_stability):
"""
Compute new control values with fine-tuning mode support
Args:
current_util (float): Current GPU utilization
load_stability (float): Measure of load stability (0-1)
Returns:
dict: Updated control parameters
"""
error = self.target - current_util # Changed from abs() to maintain sign
# Check if we should enter or exit fine-tuning mode
if not self.fine_tuning:
if abs(error) <= self.fine_tuning_threshold:
self.stability_count += 1
if self.stability_count >= self.required_stable_readings:
self.fine_tuning = True
self._reduce_gains_for_fine_tuning()
else:
self.stability_count = 0
else:
# Exit fine-tuning if error becomes too large
if abs(error) > self.fine_tuning_threshold * 1.5: # Add some hysteresis
self.fine_tuning = False
self.stability_count = 0
self._restore_original_gains()
current_time = time.time()
dt = current_time - self.last_time
if dt <= 0:
return self._get_current_values()
# Update each control variable
for var_name in self.state:
state = self.state[var_name]
gains = self.gains[var_name]
limits = self.limits[var_name]
# Update integral with anti-windup
state['integral'] = max(min(
state['integral'] + error * dt,
self.integral_limit if not self.fine_tuning else self.integral_limit * 0.3
), -self.integral_limit)
# Calculate PID terms
p_term = gains['kp'] * error
i_term = gains['ki'] * state['integral']
d_term = gains['kd'] * (error - state['last_error']) / dt if dt > 0 else 0
# Calculate raw output with variable-specific strategies
output = state['value']
if self.fine_tuning:
# In fine-tuning mode, make smaller adjustments
if var_name == 'sleep':
output += (p_term + i_term + d_term) * 0.5
elif var_name == 'chunk':
output += (p_term + i_term + d_term) * 0.3 * (1 - load_stability)
elif var_name == 'streams':
output += (p_term + i_term + d_term) * 0.2 * abs(error) / 100
elif var_name == 'sync':
output += (p_term + i_term + d_term) * 0.4 * load_stability
else:
# Normal mode adjustments
if var_name == 'sleep':
output += (p_term + i_term + d_term)
elif var_name == 'chunk':
output += (p_term + i_term + d_term) * (1 - load_stability)
elif var_name == 'streams':
output += (p_term + i_term + d_term) * abs(error) / 100
elif var_name == 'sync':
output += (p_term + i_term + d_term) * load_stability
# Apply rate limiting
max_change = self.max_change_rates[var_name]
prev_output = self.prev_outputs[var_name]
output = max(prev_output - max_change,
min(prev_output + max_change, output))
# Store for next iteration
self.prev_outputs[var_name] = output
# Apply limits with tighter bounds in fine-tuning mode
if self.fine_tuning:
# Calculate tighter limits around current value
current = state['value']
limit_range = limits[1] - limits[0]
fine_tune_limits = (
max(limits[0], current - limit_range * 0.05), # Reduced to 5%
min(limits[1], current + limit_range * 0.05)
)
state['value'] = max(fine_tune_limits[0], min(fine_tune_limits[1], output))
else:
state['value'] = max(limits[0], min(limits[1], output))
state['last_error'] = error
self.last_time = current_time
return self._get_current_values()
def _get_current_values(self):
"""Get current values of all control variables"""
return {
'sleep_time': self.state['sleep']['value'],
'chunk_size': int(self.state['chunk']['value']),
'num_streams': int(self.state['streams']['value']),
'sync_frequency': int(self.state['sync']['value'])
}
def get_status(self):
"""Get controller status information"""
return {
'fine_tuning': self.fine_tuning,
'stability_count': self.stability_count,
'current_values': self._get_current_values()
}
def reset(self):
"""Reset controller state"""
self.fine_tuning = False
self.stability_count = 0
self.gains = copy.deepcopy(self.original_gains)
for state in self.state.values():
state['integral'] = 0
state['last_error'] = 0
class GPUResourceManager:
"""Manages GPU resources to maintain stable GPU utilization"""
def __init__(self, matrix_size, num_streams=4, device_id=0):
self.matrix_size = matrix_size
self.device_id = device_id
self.num_streams = num_streams
# Resource flags
self.initialized = False
self.resources_held = False
self.last_use_time = 0
self.hold_duration = 5 # Hold resources for 5 seconds
# Resource containers
self.streams = None
self.matrix1 = None
self.matrix2 = None
self.result_buffer = None
def initialize(self):
"""Initialize GPU resources"""
if self.initialized:
return
with cp.cuda.Device(self.device_id):
# Create persistent streams
self.streams = [cp.cuda.Stream(non_blocking=True) for _ in range(self.num_streams)]
# Allocate matrices with pinned memory
self.matrix1 = cp.random.rand(self.matrix_size, self.matrix_size, dtype=cp.float32)
self.matrix2 = cp.random.rand(self.matrix_size, self.matrix_size, dtype=cp.float32)
# Pre-allocate result buffer
self.result_buffer = cp.zeros((self.matrix_size, self.matrix_size), dtype=cp.float32)
# Force initialization
cp.cuda.Stream.null.synchronize()
self.initialized = True
self.resources_held = True
self.last_use_time = time.time()
def release_if_idle(self):
"""Release resources if they've been idle for too long"""
if not self.resources_held:
return
current_time = time.time()
if current_time - self.last_use_time > self.hold_duration:
self._release_resources()
def _release_resources(self):
"""Release GPU resources"""
if not self.resources_held:
return
with cp.cuda.Device(self.device_id):
# Synchronize all streams before release
for stream in self.streams:
stream.synchronize()
# Release memory
self.matrix1 = None
self.matrix2 = None
self.result_buffer = None
# Clear memory pool
cp.get_default_memory_pool().free_all_blocks()
self.resources_held = False
def perform_computation(self, params):
"""Perform GPU computation while maintaining resources"""
if not self.initialized:
self.initialize()
with cp.cuda.Device(self.device_id):
stream_idx = 0
chunk_count = 0
for i in range(0, self.matrix_size, params['chunk_size']):
end_idx = min(i + params['chunk_size'], self.matrix_size)
with self.streams[stream_idx]:
# Reuse pre-allocated result buffer
cp.dot(
self.matrix1[i:end_idx],
self.matrix2,
out=self.result_buffer[i:end_idx]
)
chunk_count += 1
if chunk_count % params['sync_frequency'] == 0:
self.streams[stream_idx].synchronize()
if params['sleep_time'] > 0:
time.sleep(params['sleep_time'])
stream_idx = (stream_idx + 1) % self.num_streams
# Update last use time
self.last_use_time = time.time()
def cleanup(self):
"""Final cleanup"""
self._release_resources()
self.initialized = False
class LoadSmoothingController:
"""
A wrapper controller that smooths the PID controller's output and applies penalties
when the system stabilizes at wrong levels.
"""
def __init__(self, pid_controller, config=None):
"""Initialize the controller with PID controller and optional config"""
self.pid_controller = pid_controller
self.config = {
'max_util_rate': 5.0,
'smoothing_factor': 0.7,
'history_size': 5,
'min_damping': 0.3,
'recovery_rate': 1.1,
'error_threshold': 10.0,
'penalty_window': 5,
'penalty_factor': 0.5,
'penalty_recovery': 0.95,
}
if config:
self.config.update(config)
self.util_history = []
self.error_history = []
self.last_output = None
self.current_damping = 1.0
self.penalty_active = False
self.penalty_multiplier = 1.0
def update_config(self, new_config):
"""Update controller configuration"""
if not isinstance(new_config, dict):
raise ValueError("new_config must be a dictionary")
# Validate required keys
required_keys = {
'max_util_rate', 'smoothing_factor', 'history_size',
'min_damping', 'recovery_rate', 'error_threshold',
'penalty_window', 'penalty_factor', 'penalty_recovery'
}
missing_keys = required_keys - set(new_config.keys())
if missing_keys:
raise ValueError(f"Missing required config keys: {missing_keys}")
# Validate values
if new_config['smoothing_factor'] <= 0 or new_config['smoothing_factor'] >= 1:
raise ValueError("smoothing_factor must be between 0 and 1")
if new_config['min_damping'] <= 0 or new_config['min_damping'] > 1:
raise ValueError("min_damping must be between 0 and 1")
if new_config['max_util_rate'] <= 0:
raise ValueError("max_util_rate must be positive")
# Update configuration
self.config.update(new_config)
# Reset damping when config changes to prevent instability
self.current_damping = 1.0
def _update_history(self, current_util, current_time):
"""Update utilization history and maintain its size"""
self.util_history.append((current_time, current_util))
while len(self.util_history) > self.config['history_size']:
self.util_history.pop(0)
def _calculate_change_rate(self):
"""Calculate current rate of change in utilization (%/s)"""
if len(self.util_history) < 2:
return 0.0
recent_time, recent_util = self.util_history[-1]
old_time, old_util = self.util_history[0]
time_diff = recent_time - old_time
if time_diff <= 0:
return 0.0
return abs(recent_util - old_util) / time_diff
def _smooth_output(self, new_output):
"""Apply exponential smoothing to the output values"""
if self.last_output is None:
self.last_output = new_output
return new_output
smoothed = {}
for key in new_output:
if key in self.last_output:
# Apply smoothing and ensure integer values where needed
smoothed_value = (self.config['smoothing_factor'] * new_output[key] +
(1 - self.config['smoothing_factor']) * self.last_output[key])
# Ensure integer values for specific parameters
if key in ['chunk_size', 'num_streams', 'sync_frequency']:
smoothed_value = int(round(smoothed_value))
smoothed[key] = smoothed_value
else:
smoothed[key] = new_output[key]
self.last_output = smoothed
return smoothed
def _apply_damping(self, output, damping):
"""Apply damping factor to control outputs"""
if self.last_output is None:
return output
damped = {}
for key in output:
if key in self.last_output:
# Calculate damped value between current output and last output
damped_value = (damping * output[key] +
(1 - damping) * self.last_output[key])
# Ensure integer values for specific parameters
if key in ['chunk_size', 'num_streams', 'sync_frequency']:
damped_value = int(round(damped_value))
damped[key] = damped_value
else:
damped[key] = output[key]
return damped
def _update_penalty_state(self, current_util):
"""
Update penalty state based on current error, excluding outliers
"""
target = self.pid_controller.target
current_error = abs(current_util - target)
self.error_history.append(current_error)
# Keep error history within window
while len(self.error_history) > self.config['penalty_window']:
self.error_history.pop(0)
# Check if we have enough samples
if len(self.error_history) >= self.config['penalty_window']:
# Calculate quartiles to identify outliers
errors = np.array(self.error_history)
q1 = np.percentile(errors, 25)
q3 = np.percentile(errors, 75)
iqr = q3 - q1
lower_bound = q1 - 1.5 * iqr
upper_bound = q3 + 1.5 * iqr
# Filter out outliers
filtered_errors = errors[(errors >= lower_bound) & (errors <= upper_bound)]
# Only proceed if we have enough non-outlier samples
if len(filtered_errors) >= max(3, self.config['penalty_window'] // 2):
avg_error = np.mean(filtered_errors)
if avg_error > self.config['error_threshold']:
if not self.penalty_active:
print(f"Activating penalty - Average error (excluding outliers): {avg_error:.1f}%")
self.penalty_active = True
# Increase penalty strength
self.penalty_multiplier = max(
self.config['penalty_factor'],
self.penalty_multiplier * self.config['penalty_factor']
)
else:
if self.penalty_active:
# Gradually recover from penalty
self.penalty_multiplier = min(
1.0,
self.penalty_multiplier / self.config['penalty_recovery']
)
if self.penalty_multiplier > 0.95: # Almost recovered
self.penalty_active = False
print("Deactivating penalty - Error within threshold")
def _adjust_damping(self, change_rate):
"""Adjust damping factor based on change rate and penalty"""
if change_rate > self.config['max_util_rate']:
# Increase damping (reduce control action) when change rate is too high
target_damping = max(
self.config['min_damping'],
self.config['max_util_rate'] / change_rate
)
self.current_damping = min(self.current_damping, target_damping)
else:
# Gradually recover damping when change rate is acceptable
self.current_damping = min(
1.0,
self.current_damping * self.config['recovery_rate']
)
# Apply penalty by reducing damping if active
if self.penalty_active:
self.current_damping *= self.penalty_multiplier
return self.current_damping
def compute(self, current_util, load_stability):
"""
Compute smoothed control values with penalty consideration
"""
current_time = time.time()
# Update history and calculate change rate
self._update_history(current_util, current_time)
change_rate = self._calculate_change_rate()
# Update penalty state
self._update_penalty_state(current_util)
# Get raw PID output
pid_output = self.pid_controller.compute(current_util, load_stability)
# Apply smoothing and damping
if change_rate > 0:
# Calculate and apply damping based on change rate and penalty
damping = self._adjust_damping(change_rate)
output = self._apply_damping(pid_output, damping)
# Apply additional exponential smoothing
output = self._smooth_output(output)
else:
output = pid_output
return output
def get_status(self):
"""Get controller status including penalty metrics"""
status = self.pid_controller.get_status()
status.update({
'change_rate': self._calculate_change_rate(),
'current_damping': self.current_damping,
'penalty_active': self.penalty_active,
'penalty_multiplier': self.penalty_multiplier,
'avg_error': sum(self.error_history) / len(self.error_history) if self.error_history else 0.0
})
return status
def reset(self):
"""Reset controller state including penalty state"""
self.pid_controller.reset()
self.util_history.clear()
self.error_history.clear()
self.last_output = None
self.current_damping = 1.0
self.penalty_active = False
self.penalty_multiplier = 1.0
def calculate_stability(current_util, util_history=None, history_size=10):
"""Calculate load stability based on utilization history"""
if util_history is None:
util_history = []
util_history.append(current_util)
if len(util_history) > history_size:
util_history.pop(0)
if len(util_history) >= 2:
variations = np.diff(util_history)
stability = 1.0 / (1.0 + np.std(variations))
else:
stability = 0.5
return stability, util_history
def single_matrix_stress(stop_flag, target_percent, gpu_index, matrix_size_or_tuple, initial_params=None):
"""
Function to perform GPU stress test with controlled usage
Args:
stop_flag (list): Flag to control the task execution
target_percent (float): Target GPU usage percentage (1-100)
gpu_index (int): Index of the GPU to stress test
matrix_size_or_tuple: Either an int or a tuple(int, dict) from find_optimal_matrix_size
initial_params (dict, optional): Initial parameters from optimization
"""
def ensure_integer_params(params):
"""Ensure certain parameters are integers and within valid ranges"""
result = params.copy()
# Define minimum and maximum values
limits = {
'chunk_size': (1, 10000),
'num_streams': (1, 32),
'sync_frequency': (1, 10),
'sleep_time': (0.0001, 0.1)
}
for key, (min_val, max_val) in limits.items():
if key in result:
if key == 'sleep_time':
result[key] = max(min_val, min(float(result[key]), max_val))
else:
result[key] = max(min_val, min(int(round(float(result[key]))), max_val))
return result
def get_gpu_utilization():
"""Safely get GPU utilization with retries"""
max_retries = 3
for _ in range(max_retries):
try:
return pynvml.nvmlDeviceGetUtilizationRates(handle).gpu
except pynvml.NVMLError:
time.sleep(0.1)
continue
return None
def get_gpu_temperature():
"""Safely get GPU temperature"""
try:
return pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU)
except pynvml.NVMLError:
return None
# Handle matrix_size input
if isinstance(matrix_size_or_tuple, tuple):
matrix_size, initial_params = matrix_size_or_tuple
else:
matrix_size = matrix_size_or_tuple
if initial_params is None:
matrix_size, initial_params = find_optimal_matrix_size(gpu_index, target_percent)
if initial_params is None:
raise ValueError("No valid initial parameters available")
initial_params = ensure_integer_params(initial_params)
params = initial_params.copy()
try:
pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_index)
except pynvml.NVMLError as e:
raise RuntimeError(f"Failed to initialize NVML: {str(e)}")
pid_controller = MultiVarPIDController(target_percent, matrix_size)
smoother = LoadSmoothingController(pid_controller)
gpu_manager = GPUResourceManager(matrix_size, device_id=gpu_index)
gpu_manager.initialize()
util_history = []
# Control parameters
if target_percent <= 30:
stability_threshold = 3.0
max_adjustment = 0.2
elif target_percent >= 70:
stability_threshold = 5.0
max_adjustment = 0.3
else:
stability_threshold = 4.0
max_adjustment = 0.25
try:
# Warm-up phase
warm_up_utils = []
warm_up_success = False
# Ensure initial parameters are valid
params = ensure_integer_params(initial_params.copy())
last_successful_params = params.copy()
# Initial stabilization
for _ in range(10):
gpu_manager.perform_computation(params)
current_util = get_gpu_utilization()
if current_util is not None:
warm_up_utils.append(current_util)
if len(warm_up_utils) >= 3:
avg_util = np.mean(warm_up_utils[-3:])
error = target_percent - avg_util
if abs(error) <= stability_threshold:
warm_up_success = True
break
elif len(warm_up_utils) >= 3:
# Gradual adjustment
if abs(error) > 20:
adjustment = 0.2 * (error / target_percent)
else:
adjustment = 0.1 * (error / target_percent)
adjustment = max(min(adjustment, max_adjustment), -max_adjustment)
new_params = params.copy()
for key in ['chunk_size', 'num_streams']:
if key in new_params:
current_value = new_params[key]
new_value = int(current_value * (1 + adjustment))
new_params[key] = new_value
params = ensure_integer_params(new_params)
warm_up_utils = warm_up_utils[-2:]
if warm_up_success:
break
last_successful_params = params.copy()
# Main control loop
while not stop_flag[0]:
try:
gpu_manager.perform_computation(params)
current_util = get_gpu_utilization()
if current_util is None:
params = last_successful_params.copy()
continue
error = target_percent - current_util
# Update stability tracking
stability, util_history = calculate_stability(current_util, util_history)
if abs(error) <= stability_threshold:
last_successful_params = params.copy()
continue
# Adjust parameters based on error
if abs(error) > 10:
adjustment = 0.15 * (error / target_percent)
else:
adjustment = 0.05 * (error / target_percent)
# Apply temperature factor
temp = get_gpu_temperature()
if temp is not None:
temp_factor = 1.0 + max(0, (temp - 40) / 60) # Increase adjustment for higher temps
adjustment *= temp_factor
adjustment = max(min(adjustment, max_adjustment), -max_adjustment)
new_params = params.copy()
for key in ['chunk_size', 'num_streams']:
if key in new_params:
current_value = new_params[key]
new_value = int(current_value * (1 + adjustment))
new_params[key] = new_value
params = ensure_integer_params(new_params)
except Exception as e:
params = last_successful_params.copy()
continue
except KeyboardInterrupt:
pass
finally:
try:
gpu_manager.cleanup()
except:
pass