meccatronis commited on
Commit
b100231
·
verified ·
1 Parent(s): 6fe8c45

Upload benchmark_fp16.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. benchmark_fp16.py +267 -0
benchmark_fp16.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+ import matplotlib.pyplot as plt
4
+ import matplotlib.animation as animation
5
+ from datetime import datetime
6
+ import subprocess
7
+ import time
8
+ import psutil
9
+ import re
10
+ from collections import deque
11
+ import threading
12
+
13
+ class FP16Benchmark:
14
+ def __init__(self):
15
+ self.max_temp = 85
16
+ self.temperatures = deque(maxlen=200)
17
+ self.tflops_history = deque(maxlen=200)
18
+ self.load_level = deque(maxlen=200)
19
+ self.peak_tflops = 0
20
+ self.running = True
21
+
22
+ self.current_load = 1
23
+ self.matrix_size = 10240
24
+ self.num_operations = 1
25
+ self.num_streams = 1
26
+
27
+ self.fig, (self.ax1, self.ax2, self.ax3) = plt.subplots(3, 1, figsize=(14, 10))
28
+ self.fig.suptitle('BENCHMARK FP16 (HALF PRECISION) - Radeon Pro VII', fontsize=16, weight='bold')
29
+
30
+ self.last_temp_check = time.time()
31
+ self.temp_rising_fast = False
32
+
33
+ def get_gpu_temp(self):
34
+ try:
35
+ result = subprocess.run(['sensors'], capture_output=True, text=True, timeout=0.5)
36
+ for line in result.stdout.split('\n'):
37
+ if 'edge:' in line.lower():
38
+ match = re.search(r'([+-]?\d+\.?\d*)\s*°C', line)
39
+ if match:
40
+ return float(match.group(1))
41
+ except:
42
+ return 0
43
+ return 0
44
+
45
+ def check_system_health(self):
46
+ try:
47
+ start = time.time()
48
+ cpu = psutil.cpu_percent(interval=0.05)
49
+ response = time.time() - start
50
+ if response > 0.4 or cpu > 95:
51
+ return False
52
+ return True
53
+ except:
54
+ return False
55
+
56
+ def calculate_tflops(self, matrix_size, elapsed_time, num_ops, num_streams):
57
+ operations = 2 * (matrix_size ** 3) * num_ops * num_streams
58
+ return (operations / elapsed_time) / 1e12
59
+
60
+ def increase_load(self):
61
+ if self.current_load < 10:
62
+ self.current_load += 1
63
+
64
+ if self.current_load >= 2 and self.num_streams < 4:
65
+ self.num_streams += 1
66
+
67
+ if self.current_load >= 4 and self.num_operations < 30:
68
+ self.num_operations += 5
69
+
70
+ if self.current_load >= 6 and self.matrix_size < 16384:
71
+ self.matrix_size = min(self.matrix_size + 1024, 16384)
72
+
73
+ def decrease_load(self):
74
+ if self.current_load > 1:
75
+ self.current_load -= 1
76
+
77
+ if self.matrix_size > 8192:
78
+ self.matrix_size = max(self.matrix_size - 512, 8192)
79
+
80
+ if self.num_operations > 5:
81
+ self.num_operations = max(self.num_operations - 5, 1)
82
+
83
+ def stress_gpu(self):
84
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
85
+ if device.type == 'cpu':
86
+ print("❌ ERRO: GPU não detectada!")
87
+ self.running = False
88
+ return
89
+
90
+ props = torch.cuda.get_device_properties(0)
91
+ print(f"🎯 GPU: {torch.cuda.get_device_name(0)}")
92
+ print(f"💾 VRAM: {props.total_memory / 1e9:.1f} GB")
93
+ print(f"🔥 Modo: FP16 (Half Precision)")
94
+ print(f"📊 TFLOPS Teórico FP16: ~26.88")
95
+ print(f"⚠️ Limite de temperatura: {self.max_temp}°C\n")
96
+
97
+ streams = [torch.cuda.Stream() for _ in range(4)]
98
+ last_temp = 0
99
+ stable_cycles = 0
100
+
101
+ while self.running:
102
+ current_time = time.time()
103
+ if current_time - self.last_temp_check > 0.05:
104
+ temp = self.get_gpu_temp()
105
+ self.last_temp_check = current_time
106
+
107
+ if len(self.temperatures) > 0:
108
+ temp_delta = temp - last_temp
109
+ if temp_delta > 2:
110
+ self.temp_rising_fast = True
111
+ else:
112
+ self.temp_rising_fast = False
113
+
114
+ if temp >= self.max_temp:
115
+ print(f"\n🚨 TEMPERATURA: {temp}°C - ABORTANDO!")
116
+ self.running = False
117
+ break
118
+
119
+ if temp >= self.max_temp - 3:
120
+ print(f"\n⚠️ ALERTA! Temp: {temp}°C - Reduzindo...")
121
+ self.decrease_load()
122
+ self.decrease_load()
123
+
124
+ if self.temp_rising_fast and temp > 75:
125
+ self.decrease_load()
126
+
127
+ last_temp = temp
128
+ else:
129
+ temp = last_temp
130
+
131
+ if not self.check_system_health():
132
+ print(f"\n🚨 SISTEMA INSTÁVEL!")
133
+ self.running = False
134
+ break
135
+
136
+ try:
137
+ torch.cuda.synchronize()
138
+ start = time.time()
139
+
140
+ for i in range(self.num_streams):
141
+ with torch.cuda.stream(streams[i]):
142
+ # FP16 - HALF PRECISION
143
+ a = torch.randn(self.matrix_size, self.matrix_size, device=device, dtype=torch.float16)
144
+ b = torch.randn(self.matrix_size, self.matrix_size, device=device, dtype=torch.float16)
145
+
146
+ for _ in range(self.num_operations):
147
+ c = torch.mm(a, b)
148
+ a = b
149
+ b = c
150
+
151
+ torch.cuda.synchronize()
152
+ elapsed = time.time() - start
153
+
154
+ tflops = self.calculate_tflops(self.matrix_size, elapsed,
155
+ self.num_operations, self.num_streams)
156
+
157
+ self.temperatures.append(temp)
158
+ self.tflops_history.append(tflops)
159
+ self.load_level.append(self.current_load)
160
+
161
+ if tflops > self.peak_tflops:
162
+ self.peak_tflops = tflops
163
+
164
+ print(f"TFLOPS: {tflops:6.2f} | Temp: {temp:5.1f}°C | Load: {self.current_load}/10 | "
165
+ f"Matrix: {self.matrix_size} | Ops: {self.num_operations} | Peak: {self.peak_tflops:.2f}", end='\r')
166
+
167
+ if temp < 75 and stable_cycles > 10:
168
+ self.increase_load()
169
+ stable_cycles = 0
170
+ elif temp < 80:
171
+ stable_cycles += 1
172
+ else:
173
+ stable_cycles = 0
174
+
175
+ time.sleep(0.02)
176
+
177
+ except RuntimeError as e:
178
+ if "out of memory" in str(e):
179
+ print(f"\n⚠️ VRAM cheia - Reduzindo...")
180
+ self.decrease_load()
181
+ torch.cuda.empty_cache()
182
+ else:
183
+ print(f"\n🚨 ERRO: {e}")
184
+ self.running = False
185
+ break
186
+ except Exception as e:
187
+ print(f"\n🚨 ERRO: {e}")
188
+ self.running = False
189
+ break
190
+
191
+ def update_plot(self, frame):
192
+ if len(self.tflops_history) == 0:
193
+ return
194
+
195
+ self.ax1.clear()
196
+ self.ax2.clear()
197
+ self.ax3.clear()
198
+
199
+ if len(self.tflops_history) > 0:
200
+ self.ax1.plot(list(self.tflops_history), 'b-', linewidth=2.5, label='TFLOPS FP16')
201
+ self.ax1.axhline(y=self.peak_tflops, color='g', linestyle='--', linewidth=2,
202
+ label=f'Peak: {self.peak_tflops:.2f}')
203
+ self.ax1.axhline(y=26.88, color='orange', linestyle=':', linewidth=2,
204
+ label='Teórico: 26.88')
205
+ self.ax1.set_ylabel('TFLOPS (FP16)', fontsize=12, weight='bold')
206
+ self.ax1.set_title('Performance FP16 (Half Precision)', fontsize=12, weight='bold')
207
+ self.ax1.legend(loc='upper left')
208
+ self.ax1.grid(True, alpha=0.3)
209
+ self.ax1.set_ylim(0, 30)
210
+
211
+ if len(self.temperatures) > 0:
212
+ temps = list(self.temperatures)
213
+ self.ax2.plot(temps, 'r-', linewidth=2.5)
214
+ self.ax2.axhline(y=self.max_temp, color='red', linestyle='--', linewidth=2,
215
+ label=f'LIMITE: {self.max_temp}°C')
216
+ self.ax2.fill_between(range(len(temps)), temps, self.max_temp,
217
+ where=[t >= self.max_temp - 5 for t in temps],
218
+ alpha=0.3, color='orange')
219
+ self.ax2.set_ylabel('Temperatura (°C)', fontsize=12, weight='bold')
220
+ self.ax2.set_title('Monitoramento Térmico', fontsize=12, weight='bold')
221
+ self.ax2.legend(loc='upper left')
222
+ self.ax2.grid(True, alpha=0.3)
223
+ self.ax2.set_ylim(30, 95)
224
+
225
+ if len(self.load_level) > 0:
226
+ loads = list(self.load_level)
227
+ self.ax3.plot(loads, 'purple', linewidth=2.5)
228
+ self.ax3.fill_between(range(len(loads)), loads, alpha=0.3, color='purple')
229
+ self.ax3.set_ylabel('Carga (1-10)', fontsize=12, weight='bold')
230
+ self.ax3.set_xlabel('Amostras', fontsize=12, weight='bold')
231
+ self.ax3.set_title('Intensidade', fontsize=12, weight='bold')
232
+ self.ax3.grid(True, alpha=0.3)
233
+ self.ax3.set_ylim(0, 11)
234
+
235
+ if not self.running and len(self.tflops_history) > 0:
236
+ efficiency = (self.peak_tflops / 26.88) * 100
237
+ self.ax1.text(0.5, 0.5,
238
+ f'🏆 PEAK: {self.peak_tflops:.2f} TFLOPS\n'
239
+ f'📊 Eficiência: {efficiency:.1f}%',
240
+ transform=self.ax1.transAxes, fontsize=20,
241
+ ha='center', va='center', color='darkgreen', weight='bold',
242
+ bbox=dict(boxstyle='round,pad=1', facecolor='lightgreen', alpha=0.9))
243
+
244
+ def run(self):
245
+ stress_thread = threading.Thread(target=self.stress_gpu)
246
+ stress_thread.daemon = True
247
+ stress_thread.start()
248
+
249
+ ani = animation.FuncAnimation(self.fig, self.update_plot,
250
+ interval=300, cache_frame_data=False)
251
+ plt.tight_layout()
252
+ plt.show()
253
+ stress_thread.join(timeout=2)
254
+
255
+ print(f"\n\n{'='*70}")
256
+ print(f"{'BENCHMARK FP16 - RESULTADO FINAL':^70}")
257
+ print(f"{'='*70}")
258
+ print(f"🏆 PEAK TFLOPS (FP16): {self.peak_tflops:.2f}")
259
+ print(f"📊 Teórico FP16: 26.88 TFLOPS")
260
+ print(f"📈 Eficiência: {(self.peak_tflops / 26.88) * 100:.1f}%")
261
+ print(f"🌡️ Temp Máxima: {max(self.temperatures) if self.temperatures else 0:.1f}°C")
262
+ print(f"🔥 Carga Máxima: {max(self.load_level) if self.load_level else 0}/10")
263
+ print(f"{'='*70}\n")
264
+
265
+ if __name__ == "__main__":
266
+ bench = FP16Benchmark()
267
+ bench.run()