Compare commits
18 Commits
cb2e42143a
...
feat/train
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d2a4049d3 | |||
| 0cbaf53e86 | |||
| 80fd2bda3e | |||
| fb647e5991 | |||
| 87575a62f7 | |||
| 246c11f8b0 | |||
| 2c1f9bdf5c | |||
| 5799f7dfb2 | |||
| 9f428e9572 | |||
| 904968a1be | |||
| 4b44be6a29 | |||
| f9f0662f8e | |||
| 7416327cc3 | |||
| da31bd9d99 | |||
| f3e5347335 | |||
| 7d5581f60c | |||
| b4428217ea | |||
| 8a63fdacdd |
@@ -5,6 +5,13 @@ services:
|
||||
dockerfile: Dockerfile-dev
|
||||
image: kamco-cd-training-api:${IMAGE_TAG:-latest}
|
||||
container_name: kamco-cd-training-api
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
ports:
|
||||
- "7200:8080"
|
||||
environment:
|
||||
|
||||
@@ -5,6 +5,13 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
image: kamco-train-api:${IMAGE_TAG:-latest}
|
||||
container_name: kamco-train-api
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
expose:
|
||||
- "8080"
|
||||
environment:
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.kamco.cd.training.common.dto;
|
||||
|
||||
public class MonitorDto {
|
||||
|
||||
public int cpu; // CPU 사용률 (%)
|
||||
public long[] memory; // "사용/전체"
|
||||
public int gpu; // 🔥 전체 GPU 평균 (%)
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.kamco.cd.training.common.service;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Log4j2
|
||||
public class GpuDmonReader {
|
||||
|
||||
// =========================
|
||||
// GPU 사용률 저장소
|
||||
// key: GPU index (0,1,2...)
|
||||
// value: 현재 GPU 사용률 (%)
|
||||
// ConcurrentHashMap → 멀티스레드 안전
|
||||
// =========================
|
||||
private final Map<Integer, Integer> gpuUtilMap = new ConcurrentHashMap<>();
|
||||
|
||||
// =========================
|
||||
// 외부 조회용
|
||||
// SystemMonitorService에서 호출
|
||||
// =========================
|
||||
public Map<Integer, Integer> getGpuUtilMap() {
|
||||
return gpuUtilMap;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Bean 초기화 시 실행
|
||||
// - 별도 스레드에서 GPU 모니터링 시작
|
||||
// - 메인 스레드 block 방지
|
||||
// =========================
|
||||
@PostConstruct
|
||||
public void start() {
|
||||
|
||||
// nvidia-smi 없는 환경이면 GPU 모니터링 비활성화
|
||||
if (!isNvidiaAvailable()) {
|
||||
log.warn("nvidia-smi not found. GPU monitoring disabled.");
|
||||
return;
|
||||
}
|
||||
|
||||
// 데몬 스레드로 실행 (서버 종료 시 자동 종료)
|
||||
Thread t = new Thread(this::runLoop, "gpu-dmon-thread");
|
||||
t.setDaemon(true);
|
||||
t.start();
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 무한 루프
|
||||
// - dmon 실행
|
||||
// - 죽으면 자동 재시작
|
||||
// =========================
|
||||
private void runLoop() {
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
runDmon(); // GPU 사용률 수집 시작
|
||||
} catch (Exception e) {
|
||||
// dmon 프로세스 종료되면 여기로 들어옴
|
||||
log.warn("dmon restart: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 5초 대기 후 재시작
|
||||
sleep(5000);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// nvidia-smi dmon 실행
|
||||
// - GPU 사용률 스트리밍으로 계속 수신
|
||||
// =========================
|
||||
private void runDmon() throws Exception {
|
||||
|
||||
// -s u → GPU utilization만 출력
|
||||
ProcessBuilder pb = new ProcessBuilder("nvidia-smi", "dmon", "-s", "u");
|
||||
|
||||
// 프로세스 실행 후 stdout 읽기
|
||||
try (BufferedReader br =
|
||||
new BufferedReader(new InputStreamReader(pb.start().getInputStream()))) {
|
||||
|
||||
String line;
|
||||
|
||||
// dmon은 계속 출력됨 (스트리밍)
|
||||
while ((line = br.readLine()) != null) {
|
||||
|
||||
// 헤더 제거 (#로 시작)
|
||||
if (line.startsWith("#")) continue;
|
||||
|
||||
line = line.trim();
|
||||
if (line.isEmpty()) continue;
|
||||
|
||||
// 공백 기준 분리
|
||||
String[] parts = line.split("\\s+");
|
||||
|
||||
// 첫 번째 값이 GPU index인지 확인
|
||||
if (!parts[0].matches("\\d+")) continue;
|
||||
|
||||
int index = Integer.parseInt(parts[0]);
|
||||
|
||||
try {
|
||||
// 두 번째 값이 GPU 사용률 (sm)
|
||||
int util = Integer.parseInt(parts[1]);
|
||||
|
||||
// 최신 값 갱신
|
||||
gpuUtilMap.put(index, util);
|
||||
|
||||
} catch (Exception ignored) {
|
||||
// 파싱 실패 시 무시
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 여기까지 왔다는 건 dmon 프로세스 종료됨
|
||||
// → runLoop에서 재시작하도록 예외 발생
|
||||
throw new IllegalStateException("dmon stopped");
|
||||
}
|
||||
|
||||
// =========================
|
||||
// nvidia-smi 존재 여부 확인
|
||||
// =========================
|
||||
private boolean isNvidiaAvailable() {
|
||||
try {
|
||||
Process p = new ProcessBuilder("which", "nvidia-smi").start();
|
||||
return p.waitFor() == 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// sleep 유틸
|
||||
// =========================
|
||||
private void sleep(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package com.kamco.cd.training.common.service;
|
||||
|
||||
import com.kamco.cd.training.common.dto.MonitorDto;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Log4j2
|
||||
public class SystemMonitorService {
|
||||
|
||||
// =========================
|
||||
// CPU 이전값 (delta 계산용)
|
||||
// - /proc/stat은 누적값이기 때문에
|
||||
// - 이전 값과 비교해서 사용률 계산
|
||||
// =========================
|
||||
private long prevIdle = 0;
|
||||
private long prevTotal = 0;
|
||||
|
||||
// =========================
|
||||
// 최근 30초 히스토리
|
||||
// - CPU: 30개 (1초 * 30)
|
||||
// - GPU: GPU별 30개
|
||||
// =========================
|
||||
private final Deque<Double> cpuHistory = new ArrayDeque<>();
|
||||
|
||||
// key: GPU index
|
||||
// value: 최근 30개 사용률
|
||||
private final Map<Integer, Deque<Integer>> gpuHistory = new ConcurrentHashMap<>();
|
||||
|
||||
// =========================
|
||||
// GPU 데이터 제공 (dmon reader)
|
||||
// =========================
|
||||
private final GpuDmonReader gpuReader;
|
||||
|
||||
// =========================
|
||||
// 캐시 (API 응답용)
|
||||
// - 매 요청마다 계산하지 않기 위해 사용
|
||||
// - volatile → 멀티스레드 안전하게 최신값 유지
|
||||
// =========================
|
||||
private volatile MonitorDto cached = new MonitorDto();
|
||||
|
||||
// =========================
|
||||
// 1초마다 수집
|
||||
// =========================
|
||||
@Scheduled(fixedRate = 1000)
|
||||
public void collect() {
|
||||
try {
|
||||
|
||||
// =====================
|
||||
// 1. CPU 수집
|
||||
// =====================
|
||||
double cpu = readCpu();
|
||||
|
||||
cpuHistory.add(cpu);
|
||||
|
||||
// 30개 유지 (rolling window)
|
||||
if (cpuHistory.size() > 30) cpuHistory.poll();
|
||||
|
||||
// =====================
|
||||
// 2. GPU 수집
|
||||
// =====================
|
||||
Map<Integer, Integer> gpuMap = gpuReader.getGpuUtilMap();
|
||||
|
||||
for (Map.Entry<Integer, Integer> entry : gpuMap.entrySet()) {
|
||||
|
||||
int index = entry.getKey();
|
||||
int util = entry.getValue();
|
||||
|
||||
// GPU별 히스토리 생성 및 추가
|
||||
gpuHistory.computeIfAbsent(index, k -> new ArrayDeque<>()).add(util);
|
||||
|
||||
// 30개 유지
|
||||
Deque<Integer> q = gpuHistory.get(index);
|
||||
if (q.size() > 30) q.poll();
|
||||
}
|
||||
|
||||
// =====================
|
||||
// 3. 캐시 업데이트
|
||||
// =====================
|
||||
updateCache();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("collect error", e);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// CPU 사용률 계산
|
||||
// - /proc/stat 사용
|
||||
// - 이전값과의 차이로 계산 (delta 방식)
|
||||
// =========================
|
||||
private double readCpu() throws Exception {
|
||||
|
||||
if (!isLinux()) return 0;
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("/proc/stat"))) {
|
||||
|
||||
String[] p = br.readLine().split("\\s+");
|
||||
|
||||
long user = Long.parseLong(p[1]);
|
||||
long nice = Long.parseLong(p[2]);
|
||||
long system = Long.parseLong(p[3]);
|
||||
long idle = Long.parseLong(p[4]);
|
||||
long iowait = Long.parseLong(p[5]);
|
||||
long irq = Long.parseLong(p[6]);
|
||||
long softirq = Long.parseLong(p[7]);
|
||||
|
||||
long total = user + nice + system + idle + iowait + irq + softirq;
|
||||
long idleAll = idle + iowait;
|
||||
|
||||
// 최초 실행 시 기준값만 저장
|
||||
if (prevTotal == 0) {
|
||||
prevTotal = total;
|
||||
prevIdle = idleAll;
|
||||
return 0;
|
||||
}
|
||||
|
||||
long totalDiff = total - prevTotal;
|
||||
long idleDiff = idleAll - prevIdle;
|
||||
|
||||
prevTotal = total;
|
||||
prevIdle = idleAll;
|
||||
|
||||
if (totalDiff == 0) return 0;
|
||||
|
||||
// CPU 사용률 (%)
|
||||
return (1.0 - (double) idleDiff / totalDiff) * 100;
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Linux 환경 체크
|
||||
// =========================
|
||||
private boolean isLinux() {
|
||||
return System.getProperty("os.name").toLowerCase().contains("linux");
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Memory 조회 (/proc/meminfo)
|
||||
// - OS 값 그대로 사용 (kB)
|
||||
// - [사용량, 전체]
|
||||
// =========================
|
||||
private long[] readMemory() throws Exception {
|
||||
|
||||
if (!isLinux()) return new long[] {0, 0};
|
||||
|
||||
try (BufferedReader br = new BufferedReader(new FileReader("/proc/meminfo"))) {
|
||||
|
||||
long total = 0;
|
||||
long available = 0;
|
||||
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
if (line.startsWith("MemTotal")) {
|
||||
total = Long.parseLong(line.replaceAll("\\D+", ""));
|
||||
} else if (line.startsWith("MemAvailable")) {
|
||||
available = Long.parseLong(line.replaceAll("\\D+", ""));
|
||||
}
|
||||
}
|
||||
|
||||
long used = total - available;
|
||||
|
||||
return new long[] {used, total};
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 캐시 업데이트
|
||||
// - CPU: 30초 평균
|
||||
// - GPU: 전체 샘플 평균
|
||||
// - Memory: 현재값
|
||||
// =========================
|
||||
private void updateCache() throws Exception {
|
||||
|
||||
MonitorDto dto = new MonitorDto();
|
||||
|
||||
// =====================
|
||||
// CPU 평균 (30초)
|
||||
// =====================
|
||||
dto.cpu = (int) cpuHistory.stream().mapToDouble(Double::doubleValue).average().orElse(0);
|
||||
|
||||
// =====================
|
||||
// Memory (kB 그대로)
|
||||
// =====================
|
||||
dto.memory = readMemory();
|
||||
|
||||
// =====================
|
||||
// GPU 평균 (🔥 전체 샘플 기준)
|
||||
// =====================
|
||||
int sum = 0;
|
||||
int count = 0;
|
||||
|
||||
for (Deque<Integer> q : gpuHistory.values()) {
|
||||
for (int v : q) {
|
||||
sum += v;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
dto.gpu = (count == 0) ? 0 : sum / count;
|
||||
|
||||
// =====================
|
||||
// 캐시 교체 (atomic)
|
||||
// =====================
|
||||
this.cached = dto;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 외부 조회
|
||||
// - Controller에서 호출
|
||||
// =========================
|
||||
public MonitorDto get() {
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public class StartupLogger {
|
||||
"""
|
||||
|
||||
╔════════════════════════════════════════════════════════════════════════════════╗
|
||||
║ 🚀 APPLICATION STARTUP INFORMATION ║
|
||||
║ 🚀 APPLICATION STARTUP INFORMATION 2 ║
|
||||
╠════════════════════════════════════════════════════════════════════════════════╣
|
||||
║ PROFILE CONFIGURATION ║
|
||||
╠────────────────────────────────────────────────────────────────────────────────╣
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.kamco.cd.training.model;
|
||||
|
||||
import com.kamco.cd.training.common.dto.MonitorDto;
|
||||
import com.kamco.cd.training.common.service.SystemMonitorService;
|
||||
import com.kamco.cd.training.config.api.ApiResponseDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto;
|
||||
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
|
||||
@@ -40,6 +42,7 @@ public class ModelTrainMngApiController {
|
||||
private final ModelTrainMngService modelTrainMngService;
|
||||
private final ModelTrainMetricsJobService modelTrainMetricsJobService;
|
||||
private final ModelTestMetricsJobService modelTestMetricsJobService;
|
||||
private final SystemMonitorService systemMonitorService;
|
||||
|
||||
@Operation(summary = "모델학습 목록 조회", description = "모델학습 목록 조회 API")
|
||||
@ApiResponses(
|
||||
@@ -214,4 +217,22 @@ public class ModelTrainMngApiController {
|
||||
modelTestMetricsJobService.findTestValidMetricCsvFiles();
|
||||
return ApiResponseDto.ok(null);
|
||||
}
|
||||
|
||||
@Operation(summary = "학습서버 시스템 사용율 조회", description = "cpu, gpu, memory 사용율 조회")
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "검색 성공",
|
||||
content =
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = Long.class))),
|
||||
@ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
|
||||
})
|
||||
@GetMapping("/monitor")
|
||||
public ApiResponseDto<MonitorDto> getSystem() throws IOException {
|
||||
return ApiResponseDto.ok(systemMonitorService.get());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,8 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
builder.and(dataset.deleted.isFalse());
|
||||
|
||||
if (StringUtils.isNotBlank(req.getDataType()) && !"CURRENT".equals(req.getDataType())) {
|
||||
builder.and(dataset.dataType.eq(req.getDataType()));
|
||||
}
|
||||
@@ -249,6 +251,7 @@ public class DatasetRepositoryImpl implements DatasetRepositoryCustom {
|
||||
public List<SelectDataSet> getDatasetSelectG2G3List(DatasetReq req) {
|
||||
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
builder.and(dataset.deleted.isFalse());
|
||||
|
||||
NumberExpression<Long> selectedCnt = null;
|
||||
NumberExpression<Long> wasteCnt =
|
||||
|
||||
@@ -46,10 +46,17 @@ public class DockerTrainService {
|
||||
@Value("${train.docker.shmSize:16g}")
|
||||
private String shmSize;
|
||||
|
||||
// data 경로 request,response 상위 폴더
|
||||
@Value("${train.docker.basePath}")
|
||||
private String basePath;
|
||||
|
||||
// IPC host 사용 여부
|
||||
@Value("${train.docker.ipcHost:true}")
|
||||
private boolean ipcHost;
|
||||
|
||||
@Value("${spring.profiles.active}")
|
||||
private String profile;
|
||||
|
||||
private final ModelTrainJobCoreService modelTrainJobCoreService;
|
||||
|
||||
/**
|
||||
@@ -254,7 +261,9 @@ public class DockerTrainService {
|
||||
|
||||
// 요청/결과 디렉토리 볼륨 마운트
|
||||
c.add("-v");
|
||||
c.add("/home/kcomu/data" + "/tmp:/data");
|
||||
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
||||
c.add("-v");
|
||||
c.add(basePath + "/tmp:/data");
|
||||
c.add("-v");
|
||||
c.add(responseDir + ":/checkpoints");
|
||||
|
||||
@@ -273,8 +282,15 @@ public class DockerTrainService {
|
||||
addArg(c, "--output-folder", req.getOutputFolder());
|
||||
addArg(c, "--input-size", req.getInputSize());
|
||||
addArg(c, "--crop-size", req.getCropSize());
|
||||
addArg(c, "--batch-size", req.getBatchSize());
|
||||
addArg(c, "--gpu-ids", req.getGpuIds()); // null
|
||||
// addArg(c, "--batch-size", req.getBatchSize());
|
||||
// addArg(c, "--gpu-ids", req.getGpuIds()); // null
|
||||
if ("prod".equals(profile)) {
|
||||
addArg(c, "--batch-size", 2); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
|
||||
addArg(c, "--gpus", "1"); // 학습서버 GPU 1개인 곳은 1이어야 함
|
||||
addArg(c, "--gpu-ids", "0"); // 학습서버 GPU 1개인 곳은 0이어야 함
|
||||
} else {
|
||||
addArg(c, "--batch-size", req.getBatchSize()); // 학습서버 GPU 1개인 곳은 batch-size:2 까지만 가능
|
||||
}
|
||||
addArg(c, "--lr", req.getLearningRate());
|
||||
addArg(c, "--backbone", req.getBackbone());
|
||||
addArg(c, "--epochs", req.getEpochs());
|
||||
@@ -440,11 +456,14 @@ public class DockerTrainService {
|
||||
c.add("--rm");
|
||||
c.add("--gpus");
|
||||
c.add("all");
|
||||
|
||||
c.add("--ipc=host");
|
||||
c.add("--shm-size=" + shmSize);
|
||||
|
||||
c.add("-v");
|
||||
c.add("/home/kcomu/data" + "/tmp:/data");
|
||||
c.add(basePath + ":" + basePath); // 심볼릭 링크와 연결되는 실제 파일 경로도 마운트를 해줘야 함
|
||||
c.add("-v");
|
||||
c.add(basePath + "/tmp:/data");
|
||||
|
||||
c.add("-v");
|
||||
c.add(responseDir + ":/checkpoints");
|
||||
|
||||
@@ -70,7 +70,7 @@ public class TmpDatasetService {
|
||||
throw new IOException("No symlinks created.");
|
||||
}
|
||||
|
||||
log.info("tmp dataset created: {}, symlinksMade={}", tmp, linksMade);
|
||||
log.info("tmp dataset created: {}, linksMade={}", tmp, linksMade);
|
||||
}
|
||||
|
||||
private long link(Path tmp, String type, String part, String fullPath) throws IOException {
|
||||
@@ -92,28 +92,12 @@ public class TmpDatasetService {
|
||||
Files.delete(dst);
|
||||
}
|
||||
|
||||
try {
|
||||
Files.createLink(dst, src);
|
||||
log.info("hardlink created: {} -> {}", dst, src);
|
||||
} catch (FileSystemException e) {
|
||||
if (e.getMessage() != null && e.getMessage().contains("Invalid cross-device link")) {
|
||||
log.warn(
|
||||
"Hardlink failed due to cross-device link. Fallback to symlink. src={}, dst={}",
|
||||
src,
|
||||
dst);
|
||||
Files.createSymbolicLink(dst, src);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
log.info("symlink created: {} -> {}", dst, src);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private String safe(String s) {
|
||||
return (s == null || s.isBlank()) ? null : s.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* request 전체 폴더 link
|
||||
*
|
||||
|
||||
@@ -47,7 +47,7 @@ member:
|
||||
init_password: kamco1234!
|
||||
|
||||
swagger:
|
||||
local-port: 9080
|
||||
local-port: 8080
|
||||
|
||||
file:
|
||||
sync-root-dir: /app/original-images/
|
||||
|
||||
Reference in New Issue
Block a user