Ray Tune과 YOLO26을 활용한 효율적인 하이퍼파라미터 튜닝
하이퍼파라미터 튜닝은 모델 성능을 최대로 높이는 하이퍼파라미터 조합을 탐색합니다. 다양한 하이퍼파라미터 값을 사용해 여러 번의 실험을 실행하고 각 실험의 성능을 평가합니다.
Ultralytics YOLO26과 Ray Tune으로 튜닝 속도 향상#
Ultralytics YOLO26은 하이퍼파라미터 튜닝을 위해 Ray Tune을 통합합니다. Ray Tune을 사용하면 고급 탐색 전략, 병렬 처리, 조기 종료 기능으로 튜닝 과정을 단축할 수 있습니다.
Ray Tune#
Ray Tune은 효율성과 유연성을 위해 설계된 하이퍼파라미터 튜닝 라이브러리입니다. 다양한 탐색 전략, 병렬 처리, 조기 종료 전략을 지원하며 Ultralytics YOLO26을 포함한 널리 사용되는 머신러닝 프레임워크와 통합됩니다.
Weights & Biases 통합#
YOLO26은 튜닝 과정을 모니터링하기 위해 Weights & Biases와 선택적으로 통합하는 기능도 지원합니다.
설치#
필수 패키지를 설치하려면 다음을 실행하세요:
# Install and update Ultralytics and Ray Tune packages
pip install -U ultralytics "ray[tune]" optuna
# Optionally install and enable W&B for per-trial logging
pip install wandb
yolo settings wandb=True사용법#
from ultralytics import YOLO
# YOLO26n 모델 로드
model = YOLO("yolo26n.pt")
# COCO8 데이터셋에서 YOLO26n 학습을 위한 하이퍼파라미터 튜닝 시작
result_grid = model.tune(data="coco8.yaml", use_ray=True)tune() 메서드 매개변수#
YOLO26의 tune() 메서드는 Ray Tune을 사용한 하이퍼파라미터 튜닝을 위한 사용하기 쉬운 인터페이스를 제공합니다. 이 메서드는 튜닝 프로세스를 맞춤 설정할 수 있는 여러 인수를 받습니다. 아래에서 각 매개변수를 자세히 설명합니다.
| 매개변수 | 유형 | 설명 | 기본값 |
|---|---|---|---|
data | str or list | 튜너 실행에 사용할 데이터셋 YAML로, 학습 및 검증 데이터 경로와 기타 데이터셋별 설정을 지정합니다. 분류 작업에는 데이터셋 디렉터리 또는 기본 제공 데이터셋 이름(예: imagenet10)을 대신 사용합니다. 목록을 지정하면 각 트라이얼에서 모든 데이터셋으로 학습하고 작업 지표의 평균을 보고합니다. | |
space | dict, optional | Ray Tune의 하이퍼파라미터 검색 공간을 정의하는 딕셔너리입니다. 각 키는 하이퍼파라미터 이름에 해당하며, 값은 튜닝 중 탐색할 값의 범위를 지정합니다. 지정하지 않으면 YOLO26은 다양한 하이퍼파라미터를 포함하는 기본 검색 공간을 사용합니다. | |
grace_period | int, optional | Ray Tune의 ASHA 스케줄러에서 유예 기간으로 설정하는 에포크 수입니다. 스케줄러는 이 에포크 수 이전에 어떤 trial도 종료하지 않습니다(epochs로 제한). search_alg="bohb"에서는 사용되지 않습니다. | 10 |
gpu_per_trial | int, optional | Ray가 각 trial에 할당하는 GPU 수입니다. GPU 학습을 사용하려면 이 값을 명시적으로 설정해야 하며, 생략하면 trial에 GPU 리소스가 할당되지 않습니다. | None |
iterations | int, optional | 튜닝 중 실행할 최대 trial 수입니다. 이 매개변수를 사용하면 테스트할 하이퍼파라미터 조합의 총수를 제어하여 튜닝 프로세스가 무한정 실행되지 않도록 할 수 있습니다. | 300 |
search_alg | str or Searcher, optional | 사용할 Ray Tune 검색 전략입니다. Ray searcher 객체를 직접 전달하거나 optuna, hyperopt, bayesopt, bohb, hebo, nevergrad, zoopt, ax 또는 random과 같이 지원되는 문자열을 사용할 수 있습니다. 문자열 기반 searcher는 기본 작업 메트릭과 mode="max"를 자동으로 사용합니다. 기본값은 병렬 처리를 고려한 제안을 사용하는 Optuna 다변량 TPE입니다. | "optuna" |
**train_args | dict, optional | 튜닝 중 train() 메서드에 전달할 추가 인수입니다. 이러한 인수에는 학습 epoch 수, 배치 크기 및 학습 관련 기타 설정이 포함될 수 있습니다. | {} |
이러한 매개변수를 맞춤 설정하면 특정 요구사항과 사용 가능한 컴퓨팅 리소스에 맞게 하이퍼파라미터 최적화 프로세스를 세밀하게 조정할 수 있습니다.
기본 검색 공간 설명#
다음 표에는 Ray Tune을 사용한 YOLO26 하이퍼파라미터 튜닝의 기본 검색 공간 매개변수가 나와 있습니다. 각 매개변수에는 tune.uniform()으로 정의된 특정 값 범위가 있으며, close_mosaic은 예외적으로 tune.randint()를 사용합니다.
| 매개변수 | 범위 | 설명 |
|---|---|---|
lr0 | tune.uniform(1e-5, 1e-2) | 최적화 중 스텝 크기를 제어하는 초기 학습률입니다. 값이 높으면 학습 속도가 빨라지지만 불안정해질 수 있습니다. |
lrf | tune.uniform(0.01, 1.0) | 학습이 끝날 때 학습률이 얼마나 감소할지를 결정하는 최종 학습률 계수입니다. |
momentum | tune.uniform(0.7, 0.98) | 학습 속도를 높이고 로컬 최소값을 벗어나는 데 도움이 되는 옵티마이저의 모멘텀 계수입니다. |
weight_decay | tune.uniform(0.0, 0.001) | 큰 가중치 값에 페널티를 부여해 과적합을 방지하는 정규화 매개변수입니다. |
warmup_epochs | tune.uniform(0.0, 5.0) | 초기 학습을 안정화하기 위해 학습률을 점진적으로 높이는 epoch 수입니다. |
warmup_momentum | tune.uniform(0.0, 0.95) | 워밍업 기간에 점진적으로 증가하는 초기 모멘텀 값입니다. |
box | tune.uniform(1.0, 20.0) | 모델의 위치 정확도 균형을 조정하는 바운딩 박스 손실 항목의 가중치입니다. |
cls | tune.uniform(0.1, 4.0) | 모델의 클래스 예측 정확도 균형을 조정하는 분류 손실 항목의 가중치입니다. |
cls_pw | tune.uniform(0.0, 1.0) | 비활성화(0.0)부터 전체 역빈도 가중치 적용(1.0)까지의 클래스 가중치 조정 값입니다. |
dfl | tune.uniform(0.4, 12.0) | 정밀한 바운딩 박스 위치 지정에 중점을 두는 박스 거리 회귀 항목의 가중치입니다. |
hsv_h | tune.uniform(0.0, 0.1) | 모델의 일반화 성능을 높이기 위해 색상 변화를 주는 색조 증강 범위입니다. |
hsv_s | tune.uniform(0.0, 0.9) | 강건성을 개선하기 위해 색상 강도를 변화시키는 채도 증강 범위입니다. |
hsv_v | tune.uniform(0.0, 0.9) | 다양한 조명 조건에서 모델 성능을 높이는 명도 증강 범위입니다. |
degrees | tune.uniform(0.0, 45.0) | 회전된 객체 인식을 개선하는 회전 증강 범위(도 단위)입니다. |
translate | tune.uniform(0.0, 0.9) | 이미지를 가로 및 세로 방향으로 이동시키는 이동 증강 범위입니다. |
scale | tune.uniform(0.0, 0.95) | 서로 다른 거리에 있는 객체를 모사하는 크기 조정 증강 범위입니다. |
shear | tune.uniform(0.0, 10.0) | 원근 변화를 모사하는 전단 증강 범위(도 단위)입니다. |
perspective | tune.uniform(0.0, 0.001) | 3D 시점 변화를 모사하는 원근 증강 범위입니다. |
flipud | tune.uniform(0.0, 1.0) | 데이터셋 다양성을 높이는 수직 뒤집기 증강 확률입니다. |
fliplr | tune.uniform(0.0, 1.0) | 대칭 객체에 유용한 수평 뒤집기 증강 확률입니다. |
bgr | tune.uniform(0.0, 1.0) | 색상 불변성을 높이는 BGR 채널 교환 증강 확률입니다. |
mosaic | tune.uniform(0.0, 1.0) | 네 장의 이미지를 하나의 학습 샘플로 결합하는 모자이크 증강 확률입니다. |
mixup | tune.uniform(0.0, 1.0) | 두 이미지와 해당 레이블을 혼합하는 MixUp 증강 확률입니다. |
cutmix | tune.uniform(0.0, 1.0) | 지역 특징을 유지하면서 이미지 영역을 결합하는 CutMix 증강 확률입니다. |
copy_paste | tune.uniform(0.0, 1.0) | flip 모드에서는 복사 가능한 객체 중 이미지에 복사할 비율을 지정하고, mixup 모드에서는 이를 실행할 확률도 지정합니다. |
close_mosaic | tune.randint(0, 11) | 학습 완료 전 안정화를 위해 마지막 N epoch 동안 모자이크를 비활성화합니다. |
사용자 지정 검색 공간 예제#
이 예제에서는 Ray Tune과 YOLO26으로 하이퍼파라미터를 튜닝할 때 사용자 지정 탐색 공간을 사용하는 방법을 보여줍니다. 사용자 지정 탐색 공간을 제공하면 관심 있는 특정 하이퍼파라미터에 튜닝 과정을 집중할 수 있습니다.
from ray import tune
from ultralytics import YOLO
# YOLO 모델 정의
model = YOLO("yolo26n.pt")
# 모델에서 Ray Tune 실행
result_grid = model.tune(
data="coco8.yaml",
space={"lr0": tune.uniform(1e-5, 1e-2)},
epochs=50,
use_ray=True,
)위 코드 스니펫은 사전 학습된 YOLO26n 가중치로 YOLO 모델을 생성한 다음, tune() 메서드를 데이터셋 구성 coco8.yaml와 함께 호출합니다. 초기 학습률 lr0에 대한 사용자 지정 탐색 공간을 키 "lr0"와 값 tune.uniform(1e-5, 1e-2)으로 구성된 딕셔너리로 제공합니다. 마지막으로 에포크 수와 같은 추가 학습 인수를 튜닝 메서드에 epochs=50로 직접 전달합니다.
검색 알고리즘 예제#
Ray Tune 검색 전략을 이름으로 선택할 수 있습니다. 문자열 기반 검색 알고리즘의 경우 Ultralytics는 현재 작업의 기본 최적화 메트릭과 mode="max"를 자동으로 사용합니다. search_alg을 제공하지 않으면 Ultralytics는 병렬 처리를 고려한 제안을 사용하는 Optuna 다변량 TPE를 사용합니다.
from ultralytics import YOLO
# YOLO 모델 정의
model = YOLO("yolo26n.pt")
result_grid = model.tune(
data="coco8.yaml",
epochs=50,
search_alg="optuna",
use_ray=True,
)searcher의 샘플러를 맞춤 설정하거나 메트릭 및 최적화 모드를 재정의해야 하는 경우 문자열 대신 인스턴스화된 Ray Tune searcher 객체를 전달합니다.
from ray.tune.search.optuna import OptunaSearch
from ultralytics import YOLO
# YOLO 모델 정의
model = YOLO("yolo26n.pt")
# searcher 정의
searcher = OptunaSearch(
metric="metrics/mAP50-95(B)",
mode="max",
)
result_grid = model.tune(
data="coco8.yaml",
epochs=50,
search_alg=searcher,
use_ray=True,
)Ray Tune으로 중단된 하이퍼파라미터 튜닝 세션 재개#
resume=True을 전달하면 중단된 Ray Tune 세션을 재개할 수 있습니다. 선택적으로 재개에 사용할 Ray Tune 디렉터리 name을 runs/{task} 아래에 전달할 수 있습니다. 그렇지 않으면 마지막으로 중단된 세션을 재개합니다. iterations과 space를 다시 제공할 필요는 없지만 data와 epochs을 포함한 나머지 학습 인수는 다시 제공해야 합니다.
from ultralytics import YOLO
# YOLO 모델 정의
model = YOLO("yolo26n.pt")
# 이전 실행 재개
results = model.tune(use_ray=True, data="coco8.yaml", epochs=50, resume=True)
# 이름이 'tune_exp_2'인 Ray Tune 실행 재개
results = model.tune(use_ray=True, data="coco8.yaml", epochs=50, name="tune_exp_2", resume=True)Ray Tune 결과 처리#
Ray Tune으로 하이퍼파라미터 튜닝 실험을 실행한 후에는 얻은 결과를 다양하게 분석할 수 있습니다. 이 가이드에서는 이러한 결과를 처리하고 분석하는 일반적인 워크플로를 안내합니다.
디렉터리에서 Tune 실험 결과 로드#
model.tune(use_ray=True)은 Ray ResultGrid을 반환하고 실험을 runs/{task}/tune 또는 전달한 name에 저장합니다. 원래 스크립트가 종료된 후 결과를 로드하려면 세션을 재개합니다. 그러면 저장된 trial이 복원되고 동일한 ResultGrid가 반환됩니다.
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
result_grid = model.tune(data="coco8.yaml", epochs=50, use_ray=True, resume=True)기본 실험 수준 분석#
trial의 성능을 개괄적으로 확인합니다. trial 중 오류가 발생했는지 빠르게 확인할 수 있습니다.
if result_grid.errors:
print("One or more trials failed!")
else:
print("No errors!")기본 trial 수준 분석#
개별 trial의 하이퍼파라미터 구성과 마지막으로 보고된 메트릭에 액세스합니다.
for i, result in enumerate(result_grid):
print(f"Trial #{i}: Configuration: {result.config}, Last Reported Metrics: {result.metrics}")trial에서 보고된 메트릭 전체 이력 시각화#
각 trial에서 보고된 메트릭의 이력을 시각화하여 시간이 지남에 따라 메트릭이 어떻게 변화했는지 확인할 수 있습니다.
import matplotlib.pyplot as plt
for i, result in enumerate(result_grid):
plt.plot(
result.metrics_dataframe["training_iteration"],
result.metrics_dataframe["metrics/mAP50-95(B)"],
label=f"Trial {i}",
)
plt.xlabel("Training Iterations")
plt.ylabel("mAP50-95")
plt.legend()
plt.show()요약#
이 가이드에서는 Ultralytics를 사용해 Ray Tune으로 실행한 실험 결과를 분석하는 일반적인 워크플로를 다뤘습니다. 주요 단계에는 디렉터리에서 실험 결과를 로드하고, 기본적인 실험 수준 및 trial 수준 분석을 수행하고, 메트릭을 시각화하는 과정이 포함됩니다.
하이퍼파라미터 튜닝 실험을 최대한 활용하려면 Ray Tune의 결과 분석 문서를 살펴보세요.
자주 묻는 질문#
Ray Tune을 사용해 Ultralytics YOLO26 모델의 하이퍼파라미터를 튜닝하려면 다음 단계를 따르세요.
-
필수 패키지 설치:
pip install -U ultralytics "ray[tune]" optuna pip install wandb # optional for logging yolo settings wandb=True -
YOLO26 모델을 로드하고 튜닝 시작:
from ultralytics import YOLO # YOLO26 모델 로드 model = YOLO("yolo26n.pt") # COCO8 데이터셋으로 튜닝 시작 result_grid = model.tune(data="coco8.yaml", use_ray=True)
이 기능은 Ray Tune의 탐색 전략과 병렬 처리를 사용하여 모델의 하이퍼파라미터를 효율적으로 최적화합니다.
-
Ultralytics YOLO26은 Ray Tune으로 튜닝할 때 다음 기본 하이퍼파라미터를 사용합니다.
매개변수 값 범위 설명 lr0tune.uniform(1e-5, 1e-2)초기 학습률 lrftune.uniform(0.01, 1.0)최종 학습률 계수 momentumtune.uniform(0.7, 0.98)모멘텀 weight_decaytune.uniform(0.0, 0.001)가중치 감쇠 warmup_epochstune.uniform(0.0, 5.0)워밍업 epoch boxtune.uniform(1.0, 20.0)박스 손실 가중치 clstune.uniform(0.1, 4.0)클래스 손실 가중치 cls_pwtune.uniform(0.0, 1.0)클래스 가중치 조정 값 dfltune.uniform(0.4, 12.0)박스 거리 손실 가중치 hsv_htune.uniform(0.0, 0.1)색조 증강 범위 translatetune.uniform(0.0, 0.9)이동 증강 범위 이러한 하이퍼파라미터는 특정 요구사항에 맞게 맞춤 설정할 수 있습니다. 전체 목록과 자세한 내용은 하이퍼파라미터 튜닝 가이드를 참조하세요.
Ultralytics YOLO26 튜닝 과정에 Weights & Biases (W&B)를 통합하려면 다음을 수행하세요.
-
W&B 설치:
pip install wandb wandb login yolo settings wandb=True -
튜너 실행:
from ultralytics import YOLO # YOLO 모델 로드 model = YOLO("yolo26n.pt") # 각 Ray trial은 이 프로젝트에서 자체 W&B run을 생성합니다 result_grid = model.tune(data="coco8.yaml", project="YOLO-Tuning", use_ray=True)
이 설정을 통해 튜닝 프로세스를 모니터링하고, 하이퍼파라미터 구성을 추적하며, W&B에서 결과를 시각화할 수 있습니다.
-
Ray Tune은 하이퍼파라미터 최적화에 여러 이점을 제공합니다.
- 고급 탐색 전략: 효율적인 파라미터 탐색을 위해 베이지안 최적화 및 HyperOpt와 같은 알고리즘을 활용합니다.
- 병렬 처리: 여러 trial의 병렬 실행을 지원하여 튜닝 프로세스의 속도를 크게 높입니다.
- 조기 종료: ASHA와 같은 전략을 사용해 성능이 낮은 trial을 조기에 종료함으로써 컴퓨팅 리소스를 절약합니다.
Ray Tune은
model.tune(use_ray=True)을 통해 Ultralytics YOLO26에 내장되어 있습니다.Ray Tune을 사용해 YOLO26 하이퍼파라미터 튜닝을 위한 사용자 지정 탐색 공간을 정의하려면 다음을 수행하세요.
from ray import tune from ultralytics import YOLO model = YOLO("yolo26n.pt") search_space = {"lr0": tune.uniform(1e-5, 1e-2), "momentum": tune.uniform(0.7, 0.98)} result_grid = model.tune(data="coco8.yaml", space=search_space, use_ray=True)이렇게 하면 튜닝 프로세스 중 탐색할 초기 학습률 및 모멘텀과 같은 하이퍼파라미터의 범위를 사용자 지정할 수 있습니다. 고급 구성은 사용자 지정 탐색 공간 예제 섹션을 참조하세요.
댓글40
질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.
supriamir
Hi, I finish the hyperparameter tune, how to use the best parameter in best_hyperparameters.ymal for training?
Currently i manually use the manually copy the htperparameter.
model.train( data=str(dataset_yaml), epochs=epochs, imgsz=imgsz, batch=batch, project=project, name=f"fold_{k}", workers=0, patience=100, exist_ok=True, cache=False, device=0,
lr0= 0.00254, lrf= 0.02718, momentum= 0.83225, weight_decay= 0.001, warmup_epochs= 2.22741, warmup_momentum= 0.72834, box= 8.86345, cls= 0.52365, dfl= 0.45493, hsv_h= 0.01544, hsv_s= 0.44438, hsv_v= 0.37867, degrees= 0.01115, translate= 0.10045, scale= 0.33157, shear= 0.0075, perspective= 6.0e-05, flipud= 0.00882, fliplr= 0.34916, bgr= 9.0e-05, mosaic= 0.63841, mixup= 0.00099, cutmix= 0.00361, copy_paste= 0.00051, close_mosaic= 6, )
Glenn JocherUltralyticsYes — you can load
best_hyperparameters.yamland unpack it directly intomodel.train()instead of copying values by hand; see the Ray Tune integration guide and feel free to keep follow-ups here in Discussions so the Ultralytics team can see them.from pathlib import Path import yaml from ultralytics import YOLO model = YOLO("yolo26n.pt") hyp_path = Path("runs/detect/tune/best_hyperparameters.yaml") with hyp_path.open() as f: hyp = yaml.safe_load(f) model.train( data=str(dataset_yaml), epochs=epochs, imgsz=imgsz, batch=batch, project=project, name=f"fold_{k}", workers=0, patience=100, exist_ok=True, cache=False, device=0, **hyp, )1
Emeyer87
Hello,
I've noticed that every Iteration with use_ray = True is downloading yolo11n.pt. I'm attempting to use this on an existing instance segmentation model I built but wanted to ensure the tuning is running against the model I've assigned, and not a fresh Detection model.
from ultralytics import YOLO from ray import tune
model_path = r"C:/Users/Me/Downloads/NashvilleSegmentation.pt" data_path = r"C:/Users/Me/Downloads/dataset/data.yaml" model=YOLO(model_path)
search_space = { "degrees": tune.uniform(0.0, 12.0) }
results = model.tune( data=data_path, epochs=20, # keep it tiny iterations=20, # exactly one trial optimizer="AdamW", space=search_space, device=0, seed=0, workers=2, amp=True, batch=16, patience=12, plots=False, save=False, project="test_tune", name="degrees_tune_01", lr0=0.00114, use_ray=True, gpu_per_trial=1
)
Emeyer87
Disregard...completely misunderstood what tuning was actually doing.
Glenn JocherUltralyticsGlad it’s sorted—quick tip: to tune your existing segmentation model, load your .pt first (model = YOLO("path/to/your.pt")) and then run model.tune(..., use_ray=True); Ray trials will reuse that same model/task—verify in the logs that task=segment.
Fatima-khanjar
Subject: Questions Regarding Using Ray Tune for YOLOv11 Hyperparameter Tuning
Hello!
I hope this message finds you well.
#hyperparameter tuning using tune() from ray import tune from ray.tune import ResultGrid from ray.tune.examples.mnist_pytorch import train_mnist from ultralytics import YOLO import os import torch import matplotlib.pyplot as plt # Define a YOLO model model = YOLO("yolo11s.pt").to('cuda') tune_dir = 'ray_results' os.makedirs(tune_dir, exist_ok=True) # Tune hyperparameters using ray tune result_grid = model.tune( data= "data.yaml", epochs=10, iterations=10, batch = 16, device = 0, workers=0, use_ray=True, gpu_per_trial =1, name = "tuning", project = tune_dir ) Now, load the results after the tuning experiment is finished exp_name = "tuning" experiment_path = f"{tune_dir}/{exp_name}" # Get the name of the experiment print(f"Loading results from {experiment_path}...") restored_tuner = tune.Tuner.restore(experiment_path, trainable=train_mnist) result_grid = restored_tuner.get_results() # Basic Experiment-Level Analysis: Check for errors if result_grid.errors: print("One or more trials failed!") else: print("No errors!") # Basic Trial-Level Analysis: Print configurations and last reported metrics for each trial for i, result in enumerate(result_grid): print(f"Trial #{i}: Configuration: {result.config}, Last Reported Metrics: {result.metrics}") # Plotting the Entire History of Reported Metrics for a Trial # Assuming "mean_accuracy" is part of the metrics for i, result in enumerate(result_grid): plt.plot( result.metrics_dataframe["training_iteration"], result.metrics_dataframe["mean_accuracy"], # Modify this depending on your metrics label=f"Trial {i}", ) plt.xlabel("Training Iterations") plt.ylabel("Mean Accuracy") plt.legend() plt.show()
#hyperparameter tuning using tuner.fit() import os from ray import tune from ray.tune import ResultGrid from ray.tune.examples.mnist_pytorch import train_mnist from ray.tune import Result from pathlib import Path tune_dir = Path("ray_results").resolve().as_uri() exp_name = "tune_analyzing_results" tuner = tune.Tuner( trainable=train_mnist, param_space={ "lr": tune.uniform(0.001, 0.1), "momentum": tune.uniform(0.1, 0.9), }, run_config=tune.RunConfig( name=exp_name, stop={"training_iteration": 100}, checkpoint_config=tune.CheckpointConfig( checkpoint_score_attribute="mean_accuracy", num_to_keep = 5, ), storage_path=tune_dir, ), tune_config=tune.TuneConfig(mode="max", metric="mean_accuracy", num_samples=3), ) result_grid: ResultGrid = tuner.fit() experiment_path = os.path.join(tune_dir, exp_name) print(f"Loading results from {experiment_path}...") restored_tuner = tune.Tuner.restore(experiment_path, trainable=train_mnist) result_grid = restored_tuner.get_results() # Check if there have been errors if result_grid.errors: print("One of the trials failed!") else: print("No errors!") num_results = len(result_grid) print("Number of results:", num_results) # Iterate over results for i, result in enumerate(result_grid): if result.error: print(f"Trial #{i} had an error:", result.error) continue print( f"Trial #{i} finished successfully with a mean accuracy metric of:", result.metrics["mean_accuracy"] ) results_df = result_grid.get_dataframe() results_df[["training_iteration", "mean_accuracy"]] print("Shortest training time:", results_df["time_total_s"].min()) print("Longest training time:", results_df["time_total_s"].max()) best_result_df = result_grid.get_dataframe( filter_metric="mean_accuracy", filter_mode="max" ) best_result_df[["training_iteration", "mean_accuracy"]] # Get the result with the maximum test set `mean_accuracy` best_result: Result = result_grid.get_best_result() # Get the result with the minimum `mean_accuracy` worst_performing_result: Result = result_grid.get_best_result( metric="mean_accuracy", mode="min" ) best_result.config best_result.path # Get the last Checkpoint associated with the best-performing trial best_result.checkpoint # Get the last reported set of metrics best_result.metrics result_df = best_result.metrics_dataframe result_df[["training_iteration", "mean_accuracy", "time_total_s"]] best_result.metrics_dataframe.plot("training_iteration", "mean_accuracy") ax = None for result in result_grid: label = f"lr={result.config['lr']:.3f}, momentum={result.config['momentum']}" if ax is None: ax = result.metrics_dataframe.plot("training_iteration", "mean_accuracy", label=label) else: result.metrics_dataframe.plot("training_iteration", "mean_accuracy", ax=ax, label=label) ax.set_title("Mean Accuracy vs. Training Iteration for All Trials") ax.set_ylabel("Mean Test Accuracy")
I have been following your guide on using Ray Tune for hyperparameter tuning with YOLOv11. I was able to run the experiment using the use_ray=True argument, and it worked successfully—thank you for the helpful explanation!
However, I still have a few questions and points of confusion:
-
Naming the Trials: How can I change or customize the names of the individual trials when using model.tune(..., use_ray=True)? Right now, the trials are auto-named, and I’d like more meaningful names to help keep track of different configurations.
-
Retrieving the Best Hyperparameters: After the tuning process is complete, I would like to extract the best hyperparameter configuration to reuse it for future training. I noticed in other examples (e.g., train_mnist) that you use tuner.fit() to retrieve and analyze results, including the best configuration. So my question is: when using model.tune() directly (as in the case of YOLOv11), is there a method to extract the best hyperparameters without using tuner.fit()? Or is it necessary to re-structure the experiment using tune.Tuner to get access to that kind of detailed analysis?
-
Using tune.Tuner() with YOLOv11: In your other examples, the tuning process is managed using tune.Tuner(...), but I’m not sure how to apply this approach to YOLOv11, since there’s no explicit trainable function like train_mnist. Should we always use model.tune() for YOLO models, or is there a way to integrate YOLOv11 into a Tuner workflow for more advanced customization and analysis?
Thank you so much for your time and support! I would really appreciate any clarification or guidance on these points.
Best regards,
Glenn JocherUltralytics@Fatima-khanjar Thank you for your detailed questions about Ray Tune integration with YOLO11!
-
Naming Trials: Currently, the high-level
model.tune()API doesn't provide direct control over individual trial naming. Ray Tune automatically generates these names. You can use thenameparameter to name the overall experiment (as you've done with "tuning"), but individual trial names remain auto-generated. -
Retrieving Best Hyperparameters: When using
model.tune()with Ray Tune, the best hyperparameters are automatically saved toruns/[task]/tune/best_hyperparameters.yaml. This file contains the optimal configuration and can be loaded for future use. You can also examinetune_results.csvfor all trial results. -
Using tune.Tuner(): While possible, creating a custom trainable function for YOLO with the low-level Ray Tune API requires more work. You'd need to wrap the YOLO training process in a function that configures and trains the model while reporting metrics to Ray Tune. For most users, the high-level
model.tune()API is recommended as it handles this integration automatically.
For more advanced customization, you might consider extending the Ray Tune integration in Ultralytics by referring to the source code in the
ultralytics/utils/tuner.pyfile.-
Fatima-khanjar
Hello! Thank you for your clarification. I will continue using model.tune() and use the following line to retrieve the best hyperparameters, since the best_hyperparameters.yaml file wasn’t automatically saved in the output directory of the Ray tuning:
best_config = analysis.get_best_config(metric="metrics/mAP50(B)",mode="max")`I have a question: I read that Optuna uses the TPE (Tree-structured Parzen Estimator) search algorithm, which is more powerful than the default search algorithms in Ray Tune. Since Ray Tune provides scalability and distributed tuning, is it possible to combine both—using Optuna’s TPE algorithm with Ray Tune while still calling model.tune()? If so, how can I integrate them?
I also have another question that’s unrelated. I noticed that YOLOv11 comes in different versions, from n to xl. I understand that the choice depends on the dataset size and the task complexity. But what are the actual criteria used to determine the complexity of a task?
best regrads,
Glenn JocherUltralytics@Fatima-khanjar
Regarding using TPE with Ray Tune - yes, it's possible! Ray Tune already supports TPE through the HyperOpt integration. You can use it by installing the HyperOpt package and specifying the search algorithm:
pip install hyperopt from ray.tune.search.hyperopt import HyperOptSearch from ray.tune.search import ConcurrencyLimiter hyperopt_search = HyperOptSearch(metric="metrics/mAP50(B)", mode="max") limited_search = ConcurrencyLimiter(hyperopt_search, max_concurrent=4) # Then in your model.tune() call model.tune( data="data.yaml", search_alg=limited_search, use_ray=True, # other parameters )For your question about YOLO11 model size selection, the criteria typically include:
- Computational resources: Larger models (l, x, xl) require more GPU memory and processing power
- Dataset complexity: More complex datasets with small/numerous objects benefit from larger models
- Inference speed requirements: Smaller models (n, s) offer faster inference for real-time applications
- Accuracy needs: Larger models generally provide higher accuracy at the cost of speed
You can check the performance trade-offs in the Ultralytics documentation to make an informed decision based on your specific constraints.
1Fatima-khanjar(수정됨)
Hello, I hope this message finds you well.
I followed your instructions to integrate Ray Tune with the TPE algorithm using HyperOpt:
hyperopt_search = HyperOptSearch(metric="metrics/mAP50(B)", mode="max") limited_search = ConcurrencyLimiter(hyperopt_search, max_concurrent=1)Then, I used the following code to tune hyperparameters with Ray Tune:
tuning_results = model.tune( data="data.yaml", epochs=50, # Number of epochs for each tuning iteration iterations=100, # Total number of tuning iterations batch=16, device=0, workers=0, grace_period=30, search_alg=limited_search, use_ray=True, gpu_per_trial=1, project=tune_dir )However, I encountered a syntax error: SyntaxError: 'search_alg' is not a valid YOLO argument. Could you please advise me on how to fix this?
I have another question regarding the output directory of Ray Tune. It shows that inside the runs folder, there are subfolders named train (equal to the number of iterations) and a tune folder that contains subdirectories also equal to the number of iterations.
My question is: should I focus on the train directories? Why are they generated, and what's their purpose?
Also, if I want to monitor the overall progress of the fine-tuning process — for example, in genetic tuning, we usually look at a graph of the fitness score vs. iteration — where should I look for that kind of visualization or information?
best regards,
Glenn JocherUltralytics(수정됨)@Fatima-khanjar
Regarding your issues with HyperOptSearch and Ray Tune integration:
-
The
search_algargument is passed throughmodel.tune(use_ray=True). It defaults to"optuna"(TPE) and accepts either a string (such as"optuna","hyperopt","bohb"or"random") or a Ray Tune searcher instance like yourHyperOptSearch, so you do not need to modifyultralytics/utils/tuner.py. -
About the directory structure:
- The
traindirectories (train1, train2, etc.) contain individual training runs for each trial with different hyperparameter sets - The
tunedirectory contains the aggregated results of all trials and should be your primary focus
- The
-
For monitoring progress:
- Check
tune/tune_results.csvfor all trial results - Look for
tune/best_fitness.pngwhich shows fitness score progression over iterations tune/best_hyperparameters.yamlcontains the optimal configuration found
- Check
The plots in the
tunedirectory (especiallytune_scatter_plots.pngif available) provide valuable visualizations of the hyperparameter search space and how different parameters affected model performance.-
-
Fatima-khanjar
Hello!
I hope this message finds you well.I'm trying to use Ray Tune for hyperparameter optimization with the following code:
results = model.tune( data="data.yaml", epochs=30, iterations=150, batch=16, optimizer="AdamW", plots=False, save=False, val=False, device=0, workers=8, use_ray=True, project="ray_results" )However, I'm getting a path-related error that I can't figure out:
FileNotFoundError: [WinError 3] The system cannot find the path specified...It seems to be related to the length of the path Ray is trying to create. Do you know how I can fix this?
Also, I have a question. I came across Ray Tune while working with Genetic Algorithms, and I was wondering: would you recommend using Ray Tune or Genetic Algorithms for hyperparameter optimization? Are they similar in how they work, or are there major differences between them? What advantages does Ray Tune offer over Genetic Algorithms?
Thank you for your help!
Fatima-khanjar
Hello Community!!
Just following up on my own post — I managed to solve the issue on Windows 11.
Here’s what worked for me:
- Opened gpedit.msc as Administrator
- Navigated to: Computer Configuration > Administrative Templates > System > Filesystem
- Enabled the setting “Enable Win32 long paths"
After doing this, the problem was resolved.
Posting this in case it helps someone else!
Glenn JocherUltralytics@Fatima-khanjar Thank you for sharing your solution to the Windows path length issue! This is helpful information that could benefit other users experiencing similar problems.
Regarding your question about Ray Tune versus Genetic Algorithms: They're different approaches to hyperparameter optimization. Ray Tune offers several advantages including:
- Multiple search strategies beyond genetic algorithms (Bayesian optimization, grid search, random search)
- Built-in parallel execution that efficiently utilizes available resources
- Early stopping via ASHA scheduler to terminate underperforming trials
- Distributed computing capabilities for scaling across multiple machines
Ultralytics actually supports both approaches - the internal tuner uses genetic algorithms focusing on mutation, while the Ray Tune integration provides more advanced search strategies and better parallelization. Ray Tune is generally recommended for more complex search spaces and when you have multiple GPUs available.
1
wisrovi
como lo combino con MLFlow?
wisrovi
tambien necesito:
model.add_callback("on_train_start", self.on_train_start) model.add_callback("on_train_end", self.on_train_end)
pero dichas funciones no se disparan
wisrovi
agradezco mucho sus valiosas aportaciones, de verdad que es una funcionalidad increible y magnifica
Glenn JocherUltralytics@wisrovi to integrate MLFlow with Ultralytics YOLO hyperparameter tuning, you'll need to create a custom Ray Tune reporter that logs metrics to MLFlow. While we don't have native MLFlow integration like Weights & Biases, you can implement it by adding MLFlow logging callbacks to your tuning script. The Ray Tune documentation provides guidance on MLFlow integration that you can adapt for YOLO workflows.
NegroAmigo
Which versions of YOLO are supported by Ray Tune? I have project with YOLOv8, will it be suitable to use with Ray Tune?
Glenn JocherUltralytics@NegroAmigo yes, YOLOv8 fully supports Ray Tune integration for hyperparameter tuning. You can use the same
model.tune()method shown in our Ray Tune integration guide by simply loading your YOLOv8 model (YOLO('yolov8n.pt')). The tuning process works identically across supported YOLO versions. For implementation details, see the Ultralytics Ray Tune documentation.
alifazeli00
Why is there no mention of beta 2(Adamw) in ultralithic documents?
Glenn JocherUltralytics@alifazeli00 the documentation currently focuses on the default hyperparameters and their tuning ranges. If you're looking for specific details on beta2 for AdamW, it might not be explicitly covered. For more information on hyperparameter tuning, you can explore the Ray Tune documentation linked in the guide.
alifazeli00
thank you, It has been mentioned that momentum is essentially beta1. Is this the same for beta2?
Glenn JocherUltralyticsBeta2 is not explicitly mentioned in the documentation as it typically defaults to 0.999 in AdamW, which is a common standard setting. For specific adjustments, you may need to modify the optimizer settings directly in your training script.
1
sirtris
Hi, you mention that the
.tune()function integrates well with wandb. Are there any plans to make it work with mlflow as well? When I try to use it now no model metric, parameters or artifacts, etc. are logged. It would also be nice to have one hyperparameter sweep as a parent run and the individual runs as child runs of that parent run. Best,
Glenn JocherUltralytics@sirtris currently, there are no plans to integrate the
.tune()function with MLflow, but we appreciate your feedback and will consider it for future updates.sirtris
Could you point me to some resources so I could maybe look into it doing it myself?
Glenn JocherUltralyticsFor resources on integrating MLflow with Ray Tune, I recommend checking the Ray Tune documentation for any updates or community contributions. This might provide insights into logging metrics and managing runs with MLflow.
sachmatkris
unfortunately that is not the issue because the results are exactly the same for different learning rates - impossible.
On Fri, 27 Sept 2024 at 19:06, Glenn Jocher @.***> wrote:
@sachmatkris https://github.com/sachmatkris it seems like the issue might be with the search space configuration. Ensure that the hyperparameters have enough variability and that the dataset path is correctly set. If the problem persists, consider adjusting the search space or reviewing the dataset configuration. For more details, you can refer to the Ray Tune documentation https://docs.ultralytics.com/integrations/ray-tune/.
— Reply to this email directly, view it on GitHub https://github.com/orgs/ultralytics/discussions/16505#discussioncomment-10777716, or unsubscribe https://github.com/notifications/unsubscribe-auth/A3WH6HFTKYE2WLTJVGR6HWTZYV7A5AVCNFSM6AAAAABO5HD4QCVHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTANZXG43TCNQ . You are receiving this because you were mentioned.Message ID: @.*** com>
Glenn JocherUltralytics@sachmatkris if you're seeing identical results for different learning rates, it might be worth checking the hyperparameter search space and ensuring the dataset configuration is correct. Adjusting these settings could help resolve the issue. For further guidance, please refer to the Ray Tune documentation.
sachmatkris
I found out the issue was setting device = 0 in the model.tune() and specifying absolute path for the .data.yaml, which is not the same what YOLO does when started from within an opened folder on VScode.
sachmatkris(수정됨)
@sachmatkris it seems like you've identified the issue with the device setting and path specification. If you need further assistance, feel free to ask!
Another issue I have is using the following call all of my experiments with ray_tune return the same metrics:
search_space = { 'lr0': tune.loguniform(1e-5, 1e-1), 'momentum': tune.uniform(0.6, 0.95), }result_grid = model.tune(data = 'C:/Users/Kristijonas/Desktop/Mokslo šaknys karčios/AI/Projects/masinu_numeriai/formated_dataset_new/data.yaml', imgsz = 1280, space = search_space, batch = 16, epochs = 50, patience = 5, use_ray = True, iterations = 20, device='cuda' )e.g.
Glenn JocherUltralytics@sachmatkris it seems like the issue might be with the search space configuration. Ensure that the hyperparameters have enough variability and that the dataset path is correctly set. If the problem persists, consider adjusting the search space or reviewing the dataset configuration. For more details, you can refer to the Ray Tune documentation.