> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 최적화 엔진 설정하기

Weights & Biases Sweeps에서 사용할 최적화 엔진을 선택하세요. 랜덤, 그리드 또는 베이지안 탐색에는 기본 제공 Weights & Biases 엔진을 사용하고, Optuna 또는 Ax의 검색 알고리즘과 맞춤형 옵션이 필요하다면 해당 엔진을 사용하세요.

엔진, 스케줄러, 스윕 에이전트는 다음과 같이 서로 연동하여 작동합니다.

| 컴포넌트 | 역할 |
| - | - |
| 최적화 엔진 | 하이퍼파라미터 설정을 제안하며, 검색 전략에 따라 run 결과를 바탕으로 검색 방향을 결정합니다. |
| 스윕 스케줄러 | 엔진에 설정을 요청하여 Weights & Biases에 제출하고, run 결과를 다시 엔진에 전달합니다. |
| 스윕 에이전트 | Weights & Biases에서 부여된 설정을 조회하고 트레이닝 코드를 실행합니다. |

이 페이지에서는 사용자 환경에서 실행되는 스케줄러에 엔진을 설정하는 방법을 설명합니다. 전체 YAML 예시는 [스윕 스케줄러 예시](https://docs.coreweave.com/ko/products/wandb/sweeps/define-sweep-configuration.md#sweep-scheduler-examples)를 참조하세요.

## 엔진 선택

필요한 검색 방법과 맞춤 설정 옵션에 따라 엔진을 선택하세요.

| 엔진 | 설명 |
| - | - |
| Weights & Biases (기본 제공) | 스윕 설정 키로 구성하는 랜덤, 그리드 또는 베이지안 탐색을 제공합니다. |
| [Optuna](https://optuna.org/) | 샘플러와 프루너를 설정할 수 있는 오픈 소스 하이퍼파라미터 최적화 프레임워크입니다. |
| [Ax](https://ax.dev/) | 생성 전략과 중지 전략을 설정할 수 있는 적응형 실험용 오픈 소스 플랫폼입니다. |

Optuna 또는 Ax를 사용하면 다음 작업을 할 수 있습니다.

* [여러 목표를 정의](#define-multiple-objectives)하여 둘 이상의 메트릭을 최적화합니다.
* [맞춤형 스윕 수준 중지 함수를 정의](#stop-the-sweep)하여 스케줄러가 새 run 제안을 중지하는 시점을 제어합니다.

Optuna를 사용하면 [조건부 검색 공간을 정의](#define-a-conditional-search-space)하여 시도 내 이전 선택에 따라 매개변수를 선택할 수도 있습니다.

## 의존성 설치

사용하는 엔진에 맞는 추가 의존성을 포함하여 Weights & Biases Python SDK 버전 0.31.0 이상을 설치하세요. 설치 명령어는 스케줄러를 실행하는 환경에서 실행해야 합니다.

> [tab] Weights & Biases
>
> Python 3.10 이상을 사용하세요. 스케줄러 환경에 `sweeps>=0.2.0`이 포함되도록 `sweeps` extra를 지정하여 SDK를 설치하세요.
>
> ```bash theme={"system"}
> pip install "wandb[sweeps]>=0.31.0"
> ```

> [tab] Optuna
>
> Python 3.10 이상을 사용하세요. 스케줄러 환경에 `optuna>=4.0.0`이 포함되도록 `optuna` extra를 지정하여 SDK를 설치하세요.
>
> ```bash theme={"system"}
> pip install "wandb[optuna]>=0.31.0"
> ```
>
> 이 페이지의 OptunaHub Terminator 예시를 사용하려면 `optunahub`도 함께 설치하세요.
>
> ```bash theme={"system"}
> pip install optunahub
> ```

> [tab] Ax
>
> Python 3.11 이상을 사용하세요. 스케줄러 환경에 `ax-platform>=1.3.1`이 포함되도록 `ax` extra를 지정하여 SDK를 설치하세요.
>
> ```bash theme={"system"}
> pip install "wandb[ax]>=0.31.0"
> ```

## 최적화 설정

엔진에 사용할 검색 전략, 목표, 검색 공간을 설정하세요. 기본 제공 Weights & Biases 엔진은 스윕 설정을 사용합니다. Optuna나 Ax를 사용하는 경우에는 Optuna study 또는 Ax client를 설정하는 Python 함수를 제공할 수 있습니다.

### 검색 전략 설정하기

`scheduler.engine`을 `wandb`, `optuna` 또는 `ax`로 설정하세요.

Optuna와 Ax에서는 맞춤형 옵티마이저 함수를 반드시 지정할 필요가 없습니다. `scheduler.engine` 값만 바꾸면 엔진을 전환할 수 있으며, 스윕 설정에 정의된 검색 공간과 목표를 그대로 사용할 수 있습니다. 여기에는 `metrics`로 정의한 여러 목표도 포함됩니다.

맞춤형 옵티마이저 함수를 사용하려면 `scheduler.source`에 Python 파일 이름을, `scheduler.optimizer`에 함수 이름을 설정하세요. Optuna에서는 `scheduler.search_space`로 맞춤형 검색 공간을 정의할 수도 있습니다.

> [tab] Weights & Biases
>
> 스윕 설정으로 기본 제공 Weights & Biases 엔진을 설정하세요.
>
> `method`를 `random`, `grid`, `bayes` 중 하나로 설정하세요. 엔진은 `method`, `metric`, `parameters`를 바탕으로 스윕 run에 사용할 설정을 선택합니다.
>
> 예를 들어, 기본 제공 Weights & Biases 엔진으로 베이지안 탐색을 설정하려면 다음과 같이 하세요.
>
> ```yaml title="sweep.yaml" theme={"system"}
> program: train.py
> method: bayes
> metric:
>   name: validation_loss
>   goal: minimize
> parameters:
>   learning_rate:
>     min: 0.0001
>     max: 0.01
>   batch_size:
>     values: [16, 32, 64]
> scheduler:
>   engine: wandb
> ```
>
> 각 검색 방법에 대한 자세한 내용은 [검색 방법](https://docs.coreweave.com/ko/products/wandb/sweeps/sweep-config-keys.md#method)을 참조하세요.

> [tab] Optuna
>
> 옵티마이저를 사용자 지정하려면 `SweepInfo` 인수 하나를 허용하고 Optuna `Study`를 반환하는 함수를 정의하세요.
>
> 예를 들어, 다음과 같은 스윕 설정이 있다고 가정해 보겠습니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> program: train.py
>
> # W&B 스윕 스키마에 필요한 항목이지만, 검색 전략은
> # Optuna 스케줄러가 제어합니다.
> method: random
>
> metric:
>   name: val_loss
>   goal: minimize
>
> parameters:
>   n_estimators:
>     min: 20
>     max: 200
>   max_depth:
>     min: 2
>     max: 20
>   min_samples_split:
>     min: 0.01
>     max: 0.5
>
> # terminator가 먼저 수렴을 감지하지 못하더라도
> # run이 최대 100개에 도달하면 중지합니다.
> run_cap: 100
>
> scheduler:
>   engine: optuna
>   source: optimizer.py
>   optimizer: create_optimizer
> ```
>
> `optimizer.py`에서 TPE 샘플러를 사용하는 study를 생성한 다음, Terminator의 중지 함수와 함께 반환하세요.
>
> ```python title="optimizer.py" theme={"system"}
> import optuna
> import optunahub
>
> terminator_module = optunahub.load_module("callbacks/terminator")
>
> EMMREvaluator = terminator_module.EMMREvaluator
> MedianErrorEvaluator = terminator_module.MedianErrorEvaluator
> Terminator = terminator_module.Terminator
>
>
> def create_optimizer(sweep_info):
>     study = optuna.create_study(
>         direction="minimize",
>         sampler=optuna.samplers.TPESampler(seed=42),
>     )
>
>     improvement_evaluator = EMMREvaluator()
>     error_evaluator = MedianErrorEvaluator(improvement_evaluator)
>
>     terminator = Terminator(
>         improvement_evaluator=improvement_evaluator,
>         error_evaluator=error_evaluator,
>         min_n_trials=20,
>     )
>
>     return study, terminator.should_terminate
> ```
>
> 앞의 예시에서는 Optuna 인테그레이션의 두 가지 구성 요소를 설정합니다.
>
> * 하이퍼파라미터 설정을 제안하는 `TPESampler`
>
> * 더 이상 개선될 가능성이 낮을 때 스윕을 중지하는 [OptunaHub Terminator](https://hub.optuna.org/callbacks/terminator/)
>
> > [!NOTE]
> >
> > 옵티마이저 함수에서 `study.optimize()`를 호출하지 마세요. 스케줄러는 Optuna의 `ask()` 및 `tell()` 메서드를 사용해 시도를 요청하고 결과를 보고합니다. 이 인테그레이션에서는 `Study.optimize()` callback 인터페이스를 제공하지 않습니다.

> [tab] Ax
>
> 옵티마이저를 사용자 지정하려면 `SweepInfo` 인수 하나를 받아 Ax `Client`를 반환하는 함수를 정의하세요.
>
> Ax 도우미 함수를 임포트하면 스윕 설정을 바탕으로 클라이언트의 검색 공간과 목표를 설정할 수 있습니다.
>
> | 도우미 함수 | 설명 |
> | - | - |
> | `sweep_config_to_search_space(config)` | `parameters`를 `Client.configure_experiment(parameters=...)`에서 허용하는 매개변수 설정으로 변환합니다. |
> | `configure_sweep_objective(client, config)` | `metric` 또는 `metrics`를 바탕으로 최적화를 설정합니다. 하이픈처럼 Ax의 표현식 파서가 잘못 해석할 수 있는 문자가 메트릭 이름에 포함되어 있어도 이름을 그대로 유지합니다. 이러한 이름에는 `Client.configure_optimization()` 대신 이 도우미를 사용하는 것이 좋습니다. |
>
> 목표 이름이나 방향이 일치하지 않으면 스케줄러가 시작될 때 검증에 실패합니다.
>
> 예를 들어 다음 함수는 Ax 클라이언트를 생성한 후 `sweep_info.config`를 바탕으로 설정합니다.
>
> ```python title="optimizer.py" theme={"system"}
> from ax.api.client import Client
> from wandb.sdk.sweeps.scheduler.ax import (
>     configure_sweep_objective,
>     sweep_config_to_search_space,
> )
>
> def create_optimizer(sweep_info):
>     client = Client()
>     client.configure_experiment(
>         parameters=sweep_config_to_search_space(sweep_info.config)
>     )
>     configure_sweep_objective(client, sweep_info.config)
>     return client
> ```
>
> `sweep.yaml`에서 `scheduler.source`를 `optimizer.py`로, `scheduler.optimizer`를 `create_optimizer`로 설정하세요.
>
> ```yaml title="sweep.yaml" theme={"system"}
> program: train.py
> method: custom
> metric:
>   name: validation_loss
>   goal: minimize
> parameters:
>   learning_rate:
>     min: 0.0001
>     max: 0.01
>   batch_size:
>     values: [16, 32, 64]
> scheduler:
>   engine: ax
>   source: optimizer.py
>   optimizer: create_optimizer
> ```

개별 run 수준 및 스윕 수준의 중지 옵션은 [중지 설정](#configure-stopping)을 참조하세요.

### 여러 목표 정의하기

Optuna 또는 Ax를 사용하는 경우 [`metrics`](https://docs.coreweave.com/ko/products/wandb/sweeps/sweep-config-keys#metrics)(복수형)를 사용하여 여러 목표를 정의할 수 있습니다.

`wandb sweep`으로 스윕을 생성하면 Weights & Biases가 스윕 설정을 저장합니다. 스케줄러는 시작될 때 이 설정을 조회한 후 `SweepInfo` 객체에 담아 맞춤형 옵티마이저 함수에 전달합니다.

저장된 스윕 설정에 액세스하려면 `sweep_info.config`를 사용하세요.

> [!NOTE]
>
> 기본 제공 Weights & Biases 엔진은 `metric`으로 정의하는 단일 목표만 지원합니다.

여러 목표를 사용할 때 맞춤형 옵티마이저 함수가 꼭 필요하지는 않습니다. 다음 예시는 맞춤형 옵티마이저 함수를 제공할 때 목표를 설정하는 방법을 보여줍니다.

> [tab] Optuna
>
> Optuna로 다중 목표 스윕을 구성하려면 `metrics` 목록에 각 목표를 정의하세요. 그런 다음 `wandb.sdk.sweeps.scheduler.optuna`의 `sweep_directions()` 도우미 함수를 사용해 각 목표를 동일한 순서의 Optuna study 방향으로 변환하세요.
>
> 예를 들어, 다음 스윕은 검증 손실을 최소화하고 정확도를 최대화합니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> name: optuna-multi-objective
> program: train.py
>
> scheduler:
>   engine: optuna
>   source: optimizer.py
>   optimizer: create_optimizer
>
> metrics:
>   - name: validation_loss
>     goal: minimize
>   - name: accuracy
>     goal: maximize
>
> parameters:
>   learning_rate:
>     min: 0.0001
>     max: 0.01
>   batch_size:
>     values: [16, 32, 64]
> ```
>
> 다음 데모 스크립트는 제안된 `learning_rate` 및 `batch_size` 값을 읽고, 두 개의 합성 목적 함수 값을 계산한 다음 run에 로깅합니다. 최종적으로 기록된 값은 run summary에 표시되며, 스케줄러는 여기에서 이 값을 조회할 수 있습니다.
>
> ```python title="train.py" theme={"system"}
> import math
> import wandb
>
> with wandb.init() as run:
>     learning_rate = run.config["learning_rate"]
>     batch_size = run.config["batch_size"]
>
>     # 이 계산을 실제 모델 학습 및 평가 코드로 바꾸세요.
>     validation_loss = (
>         abs(math.log10(learning_rate) + 3)
>         + 16 / batch_size
>     )
>     accuracy = min(
>         1.0,
>         0.8 - abs(math.log10(learning_rate) + 2.5) * 0.05 + batch_size / 1000,
>     )
>
>     run.log(
>         {
>             "validation_loss": validation_loss,
>             "accuracy": accuracy,
>         }
>     )
> ```
>
> `optimizer.py` 파일에서 Optuna study를 생성할 때 `sweep_info.config`에 저장된 스윕 설정을 `sweep_directions()`에 전달하세요.
>
> ```python title="optimizer.py" theme={"system"}
> import optuna
> from wandb.sdk.sweeps.scheduler.optuna import sweep_directions
>
> def create_optimizer(sweep_info):
>     return optuna.create_study(
>         directions=sweep_directions(sweep_info.config),
>     )
> ```
>
> 이렇게 생성된 study는 `validation_loss`를 최소화하고 `accuracy`를 최대화합니다.

> [tab] Ax
>
> Ax로 다중 목표 스윕을 실행하려면 `wandb.sdk.sweeps.scheduler.ax`의 `configure_sweep_objective()` 헬퍼 함수를 사용해 `metrics`에 있는 각 항목의 이름과 최적화 방향을 클라이언트에 설정하세요.
>
> 예를 들어, 다음 스윕은 검증 손실을 최소화하면서 정확도를 최대화합니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> name: ax-multi-objective
> program: train.py
>
> scheduler:
>   engine: ax
>   source: optimizer.py
>   optimizer: create_optimizer
>
> metrics:
>   - name: validation_loss
>     goal: minimize
>   - name: accuracy
>     goal: maximize
>
> parameters:
>   learning_rate:
>     min: 0.0001
>     max: 0.01
>   batch_size:
>     values: [16, 32, 64]
> ```
>
> 다음 데모 스크립트는 제안된 `learning_rate` 및 `batch_size` 값을 읽어 두 개의 합성 목적 값을 계산한 다음, 이를 run에 로깅합니다. 최종적으로 기록된 값은 run summary에 표시되며, 스케줄러는 여기에서 해당 값을 조회할 수 있습니다.
>
> ```python title="train.py" theme={"system"}
> import math
> import wandb
>
> with wandb.init() as run:
>     learning_rate = run.config["learning_rate"]
>     batch_size = run.config["batch_size"]
>
>     # 이 계산을 실제 모델 학습 및 평가 코드로 대체하세요.
>     validation_loss = (
>         abs(math.log10(learning_rate) + 3)
>         + 16 / batch_size
>     )
>     accuracy = min(
>         1.0,
>         0.8 - abs(math.log10(learning_rate) + 2.5) * 0.05 + batch_size / 1000,
>     )
>
>     run.log(
>         {
>             "validation_loss": validation_loss,
>             "accuracy": accuracy,
>         }
>     )
> ```
>
> `optimizer.py`에서 Ax 클라이언트를 생성한 다음, 저장된 스윕 설정을 바탕으로 검색 공간과 목표를 설정하세요. `sweep_config_to_search_space()`로 `parameters`를 Ax 매개변수 정의로 변환하고, `configure_sweep_objective()`로 `metrics`에 정의된 목표를 설정하세요.
>
> ```python title="optimizer.py" theme={"system"}
> from ax.api.client import Client
> from wandb.sdk.sweeps.scheduler.ax import (
>     configure_sweep_objective,
>     sweep_config_to_search_space,
> )
>
>
> def create_optimizer(sweep_info):
>     client = Client()
>     client.configure_experiment(
>         parameters=sweep_config_to_search_space(sweep_info.config)
>     )
>     configure_sweep_objective(client, sweep_info.config)
>     return client
> ```
>
> 이 예제에서 `configure_sweep_objective()`는 `validation_loss`를 최소화하고 `accuracy`를 최대화하도록 Ax를 설정합니다.

### 조건부 검색 공간 정의하기

> [!NOTE]
>
> `scheduler.search_space`는 Optuna 엔진에서만 지원됩니다.

Optuna를 사용하는 경우 `scheduler.search_space`로 Python에서 조건부 매개변수를 정의할 수 있습니다. 예를 들어 모델 유형마다 서로 다른 하이퍼파라미터를 정의하거나, 앞에서 선택한 값을 기반으로 매개변수 개수를 다르게 지정할 수 있습니다.

`scheduler.search_space`에는 `scheduler.source`로 지정한 파일에 있는 함수의 이름을 설정하세요. 스케줄러는 Optuna 시도(trial)를 이 함수에 전달하고, 함수가 반환한 딕셔너리를 run 구성으로 사용합니다.

> [!TIP]
>
> 고정 검색 공간을 사용하려면 스윕 설정에 `parameters`를 정의하세요.

`scheduler.search_space`를 설정하면 스케줄러는 최상위 `parameters` 정의를 무시합니다. run에 전달할 매개변수는 모두 Python 함수 안에 정의하세요.

예를 들어 다음과 같은 스윕 설정이 있다고 가정해 보겠습니다.

```yaml title="sweep.yaml" theme={"system"}
metric:
  name: validation_loss
  goal: minimize

parameters: {}

scheduler:
  engine: optuna
  source: search.py
  search_space: define_search_space
```

각 시도마다 스케줄러는 `define_search_space(trial)`을 호출하고, 반환된 딕셔너리를 run 구성으로 사용합니다.

```python title="search.py" theme={"system"}
def define_search_space(trial):
    model = trial.suggest_categorical("model", ["linear", "transformer"])

    config = {
        "model": model,
        "learning_rate": trial.suggest_float(
            "learning_rate", 1e-5, 1e-2, log=True
        ),
    }

    if model == "transformer":
        config["num_layers"] = trial.suggest_int("num_layers", 2, 12)
        config["num_heads"] = trial.suggest_categorical(
            "num_heads", [4, 8, 16]
        )
    else:
        config["regularization"] = trial.suggest_float(
            "regularization", 0.0, 1.0
        )

    return config
```

모든 run은 `model`과 `learning_rate`를 받습니다. `model="transformer"`인 run은 여기에 더해 `num_layers`와 `num_heads`도 받고, `model="linear"`인 run은 대신 `regularization`을 받습니다.

## 중지 설정

중지는 개별 run 단위로 적용하거나 스윕 전체에 적용할 수 있습니다. 개별 run 조기 중지는 유용한 결과를 낼 가능성이 낮은 run을 종료합니다. 스윕 수준 중지는 특정 조건이 충족되면 스케줄러가 더 이상 새 run을 제안하지 않도록 합니다.

### 개별 run 중지

run의 진행 상황을 평가하려면 트레이닝 전반에 걸쳐 목표 메트릭의 중간값을 로깅하세요. run 중지 여부를 결정하는 방식은 엔진마다 다릅니다.

> [!NOTE]
>
> 최상위 `early_terminate` 키는 기본 제공 Weights & Biases 엔진에만 적용됩니다. Optuna나 Ax를 사용하는 경우에는 해당 엔진 자체의 조기 중지 메커니즘을 설정하세요.

> [tab] Weights & Biases
>
> 중간 결과를 기반으로 조기 중단을 적용하는 하이퍼파라미터 최적화에는 [Hyperband](https://arxiv.org/abs/1603.06560)를 사용하세요.
>
> `early_terminate.type`을 `hyperband`로 설정하고, `min_iter`로 최소 반복 횟수를 지정하세요.
>
> 예를 들어, 다음 스윕 설정은 Hyperband를 사용하여 최소 3회 반복 후 조기 중단을 수행합니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> program: train.py
> method: bayes
> metric:
>   name: validation_loss
>   goal: minimize
> parameters:
>   learning_rate:
>     min: 0.0001
>     max: 0.01
>   batch_size:
>     values: [16, 32, 64]
> early_terminate:
>   type: hyperband
>   min_iter: 3
> scheduler:
>   engine: wandb
> ```
>
> 설정 옵션은 [`early_terminate`](https://docs.coreweave.com/ko/products/wandb/sweeps/sweep-config-keys#early_terminate)를 참조하세요.

> [tab] Optuna
>
> Optuna에서 [pruner](https://optuna.readthedocs.io/en/stable/reference/pruners.html)는 중간 결과를 기반으로 시도를 조기에 중단할지 여부를 결정합니다.
>
> 예를 들어, 다음과 같은 스윕 설정에 Optuna로 조기 중단을 적용하려 한다고 가정해 보겠습니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> name: optuna-pruning-demo
> program: train.py
> method: grid
> run_cap: 2
>
> metric:
>   name: loss
>   goal: minimize
>
> parameters:
>   loss:
>     values: [0.2, 0.9]
>
> scheduler:
>   engine: optuna
>   source: optimizer.py
>   optimizer: make_study
> ```
>
> `optimizer.py`에서 그리드 샘플러와 임계값 프루너를 사용하는 스터디를 생성하세요. 이 프루너는 중간 손실이 0.5를 초과하는 시도를 중지하도록 권장합니다.
>
> ```python title="optimizer.py" theme={"system"}
> import optuna
>
> def make_study(sweep_info):
>     """Create a study with a grid sampler and a threshold pruner."""
>     return optuna.create_study(
>         direction="minimize",
>         sampler=optuna.samplers.GridSampler(
>             {"loss": [0.2, 0.9]},
>         ),
>         # 중간 손실이 0.5를 초과하는 run을 모두 중지합니다.
>         pruner=optuna.pruners.ThresholdPruner(
>             upper=0.5,
>             n_warmup_steps=0,
>         ),
>     )
> ```
>
> 스케줄러가 중간 결과를 pruner에 전달할 수 있도록 `train.py`에서 step마다 설정한 손실을 로깅하세요.
>
> ```python title="train.py" theme={"system"}
> import time
> import wandb
>
> with wandb.init() as run:
>     loss = run.config["loss"]
>
>     for step in range(30):
>         run.log({"loss": loss}, step=step)
>         time.sleep(1)
> ```
>
> > [!NOTE]
> >
> > 다중 목표(multi-objective) 스터디에서는 Optuna 가지치기(pruning)를 사용할 수 없습니다.

> [tab] Ax
>
> Ax에서 개별 run에 대한 조기 중지를 활성화하려면 `client.set_early_stopping_strategy()`를 호출하여 조기 중지 전략을 설정한 다음 클라이언트를 반환하세요.
>
> 예를 들어 다음과 같은 스윕 설정이 있고, 여기에 Ax로 조기 중지를 적용하려 한다고 가정해 보겠습니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> name: ax-run-stopping-demo
> program: train.py
>
> # 스윕 스키마상 필수 항목입니다. 매개변수 생성은 Ax가 제어합니다.
> method: random
> run_cap: 2
> metric:
>   name: loss
>   goal: minimize
> parameters:
>   difficulty:
>     values: [0.1, 1.0]
> scheduler:
>   engine: ax
>   source: optimizer.py
>   optimizer: make_client
> ```
>
> `optimizer.py`에서 검색 공간, 목표, 백분위수 기반 조기 중지 전략을 사용해 클라이언트를 설정하세요. 목표가 `loss` 최소화이므로, 이 전략은 손실 값이 더 높은 run을 성능이 낮은 run으로 파악합니다.
>
> ```python title="optimizer.py" theme={"system"}
> from ax.api.client import Client
> from ax.early_stopping.strategies import PercentileEarlyStoppingStrategy
>
> from wandb.sdk.sweeps.scheduler.ax import (
>     configure_sweep_objective,
>     sweep_config_to_search_space,
> )
>
> def make_client(sweep_info):
>     client = Client()
>     client.configure_experiment(
>         parameters=sweep_config_to_search_space(sweep_info.config),
>     )
>     configure_sweep_objective(client, sweep_info.config)
>
>     client.set_early_stopping_strategy(
>         PercentileEarlyStoppingStrategy(
>             percentile_threshold=50.0,
>             min_progression=2,
>             min_curves=2,
>             seconds_between_polls=0,
>             normalize_progressions=False,
>         )
>     )
>
>     return client
> ```
>
> `train.py`에서 `difficulty`를 기반으로 합성 손실을 계산하고 각 step마다 로깅하세요. 이 중간 값을 바탕으로 Ax가 run 간의 진행 상황을 비교할 수 있습니다.
>
> ```python title="train.py" theme={"system"}
> import time
> import wandb
>
> with wandb.init() as run:
>     difficulty = run.config["difficulty"]
>
>     for step in range(30):
>         # difficulty=1.0인 run은 계속해서 성능이 더 낮습니다.
>         loss = difficulty + 1.0 / (step + 1)
>
>         run.log(
>             {"loss": loss},
>             step=step,
>         )
>
>         # 스케줄러가 폴링할 수 있도록 run을 충분히 오래 실행 상태로 유지합니다.
>         time.sleep(1)
> ```
>
> 스케줄러가 두 run의 중간 결과를 모두 수집할 수 있도록 스윕 에이전트 두 개를 동시에 실행하세요. Ax가 run 중지를 권장하면 스케줄러가 Weights & Biases에 해당 run의 중지를 요청합니다.

### 스윕 중지

스윕 수준 중지는 스케줄러가 새 run 제안을 멈추는 시점을 제어합니다. `run_cap`을 사용하면 어떤 엔진에서든 run 수의 고정 최댓값을 설정할 수 있습니다. Optuna나 Ax를 사용하는 경우에는 현재 최적화 상태를 평가하는 중지 함수를 반환할 수도 있습니다.

> [!NOTE]
>
> 다음 예시에서는 스케줄러가 검색 전략을 제어하므로 `method: random`은 무시됩니다. 하지만 Weights & Biases 스윕 스키마에서 `method`는 필수 항목입니다.

중지 조건이 충족되는 시점에 스케줄러에 이미 대기열에 추가되었거나 실행 중인 run이 있을 수 있습니다. 이러한 run은 스케줄러가 새 run 제안을 멈춘 후에도 계속 실행될 수 있습니다.

> [tab] Optuna
>
> 스윕 단위 중지를 활성화하려면 `scheduler.optimizer`에 지정한 최적화 함수가 Optuna study와 중지 함수를 튜플로 반환해야 합니다:
>
> ```python theme={"system"}
> (study, terminator_callback)
> ```
>
> 스케줄러는 결과를 처리한 후 현재 study를 중지 함수에 전달합니다. 이 함수가 `True`를 반환하면 스윕이 중지되고, `False`를 반환하면 계속해서 새 run을 제안합니다.
>
> 예를 들어, 다음 스윕 설정은 `x`를 검색하고, 스윕을 run 20개로 제한하며, Optuna 스케줄러가 `optimizer.py` 파일의 `make_study()`를 호출하도록 지정합니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> name: optuna-sweep-stopping-demo
> program: train.py
> method: random
> run_cap: 20
>
> metric:
>   name: loss
>   goal: minimize
>
> parameters:
>   x:
>     min: 0
>     max: 10
>
> scheduler:
>   engine: optuna
>   source: optimizer.py
>   optimizer: make_study
> ```
>
> 이 예제에서 `run_cap`은 중지 함수가 먼저 스윕을 종료하지 않을 경우를 대비한 대체 한도 역할을 합니다.
>
> 다음으로 Optuna study와 중지 함수를 정의하세요. `make_study()`는 시드가 지정된 무작위 샘플러를 설정하고, `stop_after_three_completed_trials()`와 함께 study를 반환합니다.
>
> ```python title="optimizer.py" theme={"system"}
> import optuna
>
>
> def stop_after_three_completed_trials(study: optuna.Study) -> bool:
>     """Stop the sweep after three completed trials."""
>     completed = sum(
>         trial.state == optuna.trial.TrialState.COMPLETE
>         for trial in study.trials
>     )
>
>     return completed >= 3
>
>
> def make_study(sweep_info):
>     study = optuna.create_study(
>         direction="minimize",
>         sampler=optuna.samplers.RandomSampler(seed=42),
>     )
>
>     return study, stop_after_three_completed_trials
> ```
>
> 중지 함수는 성공적으로 완료된 시도만 셉니다. 세 번째 시도가 완료되면 `True`를 반환하여 스케줄러가 더 이상 설정을 제안하지 않도록 합니다. 실패했거나, 가지치기되었거나, 실행 중인 시도는 개수에 포함되지 않습니다.
>
> 마지막으로, 각 스윕 run이 평가할 목적 함수를 정의합니다. 트레이닝 스크립트는 제안된 `x` 값을 조회하고 손실을 계산한 다음, 그 손실을 Weights & Biases에 로깅합니다.
>
> ```python title="train.py" theme={"system"}
> import wandb
>
> with wandb.init() as run:
>     x = run.config["x"]
>     loss = (x - 3) ** 2
>
>     run.log({"loss": loss})
> ```
>
> 각 run이 종료되면 스케줄러는 해당 run에서 로깅된 손실 값을 Optuna study에 전달합니다. 시도가 세 번 완료되면 중지 함수가 `True`를 반환하고, 스케줄러는 더 이상 새 run을 제안하지 않습니다. 이미 대기열에 추가되었거나 실행 중인 run은 그대로 진행되어 종료될 수 있습니다.

> [tab] Ax
>
> 스윕 단위 중지를 활성화하려면 `scheduler.optimizer`에 지정한 함수가 Ax 클라이언트와 중지 함수로 구성된 튜플을 반환하도록 하세요.
>
> ```python theme={"system"}
> (client, terminator)
> ```
>
> 다음 설정은 스윕을 최대 20개의 run으로 제한합니다. 목표 지표가 더 이상 개선되지 않으면 중지 함수가 그 전에 스윕을 종료할 수 있습니다.
>
> ```yaml title="sweep.yaml" theme={"system"}
> name: ax-sweep-stopping-example
> program: train.py
> method: random
> run_cap: 20
> metric:
>   name: loss
>   goal: minimize
> parameters:
>   x:
>     min: 0.0
>     max: 1.0
> scheduler:
>   engine: ax
>   source: optimizer.py
>   optimizer: make_client
> ```
>
> `optimizer.py`에서 Ax 클라이언트와 중지 함수를 생성하세요. 이 예제에서는 `ImprovementGlobalStoppingStrategy`를 사용해 최근 개선 폭을 지금까지 관측된 목적 함수 값의 분산 범위와 비교합니다.
>
> ```python title="optimizer.py" theme={"system"}
> from ax.api.client import Client
> from ax.global_stopping.strategies.improvement import (
>     ImprovementGlobalStoppingStrategy,
> )
>
> from wandb.sdk.sweeps.scheduler.ax import (
>     configure_sweep_objective,
>     sweep_config_to_search_space,
> )
>
>
> def make_client(sweep_info):
>     """Create the Ax client and sweep-level stopping callback."""
>
>     client = Client()
>
>     # sweep.yaml의 매개변수를 Ax 검색 공간으로 변환합니다.
>     client.configure_experiment(
>         parameters=sweep_config_to_search_space(sweep_info.config),
>     )
>
>     # Ax가 최소화할 목표로 "loss"를 설정합니다.
>     configure_sweep_objective(client, sweep_info.config)
>
>     client.configure_generation_strategy(
>         method="random_search",
>         initialization_random_seed=7,
>         initialize_with_center=True,
>     )
>
>     stopping_strategy = ImprovementGlobalStoppingStrategy(
>         min_trials=6,
>         window_size=3,
>         improvement_bar=0.01,
>         inactive_when_pending_trials=True,
>     )
>
>     def should_terminate_sweep(client):
>         """Return True when Ax recommends ending the whole sweep."""
>         should_stop, reason = stopping_strategy.should_stop_optimization(
>             experiment=client._experiment,
>         )
>
>         if should_stop:
>             print(f"Ax is stopping the sweep: {reason}")
>
>         return should_stop
>
>     return client, should_terminate_sweep
> ```
>
> 다음 트레이닝 스크립트는 `x=0.5`에서 최솟값을 갖는 합성 목적 함수를 평가합니다. 생성 전략이 이 지점을 가장 먼저 평가하므로 이후의 시도에서는 최적 결과를 더 이상 개선할 수 없습니다.
>
> ```python title="train.py" theme={"system"}
> import time
> import wandb
>
> with wandb.init() as run:
>     x = run.config["x"]
>
>     for step in range(5):
>         loss = (x - 0.5) ** 2 + 1.0 / (step + 1)
>
>         run.log(
>             {"loss": loss},
>             step=step,
>         )
>
>         time.sleep(0.5)
> ```
>
> 이 중지 전략은 완료된 각 run의 최종 목표값만 사용합니다. 스크립트는 트레이닝을 시뮬레이션하기 위해 중간값을 로깅하지만, 이 예제에서는 개별 run에 대한 조기 중지를 설정하지 않습니다.

## 스케줄러 재시작 처리

스윕 스케줄러는 기존 스윕을 대상으로 동작하므로, 새 스윕을 만들지 않고도 스케줄러를 중지했다가 다시 시작할 수 있습니다. 스케줄러는 시작될 때마다 스윕의 기존 run 데이터를 바탕으로 최적화 이력을 재구성한 다음 최적화 루프를 이어서 진행합니다. 저장된 옵티마이저 체크포인트에서 엔진을 복원하지는 않습니다.

스케줄러가 시작되거나 재시작되면 맞춤형 옵티마이저 함수를 호출하여 새 엔진 인스턴스를 생성합니다. 함수가 실행될 때마다 새로운 Optuna study 또는 Ax client를 반환하세요. 별도의 옵티마이저 체크포인트를 로드하거나 이전 스케줄러 프로세스의 엔진 인스턴스를 재사용하지 마세요.

`scheduler.source` 파일을 사용하는 경우, 스케줄러는 시작될 때마다 해당 파일의 현재 내용을 로드합니다. 따라서 재시작하기 전에 파일을 업데이트하여 버그를 수정하거나 맞춤형 `optimizer` 또는 `search_space` 함수를 변경할 수 있습니다. 이러한 변경은 이후 제안에 영향을 줄 수 있으므로, 최적화를 재현해야 한다면 스케줄러 세션마다 사용한 `source` 파일의 버전을 보존하세요.
