> ## 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.

> 스윕용 설정 파일을 만드는 방법을 알아보세요.

# 개요

스윕은 하이퍼파라미터 값을 탐색하는 전략과 그 값을 평가하는 코드를 결합한 것입니다. 전략은 모든 옵션을 하나씩 사용해 보는 단순한 방식일 수도 있고, Bayesian Optimization and Hyperband([BOHB](https://arxiv.org/abs/1807.01774))처럼 복잡한 방식일 수도 있습니다.

이 가이드에서는 검색할 하이퍼파라미터, 사용할 검색 전략, 각 run의 평가 방법을 지정하는 스윕 설정을 정의하는 방법을 설명합니다. 새 스윕을 설정하거나 기존 설정을 다른 검색 방법이나 매개변수 공간에 맞게 조정할 때 이 가이드를 참고하세요.

스윕 설정은 [Python 딕셔너리](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) 또는 [YAML](https://yaml.org/) 파일로 정의합니다. 어떤 방식을 사용할지는 스윕을 관리하려는 방식에 따라 달라집니다.

<Note>
  명령줄에서 스윕을 초기화하고 스윕 에이전트를 시작하려면 YAML 파일에 스윕 설정을 정의하세요. Python 스크립트 또는 노트북 안에서 스윕 초기화와 시작을 모두 수행한다면 Python 딕셔너리로 스윕을 정의하세요.
</Note>

다음 섹션에서는 스윕 설정의 형식을 작성하는 방법을 설명합니다. 최상위 스윕 설정 키의 전체 목록은 [Sweep configuration options](/ko/products/wandb/sweeps/sweep-config-keys)을 참조하세요.

<h2 id="basic-structure">
  기본 구조
</h2>

스윕 설정은 YAML 또는 Python 딕셔너리로 정의하며, 키-값 쌍과 중첩 구조로 구성됩니다.

스윕 설정의 최상위 키를 사용하여 스윕 [`name`](/ko/products/wandb/sweeps/sweep-config-keys), 검색할 [`parameters`](/ko/products/wandb/sweeps/sweep-config-keys#parameters), 검색 [`method`](/ko/products/wandb/sweeps/sweep-config-keys#method) 등 스윕 검색의 특성을 정의하세요.

예를 들어, 다음 코드 스니펫은 동일한 스윕 설정을 YAML 파일과 Python 딕셔너리로 각각 정의한 것입니다. 이 스윕 설정에는 `program`, `name`, `method`, `metric`, `parameters`의 다섯 가지 최상위 키가 지정되어 있습니다.

<Tabs>
  <Tab title="CLI">
    명령줄에서 대화형으로 스윕을 관리하려면 YAML 파일에 스윕 설정을 정의하세요.

    ```yaml title="config.yaml" theme={"system"}
    program: train.py
    name: sweepdemo
    method: bayes
    metric:
      goal: minimize
      name: validation_loss
    parameters:
      learning_rate:
        min: 0.0001
        max: 0.1
      batch_size:
        values: [16, 32, 64]
      epochs:
        values: [5, 10, 15]
      optimizer:
        values: ["adam", "sgd"]
    ```
  </Tab>

  <Tab title="Python script or notebook">
    트레이닝 알고리즘을 Python 스크립트나 노트북에서 정의하는 경우 Python 딕셔너리 데이터 구조로 스윕을 정의하세요.

    다음 코드 스니펫은 `sweep_configuration`이라는 변수에 스윕 설정을 저장합니다.

    ```python title="train.py" theme={"system"}
    sweep_configuration = {
        "name": "sweepdemo",
        "method": "bayes",
        "metric": {"goal": "minimize", "name": "validation_loss"},
        "parameters": {
            "learning_rate": {"min": 0.0001, "max": 0.1},
            "batch_size": {"values": [16, 32, 64]},
            "epochs": {"values": [5, 10, 15]},
            "optimizer": {"values": ["adam", "sgd"]},
        },
    }
    ```
  </Tab>
</Tabs>

최상위 `parameters` 키 아래에는 `learning_rate`, `batch_size`, `epochs`, `optimizer` 키가 중첩되어 있습니다. 각 중첩 키에는 하나 이상의 값, 분포, 확률 등을 지정할 수 있습니다. 자세한 내용은 [Sweep configuration options](/ko/products/wandb/sweeps/sweep-config-keys)의 [parameters](/ko/products/wandb/sweeps/sweep-config-keys#parameters) 섹션을 참조하세요.

<h2 id="double-nested-parameters">
  이중 중첩 매개변수
</h2>

관련된 하이퍼파라미터를 하나로 묶으려는 경우나 트레이닝 코드가 중첩된 설정 구조를 요구하는 경우 중첩 매개변수를 사용하세요. 중첩 매개변수를 정의하려면 최상위 매개변수 이름 아래에 `parameters` 키를 하나 더 추가하세요.

다음 예시는 `nested_category_1`, `nested_category_2`, `nested_category_3`라는 중첩 매개변수가 포함된 스윕 설정으로, 각 중첩 매개변수에는 `momentum`과 `weight_decay` 매개변수가 추가로 들어 있습니다. 다음 코드 예시에서는 같은 설정을 YAML 파일과 Python 딕셔너리 두 가지 형식으로 보여 줍니다.

<Tabs>
  <Tab title="CLI">
    ```yaml theme={"system"}
    program: sweep_nest.py
    name: nested_sweep
    method: random
    metric:
      name: loss
      goal: minimize
    parameters:
      optimizer:
        values: ['adam', 'sgd']
      fc_layer_size:
        values: [128, 256, 512]
      dropout:
        values: [0.3, 0.4, 0.5]
      epochs:
        value: 1
      learning_rate:
        distribution: uniform
        min: 0
        max: 0.1
      batch_size:
        distribution: q_log_uniform_values
        q: 8
        min: 32
        max: 256
      nested_category_1:
        parameters:
          momentum:
            distribution: uniform
            min: 0.0
            max: 0.9
          weight_decay:
            values: [0.0001, 0.0005, 0.001]
      nested_category_2:
        parameters:
          momentum:
            distribution: uniform
            min: 0.0
            max: 0.9
          weight_decay:
            values: [0.1, 0.2, 0.3]
      nested_category_3:
        parameters:
          momentum:
            distribution: uniform
            min: 0.5
            max: 0.7
          weight_decay:
            values: [0.2, 0.3, 0.4]
    ```
  </Tab>

  <Tab title="Python script or notebook">
    ```python theme={"system"}
    {
      "program": "sweep_nest.py",
      "name": "nested_sweep",
      "method": "random",
      "metric": {
        "name": "loss",
        "goal": "minimize"
      },
      "parameters": {
        "optimizer": {
          "values": ["adam", "sgd"]
        },
        "fc_layer_size": {
          "values": [128, 256, 512]
        },
        "dropout": {
          "values": [0.3, 0.4, 0.5]
        },
        "epochs": {
          "value": 1
        },
        "learning_rate": {
          "distribution": "uniform",
          "min": 0,
          "max": 0.1
        },
        "batch_size": {
          "distribution": "q_log_uniform_values",
          "q": 8,
          "min": 32,
          "max": 256
        },
        "nested_category_1": {
          "parameters": {
            "momentum": {
              "distribution": "uniform",
              "min": 0.0,
              "max": 0.9
            },
            "weight_decay": {
              "values": [0.0001, 0.0005, 0.001]
            }
          }
        },
        "nested_category_2": {
          "parameters": {
            "momentum": {
              "distribution": "uniform",
              "min": 0.0,
              "max": 0.9
            },
            "weight_decay": {
              "values": [0.1, 0.2, 0.3]
            }
          }
        },
        "nested_category_3": {
          "parameters": {
            "momentum": {
              "distribution": "uniform",
              "min": 0.5,
              "max": 0.7
            },
            "weight_decay": {
              "values": [0.2, 0.3, 0.4]
            }
          }
        }
      }
    }
    ```
  </Tab>
</Tabs>

<Warning>
  스윕 설정에 정의된 중첩 매개변수는 W\&B run 설정에 지정된 키를 덮어씁니다.

  예를 들어, 중첩된 기본값으로 run을 초기화하는 `train.py` 스크립트가 있다고 가정해 보겠습니다.

  ```python theme={"system"}
  def main():
      with  wandb.init(config={"nested_param": {"manual_key": 1}}) as run:
          # 여기에 트레이닝 코드를 작성하세요
  ```

  스윕 설정에서는 최상위 `"parameters"` 키 아래에 중첩 매개변수를 정의합니다.

  ```python theme={"system"}
  sweep_configuration = {
      "method": "grid",
      "metric": {"name": "score", "goal": "minimize"},
      "parameters": {
          "top_level_param": {"value": 0},
          "nested_param": {
              "parameters": {
                  "learning_rate": {"value": 0.01},
                  "double_nested_param": {
                      "parameters": {"x": {"value": 0.9}, "y": {"value": 0.8}}
                  },
              }
          },
      },
  }

  sweep_id = wandb.sweep(sweep=sweep_configuration, project="[PROJECT]")
  wandb.agent(sweep_id, function=main, count=4)
  ```

  스윕 run이 실행되는 동안 `run.config["nested_param"]`에는 스윕 설정에 정의된 하위 트리(`learning_rate` 및 `double_nested_param`)가 반영됩니다. `wandb.init(config=...)`에 정의된 `manual_key`는 포함되지 않습니다.
</Warning>

<h2 id="sweep-configuration-template">
  스윕 설정 템플릿
</h2>

새 스윕 설정을 작성할 때 이 템플릿을 기본 틀로 활용하세요. 이 템플릿에는 가장 일반적인 매개변수 패턴과 조기 종료 패턴이 나와 있습니다. `hyperparameter_name`을 사용할 하이퍼파라미터 이름으로 바꾸고, 대괄호로 묶인 값도 모두 알맞게 바꾸세요.

```yaml title="config.yaml" theme={"system"}
program: [INSERT]
method: [INSERT]
parameters:
  hyperparameter_name0:
    value: 0
  hyperparameter_name1:
    values: [0, 0, 0]
  hyperparameter_name:
    distribution: [INSERT]
    value: [INSERT]
  hyperparameter_name2:
    distribution: [INSERT]
    min: [INSERT]
    max: [INSERT]
    q: [INSERT]
  hyperparameter_name3:
    distribution: [INSERT]
    values:
      - [LIST-OF-VALUES]
      - [LIST-OF-VALUES]
      - [LIST-OF-VALUES]
early_terminate:
  type: hyperband
  s: [INSERT]
  eta: [INSERT]
  max_iter: [INSERT]
command:
- ${Command macro}
- ${Command macro}
- ${Command macro}
- ${Command macro}
```

과학적 표기법으로 숫자 값을 표현하려면 값을 부동 소수점 숫자로 변환하는 YAML `!!float` 연산자를 추가하세요. 예: `min: !!float 1e-5`. 자세한 내용은 [매크로 및 맞춤형 명령 인수 예시](#macro-and-custom-command-arguments-example)를 참조하세요.

<h2 id="sweep-configuration-examples">
  스윕 설정 예시
</h2>

다음 스윕 설정 예시는 일반적인 시나리오를 보여 줍니다. 자신의 트레이닝 스크립트에 맞게 스윕을 조정할 때 참고하세요.

<Tabs>
  <Tab title="CLI">
    ```yaml title="config.yaml" theme={"system"}
    program: train.py
    method: random
    metric:
      goal: minimize
      name: loss
    parameters:
      batch_size:
        distribution: q_log_uniform_values
        max: 256
        min: 32
        q: 8
      dropout:
        values: [0.3, 0.4, 0.5]
      epochs:
        value: 1
      fc_layer_size:
        values: [128, 256, 512]
      learning_rate:
        distribution: uniform
        max: 0.1
        min: 0
      optimizer:
        values: ["adam", "sgd"]
    ```
  </Tab>

  <Tab title="Python script or notebook">
    ```python title="train.py" theme={"system"}
    sweep_config = {
        "method": "random",
        "metric": {"goal": "minimize", "name": "loss"},
        "parameters": {
            "batch_size": {
                "distribution": "q_log_uniform_values",
                "max": 256,
                "min": 32,
                "q": 8,
            },
            "dropout": {"values": [0.3, 0.4, 0.5]},
            "epochs": {"value": 1},
            "fc_layer_size": {"values": [128, 256, 512]},
            "learning_rate": {"distribution": "uniform", "max": 0.1, "min": 0},
            "optimizer": {"values": ["adam", "sgd"]},
        },
    }
    ```
  </Tab>
</Tabs>

<h3 id="bayes-hyperband-example">
  Bayes hyperband 예시
</h3>

다음 예시는 베이지안 탐색과 Hyperband 조기 종료를 결합해 성능이 낮은 run을 조기에 중단하고, 더 유망한 설정에 리소스를 확보해 둡니다.

```yaml theme={"system"}
program: train.py
method: bayes
metric:
  goal: minimize
  name: val_loss
parameters:
  dropout:
    values: [0.15, 0.2, 0.25, 0.3, 0.4]
  hidden_layer_size:
    values: [96, 128, 148]
  layer_1_size:
    values: [10, 12, 14, 16, 18, 20]
  layer_2_size:
    values: [24, 28, 32, 36, 40, 44]
  learn_rate:
    values: [0.001, 0.01, 0.003]
  decay:
    values: [1e-5, 1e-6, 1e-7]
  momentum:
    values: [0.8, 0.9, 0.95]
  epochs:
    value: 27
early_terminate:
  type: hyperband
  s: 2
  eta: 3
  max_iter: 27
```

다음 탭에서는 `early_terminate`에 최소 또는 최대 반복 횟수를 지정하는 방법을 보여줍니다.

<Tabs>
  <Tab title="최소 반복 횟수">
    이 예제의 브래킷은 `[3, 3*eta, 3*eta*eta, 3*eta*eta*eta]`, 즉 `[3, 9, 27, 81]`입니다.

    ```yaml theme={"system"}
    early_terminate:
      type: hyperband
      min_iter: 3
    ```
  </Tab>

  <Tab title="최대 반복 횟수">
    이 예제의 브래킷은 `[27/eta, 27/eta/eta]`, 즉 `[9, 3]`입니다.

    ```yaml theme={"system"}
    early_terminate:
      type: hyperband
      max_iter: 27
      s: 2
    ```
  </Tab>
</Tabs>

<h3 id="macro-and-custom-command-arguments-example">
  매크로 및 맞춤형 명령 인수 예제
</h3>

이 예제에서는 기본 호출보다 더 세밀한 제어가 필요할 때 스윕 에이전트가 각 trial에서 실행할 명령을 구성하는 방법을 보여 줍니다.

더 복잡한 명령줄 인수가 필요하다면 매크로를 사용하여 환경 변수, Python 인터프리터, 추가 인수를 전달할 수 있습니다. [W\&B는 사전 정의된 매크로를 지원하며](/ko/products/wandb/sweeps/sweep-config-keys#command-macros), 스윕 설정에서 지정할 수 있는 맞춤형 명령줄 인수도 지원합니다.

예를 들어 다음 스윕 설정(`sweep.yaml`)은 Python 스크립트(`run.py`)를 실행하는 명령을 정의합니다. 스윕이 실행되면 `${env}`, `${interpreter}`, `${program}` 매크로가 적절한 값으로 대체됩니다.

`--batch_size=${batch_size}`, `--test=True`, `--optimizer=${optimizer}` 인수는 맞춤형 매크로를 사용하여 스윕 설정에 정의된 `batch_size`, `test`, `optimizer` 매개변수의 값을 전달합니다.

```yaml title="sweep.yaml" theme={"system"}
program: run.py
method: random
metric:
  name: validation_loss
parameters:
  learning_rate:
    min: 0.0001
    max: 0.1
command:
  - ${env}
  - ${interpreter}
  - ${program}
  - "--batch_size=${batch_size}"
  - "--optimizer=${optimizer}"
  - "--test=True"
```

그러면 해당 Python 스크립트 `run.py`에서 `argparse` 모듈을 사용해 이 명령줄 인수를 파싱할 수 있습니다.

```python title="run.py" theme={"system"}
# run.py
import wandb
import argparse


def str2bool(v: str) -> bool:
    """Convert a string such as "True" to a boolean, because argparse
    doesn't support boolean arguments by default.
    """
    if isinstance(v, bool):
        return v
    return v.lower() in ('yes', 'true', 't', '1')


parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int)
parser.add_argument('--optimizer', type=str, choices=['adam', 'sgd'], required=True)
parser.add_argument('--test', type=str2bool, default=False)
args = parser.parse_args()

# W&B run 초기화
with wandb.init(project="test-project") as run:
    run.log({'validation_loss': 1})
```

스윕 설정에서 사용할 수 있는 사전 정의 매크로 목록은 [Sweep configuration options](/ko/products/wandb/sweeps/sweep-config-keys)의 [Command macros](/ko/products/wandb/sweeps/sweep-config-keys#command-macros) 섹션을 참조하세요.

<h4 id="boolean-arguments">
  Boolean 인수
</h4>

스윕에서 명령 인수로 boolean 플래그를 전달하는 경우, `argparse`는 기본적으로 boolean 문자열을 해석하지 않으므로 트레이닝 스크립트에서 이를 별도로 처리해야 합니다.

`argparse` 모듈은 기본적으로 boolean 인수를 지원하지 않습니다. boolean 인수를 정의하려면 [`action`](https://docs.python.org/3/library/argparse.html#action) 매개변수를 사용하거나, boolean 값을 나타내는 문자열을 boolean 유형으로 변환하는 맞춤형 함수를 사용하세요.

예를 들어, 다음 코드 스니펫으로 boolean 인수를 정의할 수 있습니다. `ArgumentParser`에 `store_true` 또는 `store_false`를 인수로 전달하세요.

```python theme={"system"}
import wandb
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--test', action='store_true')
args = parser.parse_args()

args.test  # --test를 전달하면 True, 전달하지 않으면 False가 됩니다
```

boolean 값의 문자열 표현을 boolean 유형으로 변환하는 맞춤형 함수를 직접 정의할 수도 있습니다. 예를 들어, 다음 코드 스니펫은 문자열을 boolean 값으로 변환하는 `str2bool` 함수를 정의합니다.

```python theme={"system"}
def str2bool(v: str) -> bool:
  """Convert a string to a boolean. This is required because
  argparse doesn't support boolean arguments by default.
  """
  if isinstance(v, bool):
      return v
  return v.lower() in ('yes', 'true', 't', '1')
```


## Related topics

- [개요](/ko/products/wandb/weave/reference.md)
