전자기기 리뷰
[데스크톱] 딥러닝 pytorch 벤치마크
교통앵무
2024. 12. 1. 23:02
새 데스크톱을 맞춘 김에 가지고 있는 PC들과 딥러닝 벤치마크를 시도해 보았다.
import torch
torch.cuda.is_available() #True
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import time
# 1. 데이터 생성
def target_function(x):
return np.sin(x)
# 학습 데이터 생성
x_train = np.linspace(-10, 10, 1000).reshape(-1, 1)
y_train = target_function(x_train)
# 데이터를 torch 텐서로 변환
x_train = torch.tensor(x_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.float32)
# 2. MLP 모델 정의
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.layer1 = nn.Linear(1, 64) # 입력층 -> 은닉층1
self.layer2 = nn.Linear(64, 64) # 은닉층1 -> 은닉층2
self.layer3 = nn.Linear(64, 1) # 은닉층2 -> 출력층
def forward(self, x):
x = torch.relu(self.layer1(x)) # ReLU 활성화 함수
x = torch.relu(self.layer2(x)) # ReLU 활성화 함수
x = self.layer3(x)
return x
# 3. 모델, 손실 함수, 옵티마이저 정의
model = MLP()
criterion = nn.MSELoss() # 평균 제곱 오차(MSE) 손실 함수
optimizer = optim.Adam(model.parameters(), lr=0.0001) # Adam 옵티마이저
# 4. 학습 시작 시간 기록
start_time = time.time()
# 5. 모델 학습
epochs = 10000
for epoch in range(epochs):
# 순전파
y_pred = model(x_train)
# 손실 계산
loss = criterion(y_pred, y_train)
# 역전파
optimizer.zero_grad() # 기울기 초기화
loss.backward() # 기울기 계산
optimizer.step() # 가중치 업데이트
# 100번마다 학습 상태 출력
if (epoch + 1) % 1000 == 0:
print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")
# 6. 학습 종료 시간 기록
end_time = time.time()
# 7. 학습 시간 출력
print(f"Total training time: {end_time - start_time:.2f} seconds")
# 8. 예측 결과 출력
import matplotlib.pyplot as plt
with torch.no_grad(): # 기울기 계산을 하지 않음
y_pred = model(x_train)
# 결과 그래프 출력
plt.plot(x_train.numpy(), y_train.numpy(), label='True Function (sin(x))')
plt.plot(x_train.numpy(), y_pred.numpy(), label='Predicted Function')
plt.legend()
plt.show()
- sin 함수 근사 MLP 설계
- 총 10,000 epoch 학습
1. 집컴 (RTX 2080 TI /// Intel Ultra 9 285K + DDR5 32GB)
학습 시간: 13.39 초
2. 연구실컴 (GTX 1050 TI /// Intel I7 8700 + DDR4 32GB)
학습 시간: 33.01 초
3. 연구실 워크스테이션 (RTX A2000 12GB /// AMD Ryzen Threadripper PRO 5975WX + DDR4 128GB)
학습 시간: 10.01 초