-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1980 lines (1656 loc) · 58.5 KB
/
main.go
File metadata and controls
1980 lines (1656 loc) · 58.5 KB
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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"math"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/NVIDIA/go-nvml/pkg/nvml"
)
const version = "1.3.3"
type GPUInfo struct {
Index uint `json:"index"`
UUID string `json:"uuid"`
Name string `json:"name"`
GPUUtilisation uint `json:"gpu_utilisation"`
MemoryUtilisation uint `json:"memory_utilisation"`
PowerWatts uint `json:"power_watts"`
PowerLimitWatts uint `json:"power_limit_watts"`
MemoryTotal float64 `json:"memory_total_gb"`
MemoryUsed float64 `json:"memory_used_gb"`
MemoryFree float64 `json:"memory_free_gb"`
MemoryUsagePercent int `json:"memory_usage_percent"`
Temperature uint `json:"temperature"`
// FanSpeed *uint `json:"fan_speed,omitempty"`
Processes []ProcessInfo `json:"processes"`
PCIeLinkState string `json:"pcie_link_state"`
ClockOffsets *ClockOffsets `json:"clock_offsets,omitempty"`
}
type ProcessInfo struct {
Pid uint32 `json:"pid"`
UsedGpuMemoryMb uint64 `json:"used_gpu_memory_mb"`
Name string `json:"name"`
Arguments []string `json:"arguments"`
}
type rateLimiter struct {
tokens float64
capacity float64
rate float64
mu sync.Mutex
lastTime time.Time
cache *[]GPUInfo
}
// TempPowerLimits holds the temperature-based power limit settings for a GPU
type TempPowerLimits struct {
LowTemp int
MediumTemp int
LowTempLimit uint
MediumTempLimit uint
HighTempLimit uint
}
// ClockOffset represents clock offset information for a performance state
type ClockOffset struct {
Current int32 `json:"current"` // Current applied offset in MHz
Min int32 `json:"min"` // Minimum allowed offset in MHz
Max int32 `json:"max"` // Maximum allowed offset in MHz
}
// ClockOffsets holds all clock offset information for a GPU
type ClockOffsets struct {
GPUOffsets map[uint32]ClockOffset `json:"gpu_offsets"` // P-state → GPU offset
MemOffsets map[uint32]ClockOffset `json:"mem_offsets"` // P-state → Memory offset
GPURange *[2]uint32 `json:"gpu_clock_range,omitempty"`
VRAMRange *[2]uint32 `json:"vram_clock_range,omitempty"`
}
// ClockOffsetConfig stores the user's desired offset configuration
type ClockOffsetConfig struct {
GPUOffsets map[uint32]int32 `json:"gpu_offsets"` // P-state → desired offset
MemOffsets map[uint32]int32 `json:"mem_offsets"` // P-state → desired offset
}
// OffsetRequest represents a request to set clock offsets
type OffsetRequest struct {
GPUOffsets map[string]int32 `json:"gpu_offsets"` // "P0": 150, "P1": 100
MemOffsets map[string]int32 `json:"mem_offsets"` // "P0": 500, "P2": -100
}
// OffsetResponse represents current offset status
type OffsetResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
ClockOffsets *ClockOffsets `json:"clock_offsets,omitempty"`
Applied map[string]interface{} `json:"applied,omitempty"`
}
// Track GPU capabilities
type GPUCapabilities struct {
HasFanSpeedSensor bool
FanSpeedSupported bool
}
const (
pcieSysfsPath = "/sys/bus/pci/devices"
)
type PCIeConfig struct {
IdleThresholdSeconds int
Enabled bool
MinSpeed int
MaxSpeed int
}
type PCIeStateManager struct {
devices []nvml.Device
utilisationHistory map[int][]float64
lastChangeTime map[int]time.Time
configs map[int]*PCIeConfig
mutex sync.RWMutex
updateInterval time.Duration
stopChan chan struct{}
}
var (
port = flag.Int("port", 9999, "Port to listen on")
rate = flag.Int("rate", 3, "Minimum number of seconds between requests")
debug = flag.Bool("debug", false, "Print debug logs to the console")
help = flag.Bool("help", false, "Print this help")
gpuPowerLimits map[int]TempPowerLimits
tempCheckInterval time.Duration
lastTempCheckTime time.Time
totalPowerCap uint
lastTotalPower uint
enablePCIeStateManagement = flag.Bool("enable-pcie-state-management", false, "Enable automatic PCIe link state management")
pcieStateManager *PCIeStateManager
gpuClockOffsetConfigs map[int]ClockOffsetConfig // GPU index → offset config
lastAppliedOffsets map[int]ClockOffsets // Track applied offsets for reporting
offsetsMutex sync.RWMutex // Protect offset operations
rl *rateLimiter // Rate limiter for HTTP requests
// gpuCapabilities []GPUCapabilities
)
// Initialise GPU capabilities
// func initialiseGPUCapabilities() error {
// count, ret := nvml.DeviceGetCount()
// if ret != nvml.SUCCESS {
// return fmt.Errorf("unable to get device count: %v", nvml.ErrorString(ret))
// }
// gpuCapabilities = make([]GPUCapabilities, count)
// for i := 0; i < int(count); i++ {
// device, ret := nvml.DeviceGetHandleByIndex(i)
// if ret != nvml.SUCCESS {
// return fmt.Errorf("unable to get device at index %d: %v", i, nvml.ErrorString(ret))
// }
// // Check if fan speed sensor is available
// _, ret = device.GetFanSpeed()
// gpuCapabilities[i].HasFanSpeedSensor = (ret == nvml.SUCCESS)
// // If we have a sensor, check if we can actually read from it
// if gpuCapabilities[i].HasFanSpeedSensor {
// speed, ret := device.GetFanSpeed()
// gpuCapabilities[i].FanSpeedSupported = (ret == nvml.SUCCESS && speed != 0)
// }
// if *debug {
// log.Printf("GPU %d - Has Fan Sensor: %v, Fan Speed Supported: %v",
// i, gpuCapabilities[i].HasFanSpeedSensor, gpuCapabilities[i].FanSpeedSupported)
// }
// }
// return nil
// }
// getGPUUUID retrieves the UUID for a given GPU device
func getGPUUUID(device nvml.Device) (string, error) {
uuid, ret := device.GetUUID()
if ret != nvml.SUCCESS {
return "", fmt.Errorf("unable to get UUID for device: %v", nvml.ErrorString(ret))
}
return uuid, nil
}
// mapUUIDsToIndices creates a mapping of GPU UUIDs to their corresponding device indices
func mapUUIDsToIndices() (map[string]int, error) {
uuidToIndex := make(map[string]int)
count, ret := nvml.DeviceGetCount()
if ret != nvml.SUCCESS {
return nil, fmt.Errorf("unable to get device count: %v", nvml.ErrorString(ret))
}
for i := 0; i < int(count); i++ {
device, ret := nvml.DeviceGetHandleByIndex(i)
if ret != nvml.SUCCESS {
return nil, fmt.Errorf("unable to get device at index %d: %v", i, nvml.ErrorString(ret))
}
uuid, err := getGPUUUID(device)
if err != nil {
return nil, err
}
uuidToIndex[uuid] = i
}
return uuidToIndex, nil
}
func parseTotalPowerCap() {
capStr := os.Getenv("GPU_TOTAL_POWER_CAP")
if capStr == "" {
totalPowerCap = 0 // Disabled if not set
return
}
cap, err := strconv.ParseUint(capStr, 10, 32)
if err != nil {
log.Printf("Warning: Invalid GPU_TOTAL_POWER_CAP value. Total power cap will be disabled.")
totalPowerCap = 0
return
}
totalPowerCap = uint(cap)
}
func applyTotalPowerCap(devices []nvml.Device) error {
if totalPowerCap == 0 {
return nil // Total power cap is disabled
}
var totalPower uint
var currentPowers []uint
var maxPowerLimits []uint
for _, device := range devices {
power, ret := device.GetPowerUsage()
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get power usage: %v", nvml.ErrorString(ret))
}
currentPower := uint(power / 1000) // Convert milliwatts to watts
totalPower += currentPower
currentPowers = append(currentPowers, currentPower)
maxPowerLimit, ret := device.GetPowerManagementLimit()
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get power management limit: %v", nvml.ErrorString(ret))
}
maxPowerLimits = append(maxPowerLimits, uint(maxPowerLimit/1000)) // Convert milliwatts to watts
}
if totalPower > totalPowerCap {
log.Printf("Total power consumption (%d W) exceeds the cap (%d W). Adjusting limits...", totalPower, totalPowerCap)
excessPower := totalPower - totalPowerCap
for i, device := range devices {
if currentPowers[i] == 0 {
continue // Skip GPUs that aren't consuming power
}
// Calculate how much this GPU should reduce its power
reductionRatio := float64(currentPowers[i]) / float64(totalPower)
reduction := uint(float64(excessPower) * reductionRatio)
// Ensure we don't reduce below zero
newLimit := maxPowerLimits[i]
if reduction < currentPowers[i] {
newLimit = currentPowers[i] - reduction
}
ret := device.SetPowerManagementLimit(uint32(newLimit * 1000)) // Convert watts to milliwatts
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to set power management limit for GPU %d: %v", i, nvml.ErrorString(ret))
}
log.Printf("GPU %d power limit adjusted to %d W (current consumption: %d W)", i, newLimit, currentPowers[i])
}
} else if totalPower >= uint(float64(totalPowerCap)*0.98) && totalPower != lastTotalPower {
log.Printf("Warning: Total power consumption (%d W) is approaching the cap (%d W)", totalPower, totalPowerCap)
} else {
// If we're well below the cap, restore original power limits
for i, device := range devices {
ret := device.SetPowerManagementLimit(uint32(maxPowerLimits[i] * 1000)) // Convert watts to milliwatts
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to restore power management limit for GPU %d: %v", i, nvml.ErrorString(ret))
}
}
}
lastTotalPower = totalPower
return nil
}
func parseTempCheckInterval() {
intervalStr := os.Getenv("GPU_TEMP_CHECK_INTERVAL")
if intervalStr == "" {
tempCheckInterval = 5 * time.Second // Default to 5 seconds if not set
return
}
interval, err := strconv.Atoi(intervalStr)
if err != nil {
log.Printf("Warning: Invalid GPU_TEMP_CHECK_INTERVAL value. Using default of 5 seconds.")
tempCheckInterval = 5 * time.Second
return
}
tempCheckInterval = time.Duration(interval) * time.Second
}
func checkAndApplyPowerLimits() error {
if time.Since(lastTempCheckTime) < tempCheckInterval {
return nil
}
lastTempCheckTime = time.Now()
count, ret := nvml.DeviceGetCount()
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device count: %v", nvml.ErrorString(ret))
}
var devices []nvml.Device
for i := 0; i < int(count); i++ {
device, ret := nvml.DeviceGetHandleByIndex(i)
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device at index %d: %v", i, nvml.ErrorString(ret))
}
devices = append(devices, device)
// Only apply individual temperature-based limits if they are configured
if _, exists := gpuPowerLimits[i]; exists {
temperature, ret := device.GetTemperature(nvml.TEMPERATURE_GPU)
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get temperature for GPU %d: %v", i, nvml.ErrorString(ret))
}
err := applyPowerLimit(device, i, uint(temperature))
if err != nil {
log.Printf("Warning: Failed to apply power limit for GPU %d: %v", i, err)
}
}
}
// Always apply total power cap if it's set, regardless of individual temperature limits
err := applyTotalPowerCap(devices)
if err != nil {
log.Printf("Warning: Failed to apply total power cap: %v", err)
}
return nil
}
func (rl *rateLimiter) takeToken() bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
elapsed := now.Sub(rl.lastTime)
rl.lastTime = now
rl.tokens = math.Min(rl.capacity, rl.tokens+rl.rate*elapsed.Seconds())
if rl.tokens < 1 {
return false
}
rl.tokens--
return true
}
func (rl *rateLimiter) getCache() []GPUInfo {
return *(rl.cache)
}
func getProcessInfo(pid uint32) (string, []string, error) {
procDir := fmt.Sprintf("/proc/%d", pid)
cmdlineFile := filepath.Join(procDir, "cmdline")
cmdline, err := os.ReadFile(cmdlineFile)
if err != nil {
return "", nil, err
}
cmdlineArgs := strings.Split(string(cmdline), "\x00")
cmdlineArgs = cmdlineArgs[:len(cmdlineArgs)-1] // remove trailing empty string
processName := cmdlineArgs[0]
arguments := cmdlineArgs[1:]
return processName, arguments, nil
}
// parseTempPowerLimits parses the environment variables for temperature-based power limits
func parseTempPowerLimits() error {
gpuPowerLimits = make(map[int]TempPowerLimits)
uuidToIndex, err := mapUUIDsToIndices()
if err != nil {
return fmt.Errorf("failed to map UUIDs to indices: %v", err)
}
for _, env := range os.Environ() {
if strings.HasPrefix(env, "GPU_") && strings.Contains(env, "_LOW_TEMP") {
parts := strings.SplitN(env, "=", 2)
if len(parts) != 2 {
continue
}
key := strings.TrimPrefix(parts[0], "GPU_")
// Remove all suffixes related to temperature limits
key = strings.TrimSuffix(key, "_LOW_TEMP")
key = strings.TrimSuffix(key, "_MEDIUM_TEMP")
key = strings.TrimSuffix(key, "_HIGH_TEMP")
key = strings.TrimSuffix(key, "_LOW_TEMP_LIMIT")
key = strings.TrimSuffix(key, "_MEDIUM_TEMP_LIMIT")
key = strings.TrimSuffix(key, "_HIGH_TEMP_LIMIT")
if *debug {
log.Printf("Debug: Processing key: %s", key)
}
var index string
if strings.Contains(key, "-") {
// This is a UUID
if idx, ok := uuidToIndex[key]; ok {
index = strconv.Itoa(idx)
} else {
log.Printf("Warning: Unknown GPU UUID %s", key)
continue
}
} else {
// This is an index
index = key
}
if *debug {
log.Printf("Debug: Resolved index: %s", index)
}
// Use the key to construct environment variable names
lowTempEnv := fmt.Sprintf("GPU_%s_LOW_TEMP", key)
mediumTempEnv := fmt.Sprintf("GPU_%s_MEDIUM_TEMP", key)
lowTempLimitEnv := fmt.Sprintf("GPU_%s_LOW_TEMP_LIMIT", key)
mediumTempLimitEnv := fmt.Sprintf("GPU_%s_MEDIUM_TEMP_LIMIT", key)
highTempLimitEnv := fmt.Sprintf("GPU_%s_HIGH_TEMP_LIMIT", key)
lowTemp, err := strconv.Atoi(os.Getenv(lowTempEnv))
if err != nil {
return fmt.Errorf("invalid LOW_TEMP value for GPU %s: %v", key, err)
}
mediumTempStr := os.Getenv(mediumTempEnv)
if *debug {
log.Printf("Debug: Looking for MEDIUM_TEMP with key: %s, value: %s", mediumTempEnv, mediumTempStr)
}
mediumTemp, err := strconv.Atoi(mediumTempStr)
if err != nil {
return fmt.Errorf("invalid MEDIUM_TEMP value for GPU %s: %v", key, err)
}
lowTempLimit, err := strconv.ParseUint(os.Getenv(lowTempLimitEnv), 10, 32)
if err != nil {
return fmt.Errorf("invalid LOW_TEMP_LIMIT value for GPU %s: %v", key, err)
}
mediumTempLimit, err := strconv.ParseUint(os.Getenv(mediumTempLimitEnv), 10, 32)
if err != nil {
return fmt.Errorf("invalid MEDIUM_TEMP_LIMIT value for GPU %s: %v", key, err)
}
highTempLimit, err := strconv.ParseUint(os.Getenv(highTempLimitEnv), 10, 32)
if err != nil {
return fmt.Errorf("invalid HIGH_TEMP_LIMIT value for GPU %s: %v", key, err)
}
idx, err := strconv.Atoi(index)
if err != nil {
return fmt.Errorf("invalid GPU index %s: %v", index, err)
}
if *debug {
log.Printf("Debug: Successfully parsed all values for GPU %s", key)
}
gpuPowerLimits[idx] = TempPowerLimits{
LowTemp: lowTemp,
MediumTemp: mediumTemp,
LowTempLimit: uint(lowTempLimit),
MediumTempLimit: uint(mediumTempLimit),
HighTempLimit: uint(highTempLimit),
}
}
}
return nil
}
// parseClockOffsetConfig parses environment variables for clock offset configuration
func parseClockOffsetConfig() error {
gpuClockOffsetConfigs = make(map[int]ClockOffsetConfig)
if *debug {
log.Printf("Debug: Starting clock offset configuration parsing...")
}
uuidToIndex, err := mapUUIDsToIndices()
if err != nil {
return fmt.Errorf("failed to map UUIDs to indices: %v", err)
}
if *debug {
log.Printf("Debug: UUID to Index mapping:")
for uuid, idx := range uuidToIndex {
log.Printf(" %s -> %d", uuid, idx)
}
}
for _, env := range os.Environ() {
if strings.HasPrefix(env, "GPU_") && strings.Contains(env, "_OFFSET_") {
if *debug {
log.Printf("Debug: Found clock offset env var: %s", env)
}
// Parse patterns like:
// GPU_UUID_OFFSET_P0_CORE=+150
// GPU_UUID_OFFSET_P0_MEM=+500
// GPU_UUID_OFFSET_P2_CORE=-100
parts := strings.SplitN(env, "=", 2)
if len(parts) != 2 {
continue
}
key := parts[0]
value := parts[1]
// Extract UUID, P-state, and clock type from key
if uuid, pstate, clockType, err := parseOffsetEnvKey(key); err == nil {
if *debug {
log.Printf("Debug: Parsed key - UUID: %s, P-state: %d, Clock type: %s", uuid, pstate, clockType)
}
var idx int
var exists bool
if strings.Contains(uuid, "-") {
// This is a UUID
idx, exists = uuidToIndex[uuid]
if !exists {
log.Printf("Warning: Unknown GPU UUID %s", uuid)
continue
}
} else {
// This is an index
idx64, err := strconv.ParseInt(uuid, 10, 32)
if err != nil {
log.Printf("Warning: Invalid GPU index %s: %v", uuid, err)
continue
}
idx = int(idx64)
}
offset, err := strconv.ParseInt(value, 10, 32)
if err != nil {
log.Printf("Invalid offset value for %s: %v", key, err)
continue
}
if _, exists := gpuClockOffsetConfigs[idx]; !exists {
gpuClockOffsetConfigs[idx] = ClockOffsetConfig{
GPUOffsets: make(map[uint32]int32),
MemOffsets: make(map[uint32]int32),
}
}
config := gpuClockOffsetConfigs[idx]
if clockType == "CORE" {
config.GPUOffsets[pstate] = int32(offset)
if *debug {
log.Printf("Debug: Set GPU P%d offset to %d MHz for device %d", pstate, offset, idx)
}
} else if clockType == "MEM" {
config.MemOffsets[pstate] = int32(offset)
if *debug {
log.Printf("Debug: Set Memory P%d offset to %d MHz for device %d", pstate, offset, idx)
}
}
gpuClockOffsetConfigs[idx] = config
}
}
}
return nil
}
// parseOffsetEnvKey parses environment variable keys like "GPU_UUID_OFFSET_P0_CORE"
func parseOffsetEnvKey(key string) (uuid string, pstate uint32, clockType string, err error) {
// Expected format: GPU_{UUID}_OFFSET_P{PSTATE}_{CLOCKTYPE}
parts := strings.Split(key, "_")
if len(parts) < 5 {
return "", 0, "", fmt.Errorf("invalid key format")
}
// Extract UUID (everything between GPU_ and _OFFSET)
offsetIndex := -1
for i, part := range parts {
if part == "OFFSET" {
offsetIndex = i
break
}
}
if offsetIndex == -1 || offsetIndex < 2 {
return "", 0, "", fmt.Errorf("OFFSET not found in key")
}
// Join UUID parts (may contain hyphens)
uuid = strings.Join(parts[1:offsetIndex], "_")
// Find P-state (e.g., "P0" → 0)
var pstateStr string
var clockTypeIdx int
for i := offsetIndex + 1; i < len(parts); i++ {
if strings.HasPrefix(parts[i], "P") && len(parts[i]) > 1 {
pstateStr = parts[i][1:]
clockTypeIdx = i + 1
break
}
}
if pstateStr == "" || clockTypeIdx >= len(parts) {
return "", 0, "", fmt.Errorf("invalid P-state format")
}
pstateVal, err := strconv.ParseUint(pstateStr, 10, 32)
if err != nil {
return "", 0, "", fmt.Errorf("invalid P-state number: %v", err)
}
clockType = parts[clockTypeIdx]
if clockType != "CORE" && clockType != "MEM" {
return "", 0, "", fmt.Errorf("invalid clock type: %s", clockType)
}
return uuid, uint32(pstateVal), clockType, nil
}
// parsePStateString converts "P0" to 0, "P1" to 1, etc.
func parsePStateString(pstateStr string) uint32 {
if !strings.HasPrefix(pstateStr, "P") {
return 0
}
pstate, err := strconv.ParseUint(pstateStr[1:], 10, 32)
if err != nil {
return 0
}
return uint32(pstate)
}
// getClockOffsets retrieves current clock offset information for a device
func getClockOffsets(device nvml.Device, deviceIndex int) (*ClockOffsets, error) {
// Use native NVML implementation (requires driver 555+)
return GetClockOffsetsNative(device, deviceIndex)
}
// setClockOffset applies a clock offset to specific P-state using Python script
func setClockOffset(device nvml.Device, clockType string, pstate uint32, offsetMHz int32) error {
deviceIndex, ret := device.GetIndex()
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device index: %v", nvml.ErrorString(ret))
}
// Create config for single offset
config := ClockOffsetConfig{
GPUOffsets: make(map[uint32]int32),
MemOffsets: make(map[uint32]int32),
}
if clockType == "core" || clockType == "gpu" {
config.GPUOffsets[pstate] = offsetMHz
} else if clockType == "mem" || clockType == "memory" {
config.MemOffsets[pstate] = offsetMHz
} else {
return fmt.Errorf("invalid clock type: %s", clockType)
}
// Use native NVML implementation (requires driver 555+)
return SetClockOffsetsNative(device, int(deviceIndex), config)
}
// applyClockOffsets applies all configured offsets for a GPU
func applyClockOffsets(deviceIndex int) error {
device, ret := nvml.DeviceGetHandleByIndex(deviceIndex)
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device %d: %v", deviceIndex, nvml.ErrorString(ret))
}
config, exists := gpuClockOffsetConfigs[deviceIndex]
if !exists {
return nil // No offsets configured for this GPU
}
// Apply GPU core offsets
for pstate, offset := range config.GPUOffsets {
if err := setClockOffset(device, "core", pstate, offset); err != nil {
return fmt.Errorf("failed to set GPU offset %+d MHz for P%d: %v", offset, pstate, err)
}
log.Printf("Applied GPU offset %+d MHz to P-state %d on GPU %d", offset, pstate, deviceIndex)
}
// Apply memory offsets
for pstate, offset := range config.MemOffsets {
if err := setClockOffset(device, "mem", pstate, offset); err != nil {
return fmt.Errorf("failed to set memory offset %+d MHz for P%d: %v", offset, pstate, err)
}
log.Printf("Applied memory offset %+d MHz to P-state %d on GPU %d", offset, pstate, deviceIndex)
}
// Cache applied offsets for reporting
offsetsMutex.Lock()
if lastAppliedOffsets == nil {
lastAppliedOffsets = make(map[int]ClockOffsets)
}
appliedOffsets := ClockOffsets{
GPUOffsets: make(map[uint32]ClockOffset),
MemOffsets: make(map[uint32]ClockOffset),
}
for pstate, offset := range config.GPUOffsets {
appliedOffsets.GPUOffsets[pstate] = ClockOffset{Current: offset, Min: -500, Max: 500}
}
for pstate, offset := range config.MemOffsets {
appliedOffsets.MemOffsets[pstate] = ClockOffset{Current: offset, Min: -1000, Max: 1000}
}
lastAppliedOffsets[deviceIndex] = appliedOffsets
offsetsMutex.Unlock()
return nil
}
// resetClockOffsets resets all offsets to 0 (stock clocks)
func resetClockOffsets(deviceIndex int) error {
device, ret := nvml.DeviceGetHandleByIndex(deviceIndex)
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device %d: %v", deviceIndex, nvml.ErrorString(ret))
}
// Use native NVML implementation (requires driver 555+)
err := ResetClockOffsetsNative(device, deviceIndex)
if err != nil {
return fmt.Errorf("failed to reset clock offsets: %v", err)
}
// Clear cached offsets
offsetsMutex.Lock()
delete(lastAppliedOffsets, deviceIndex)
offsetsMutex.Unlock()
log.Printf("Reset all clock offsets to stock values for GPU %d", deviceIndex)
return nil
}
// resetToDefaultsWithLogging resets clock offsets to default (0) and logs if non-default values were found
func resetToDefaultsWithLogging(deviceIndex int) error {
device, ret := nvml.DeviceGetHandleByIndex(deviceIndex)
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device %d: %v", deviceIndex, nvml.ErrorString(ret))
}
// Get current offsets first to check if they're non-default
currentOffsets, err := getClockOffsets(device, deviceIndex)
if err != nil {
if *debug {
log.Printf("Warning: Could not get current offsets for GPU %d: %v", deviceIndex, err)
}
return nil // Don't fail if we can't read current offsets
}
// Check if there are any non-zero offsets to log
hasNonDefaultOffsets := false
var nonDefaultOffsets []string
for pstate, offset := range currentOffsets.GPUOffsets {
if offset.Current != 0 {
hasNonDefaultOffsets = true
nonDefaultOffsets = append(nonDefaultOffsets, fmt.Sprintf("GPU P%d: %+d MHz", pstate, offset.Current))
}
}
for pstate, offset := range currentOffsets.MemOffsets {
if offset.Current != 0 {
hasNonDefaultOffsets = true
nonDefaultOffsets = append(nonDefaultOffsets, fmt.Sprintf("Memory P%d: %+d MHz", pstate, offset.Current))
}
}
if hasNonDefaultOffsets {
log.Printf("GPU %d: No clock offset configuration found, resetting non-default offsets to 0: %s",
deviceIndex, strings.Join(nonDefaultOffsets, ", "))
}
// Reset to defaults
err = resetClockOffsets(deviceIndex)
if err != nil {
return fmt.Errorf("failed to reset to defaults: %v", err)
}
if hasNonDefaultOffsets {
log.Printf("GPU %d: Successfully reset all clock offsets to default (0)", deviceIndex)
}
return nil
}
// validateOffsets ensures offset values are within reasonable ranges
func validateOffsets(req OffsetRequest) error {
const maxOffset = 1000 // MHz
const minOffset = -1000 // MHz
for pstate, offset := range req.GPUOffsets {
if offset < minOffset || offset > maxOffset {
return fmt.Errorf("GPU offset %d MHz for %s outside safe range [%d, %d]",
offset, pstate, minOffset, maxOffset)
}
}
for pstate, offset := range req.MemOffsets {
if offset < minOffset || offset > maxOffset {
return fmt.Errorf("memory offset %d MHz for %s outside safe range [%d, %d]",
offset, pstate, minOffset, maxOffset)
}
}
return nil
}
// checkPythonDependency verifies that Python and required packages are available
func checkClockOffsetSupport() error {
if !IsNativeClockOffsetSupported() {
return fmt.Errorf("native clock offset support not available - requires NVIDIA driver 555+")
}
if *debug {
log.Printf("Native clock offset support available")
}
return nil
}
// validateDeviceIndex checks if the device index is valid
func validateDeviceIndex(deviceIndex int) error {
count, ret := nvml.DeviceGetCount()
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device count: %v", nvml.ErrorString(ret))
}
if deviceIndex < 0 || deviceIndex >= int(count) {
return fmt.Errorf("invalid device index %d. Available devices: 0-%d", deviceIndex, int(count)-1)
}
return nil
}
// validatePStateRange checks if P-state values are reasonable
func validatePStateRange(pstate uint32) error {
if pstate > 7 {
return fmt.Errorf("P-state %d is outside typical range 0-7", pstate)
}
return nil
}
// safeApplyClockOffsets applies offsets with comprehensive error handling
func safeApplyClockOffsets(deviceIndex int) error {
if err := validateDeviceIndex(deviceIndex); err != nil {
return fmt.Errorf("device validation failed: %v", err)
}
config, exists := gpuClockOffsetConfigs[deviceIndex]
if !exists {
// No offsets configured - reset to defaults and check if there were existing offsets
return resetToDefaultsWithLogging(deviceIndex)
}
// Validate all P-states before applying any offsets
for pstate := range config.GPUOffsets {
if err := validatePStateRange(pstate); err != nil {
return fmt.Errorf("GPU offset validation failed: %v", err)
}
}
for pstate := range config.MemOffsets {
if err := validatePStateRange(pstate); err != nil {
return fmt.Errorf("memory offset validation failed: %v", err)
}
}
device, ret := nvml.DeviceGetHandleByIndex(deviceIndex)
if ret != nvml.SUCCESS {
return fmt.Errorf("unable to get device %d: %v", deviceIndex, nvml.ErrorString(ret))
}
// Use native bulk implementation (requires driver 555+)
err := SetClockOffsetsNative(device, deviceIndex, config)
if err == nil {
// Cache applied offsets for reporting
offsetsMutex.Lock()
if lastAppliedOffsets == nil {
lastAppliedOffsets = make(map[int]ClockOffsets)
}
appliedOffsets := ClockOffsets{
GPUOffsets: make(map[uint32]ClockOffset),
MemOffsets: make(map[uint32]ClockOffset),
}
for pstate, offset := range config.GPUOffsets {
appliedOffsets.GPUOffsets[pstate] = ClockOffset{Current: offset, Min: -500, Max: 500}
log.Printf("Applied GPU offset %+d MHz to P-state %d on GPU %d (native)", offset, pstate, deviceIndex)
}
for pstate, offset := range config.MemOffsets {
appliedOffsets.MemOffsets[pstate] = ClockOffset{Current: offset, Min: -1000, Max: 1000}
log.Printf("Applied memory offset %+d MHz to P-state %d on GPU %d (native)", offset, pstate, deviceIndex)
}
lastAppliedOffsets[deviceIndex] = appliedOffsets
offsetsMutex.Unlock()
return nil
}
// Fallback to individual offset application
var errors []string
// Apply GPU core offsets
for pstate, offset := range config.GPUOffsets {
if err := setClockOffset(device, "core", pstate, offset); err != nil {
errors = append(errors, fmt.Sprintf("GPU P%d offset %+d MHz: %v", pstate, offset, err))
} else {
log.Printf("Applied GPU offset %+d MHz to P-state %d on GPU %d", offset, pstate, deviceIndex)
}
}
// Apply memory offsets
for pstate, offset := range config.MemOffsets {
if err := setClockOffset(device, "mem", pstate, offset); err != nil {
errors = append(errors, fmt.Sprintf("Memory P%d offset %+d MHz: %v", pstate, offset, err))
} else {
log.Printf("Applied memory offset %+d MHz to P-state %d on GPU %d", offset, pstate, deviceIndex)
}
}
if len(errors) > 0 {
return fmt.Errorf("some offsets failed to apply: %s", strings.Join(errors, "; "))
}
// Cache applied offsets for reporting
offsetsMutex.Lock()
if lastAppliedOffsets == nil {
lastAppliedOffsets = make(map[int]ClockOffsets)
}
appliedOffsets := ClockOffsets{
GPUOffsets: make(map[uint32]ClockOffset),
MemOffsets: make(map[uint32]ClockOffset),
}
for pstate, offset := range config.GPUOffsets {
appliedOffsets.GPUOffsets[pstate] = ClockOffset{Current: offset, Min: -500, Max: 500}
}
for pstate, offset := range config.MemOffsets {
appliedOffsets.MemOffsets[pstate] = ClockOffset{Current: offset, Min: -1000, Max: 1000}
}
lastAppliedOffsets[deviceIndex] = appliedOffsets
offsetsMutex.Unlock()
return nil
}
// applyPowerLimit applies the appropriate power limit based on the current temperature
func applyPowerLimit(device nvml.Device, index int, currentTemp uint) error {
limits, exists := gpuPowerLimits[index]
if !exists {
return nil // No limits set for this GPU
}
var newLimit uint
if currentTemp <= uint(limits.LowTemp) {
newLimit = limits.LowTempLimit
} else if currentTemp <= uint(limits.MediumTemp) {
newLimit = limits.MediumTempLimit
} else {
newLimit = limits.HighTempLimit
}
ret := device.SetPowerManagementLimit(uint32(newLimit * 1000)) // Convert watts to milliwatts
if ret != nvml.SUCCESS {