

# Nova 1.0 미세 조정
<a name="nova-fine-tune-1"></a>

**참고**  
지시 미세 조정(SFT) 및 직접 선호 최적화를 사용하여 Amazon Nova 1.0 모델 시리즈를 미세 조정할 수 있습니다. Nova 2.0 모델을 미세 조정하려면 [Nova 2.0 미세 조정](https://docs.aws.amazon.com//nova/latest/nova2-userguide/nova-fine-tune-2.html)을 참조하세요.

## 사전 조건
<a name="nova-model-training-jobs-prerequisites"></a>

훈련 작업을 시작하기 전에 다음을 확인하세요.
+ 입력 데이터와 훈련 작업 출력을 저장하는 Amazon S3 버킷. 두 가지 데이터를 하나의 버킷에 함께 저장하거나, 각 데이터 유형을 별도의 버킷에 저장할 수 있습니다. 버킷이 모든 훈련 관련 리소스를 생성하는 AWS 리전과 동일한 리전에 있는지 확인합니다. 자세한 내용은 [범용 버킷 생성](https://docs.aws.amazon.com//AmazonS3/latest/userguide/create-bucket-overview.html)을 참조하세요.
+ 훈련 작업 실행 권한이 있는 IAM 역할. IAM 정책을 `AmazonSageMakerFullAccess`에 연결해야 합니다. 자세한 내용은 [How to use SageMaker AI execution roles](https://docs.aws.amazon.com//sagemaker/latest/dg/sagemaker-roles.html)를 참조하세요.
+ 기본 Amazon Nova 레시피, [Amazon Nova 레시피 가져오기](nova-model-recipes.md#nova-model-get-recipes) 참조.

## 데이터 준비
<a name="nova-model-training-prepare-data"></a>

고품질의 적절한 형식의 데이터를 준비하는 것은 대규모 언어 모델의 미세 조정 프로세스에서 중요한 첫 번째 단계입니다. 전체 순위 또는 저순위 적응(LoRA) 접근 방식을 사용하여 지도 미세 조정(SFT)을 사용하든 직접 선호 최적화(DPO)를 사용하든 상관없이 성공적인 모델 훈련을 보장하려면 데이터가 특정 형식 요구 사항을 준수해야 합니다. 이 섹션에서는 Amazon Nova 모델을 미세 조정하기 위해 데이터세트를 효과적으로 준비하는 데 도움이 되는 필수 데이터 형식, 검증 방법 및 모범 사례를 간략하게 설명합니다.

### 데이터 형식 요구 사항
<a name="nova-model-training-prepare-data-format"></a>

**SFT**

SFT 데이터 형식 요구 사항 - 전체 순위 SFT 및 LoRA SFT 모두에 대해 데이터는 아래 표시된 형식을 따라야 합니다. 이 형식의 예시 및 제약 조건은 [이해 모델 미세 조정을 위한 데이터 준비](https://docs.aws.amazon.com//nova/latest/userguide/fine-tune-prepare-data-understanding.html)를 참조하세요.

SFT 데이터 검증 - 제출 전에 데이터세트 형식을 검증하려면 [Amazon Bedrock 샘플 리포지토리](https://github.com/aws-samples/amazon-bedrock-samples/blob/main/custom-models/bedrock-fine-tuning/nova/understanding/dataset_validation/nova_ft_dataset_validator.py)의 다음 검증 스크립트를 사용하는 것이 좋습니다. 이 검증 도구는 `jsonl` 파일이 필요한 형식 사양을 준수하는지 확인하고 미세 조정 작업을 제출하기 전에 잠재적 문제를 식별하는 데 도움이 됩니다.

**DPO**

DPO 데이터 형식 요구 사항 - 전체 순위 DPO 및 LoRA DPO 모두에 대해 데이터는 아래 표시된 형식을 따라야 합니다. 또한 데이터세트는 SFT와 유사한 형식이어야 합니다. 단, 마지막 턴에는 기본 설정 페어가 있어야 합니다.

DPO 데이터세트 기타 제약 조건 - 데이터세트에 대한 다른 제약 조건은 SFT에 대해 동일합니다. 자세한 내용은 [데이터세트 제약 조건](https://docs.aws.amazon.com//nova/latest/userguide/fine-tune-prepare-data-understanding.html)을 참조하세요. 훈련용 JSONL 파일 하나와 검증용 JSONL 파일 하나가 필요합니다. 검증 세트는 선택 사항입니다.

DPO 데이터세트 권장 사항 - 효과적인 훈련을 위한 최소 1,000개의 기본 설정 페어. 고품질 기본 설정 데이터를 사용하면 더 효율적인 결과를 얻을 수 있습니다.

### 예제
<a name="nova-model-training-prepare-data-example"></a>

**샘플 DPO 데이터 형식**

```
// N-1 turns same as SFT format
{
    "role": "assistant",
    "candidates": [
        {
            "content": [
                {
                    "text": "..."
                } // content list can contain multiple 'text' objects
            ],
            "preferenceLabel": "preferred"
        },
        {
            "content": [
                {
                    "text": "..."
                } // content list can contain multiple 'text' objects
            ],
            "preferenceLabel": "non-preferred"
        }
    ]
}
```

**샘플 DPO 데이터 형식(다중 턴)**

```
{
    "system": [
        {
            "text": "..."
        }
    ],
    "messages":[
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "assistant",
            "candidates": [
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "preferred"
                },
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "non-preferred"
                }
            ]
        }
    ],
}
```

**샘플 DPO 데이터 형식(이미지 포함)**

```
{
    "system": [
        {
            "text": "..."
        }
    ],
    "messages":[
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                },
                {
                    "text": "..."
                },
                {
                    "image": {
                        "format": "jpeg",
                        "source": {
                            "s3Location": {
                                "uri": "s3://your-bucket/your-path/your-image.jpg",
                                "bucketOwner": "your-aws-account-id"
                            }
                        }
                    }
                } // "content" can have multiple "text" and "image" objects.
                 // max image count is 10
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "text": "..."
                }
            ]
        },
        {
            "role": "user",
            "content": [
                {
                    "text": "..."
                },
                {
                    "text": "..."
                },
                {
                    "image": {
                        "format": "jpeg",
                        "source": {
                            "s3Location": {
                                "uri": "s3://your-bucket/your-path/your-image.jpg",
                                "bucketOwner": "your-aws-account-id"
                            }
                        }
                    }
                } // "content" can have multiple "text" and "image" objects.
                 // max image count is 10
            ]
        },
        {
            "role": "assistant",
            "candidates": [
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "preferred"
                },
                {
                    "content": [
                        {
                            "text": "..."
                        }
                    ],
                    "preferenceLabel": "non-preferred"
                }
            ]
        }
    ],
}
```

### 데이터세트 제한
<a name="nova-model-training-prepare-data-limits"></a>

아래 표의 추정치는 설명을 위해 5일의 훈련 기간을 가정하지만 훈련 작업은 기본적으로 1일의 시간 제한이 적용됩니다. 더 긴 훈련 워크로드를 수용하려면 훈련 시간 제한을 최대 28일로 늘리는 것이 좋습니다. 제한 증가를 요청하려면 [Requesting a quota increase](https://docs.aws.amazon.com//servicequotas/latest/userguide/request-quota-increase.html)를 참조하세요.

**SFT 데이터세트 제한**

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/nova/latest/userguide/nova-fine-tune-1.html)

DPO 데이터세트 제한

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/nova/latest/userguide/nova-fine-tune-1.html)

에포크 수 또는 레코드의 컨텍스트 길이를 줄이면 더 많은 레코드를 제공할 수 있습니다.

## 전체 순위 SFT 및 LoRA PEFT 구성
<a name="nova-model-training-jobs-recipe-config"></a>

이 섹션에서는 전체 순위 지도 미세 조정(SFT) 및 저순위 적응 파라미터 효율적 미세 조정(LoRA PEFT) 접근 방식 모두에 대한 레시피 구성 관련 지침을 다룹니다. 이러한 레시피 파일은 모델 사용자 지정 작업의 블루프린트 역할을 하여 모델이 데이터로부터 학습하는 방식을 결정하는 훈련 파라미터, 하이퍼파라미터 및 기타 중요한 설정을 지정할 수 있습니다. 하이퍼파라미터를 조정하려면 [하이퍼파라미터 선택](https://docs.aws.amazon.com//nova/latest/userguide/customize-fine-tune-hyperparameters.html) 섹션의 지침을 따릅니다.

### 미세 조정 구성(전체 순위 SFT 및 LoRA PEFT)
<a name="nova-model-training-jobs-recipe-config-1"></a>

레시피 관점에서 전체 순위 SFT와 LoRA PEFT의 유일한 차이점은 LoRA PEFT 구성입니다. 이 구성은 전체 순위 SFT의 경우 'null'로 설정되고 LoRA PEFT 기반 미세 조정을 사용하는 경우에는 적절한 값으로 설정됩니다. 예제 레시피는 [SageMaker HyperPod 레시피](https://github.com/aws/sagemaker-hyperpod-recipes/tree/main/recipes_collection/recipes) GitHub 리포지토리에서 사용할 수 있습니다. 다음 표에는 도움이 될 수 있는 자세한 구성이 나와 있습니다.

**'실행' 구성** 정보.


|  | 키 | 정의 | Micro | Lite | Pro | 
| --- | --- | --- | --- | --- | --- | 
| 실행 구성 | model\$1type |  사용할 Nova 모델 변형을 지정합니다. 이 필드는 수정하지 마세요.  |  "amazon.nova-micro-v1:0:128k"  |  "amazon.nova-lite-v1:0:300k"  |  "amazon.nova-pro-v1:0:300k"  | 
|  | model\$1name\$1or\$1path |  기본 모델의 경로입니다.  |  "nova-micro/prod"  |  “nova-lite/prod”  |  "nova-pro/prod"  | 
|  | 복제본 |  분산 훈련에 사용할 컴퓨팅 인스턴스의 수입니다.  |  2, 4 또는 8  |  4, 8 또는 16  |  6, 12 또는 24  | 

**'training\$1config' 구성** 정보.

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/nova/latest/userguide/nova-fine-tune-1.html)

### 미세 조정 특정 구성(DPO)
<a name="nova-model-training-jobs-recipe-config-2"></a>

LoRA PEFT 및 FullRank SFT와 비교한 직접 선호 최적화(DPO)의 유일한 차이점은 dpo\$1cfg 구성 및 허용되는 값입니다. DPO에 대해 특별히 허용되는 예는 아래 표를 참조하세요. 예제 레시피는 [SageMaker HyperPod 레시피](https://github.com/aws/sagemaker-hyperpod-recipes/tree/main/recipes_collection/recipes) GitHub 리포지토리에서 사용할 수 있습니다. 다음 표에는 도움이 될 수 있는 자세한 구성이 나와 있습니다.

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/nova/latest/userguide/nova-fine-tune-1.html)

## SageMaker 훈련 작업에서 사용자 지정된 Nova 모델 실행
<a name="nova-model-training-jobs-notebook"></a>

이 섹션에서는 Jupyter Notebook 환경을 통해 SageMaker 훈련 작업에서 사용자 지정 Nova 모델을 실행하는 방법을 보여줍니다. 훈련 작업을 구성하고 실행하는 전 프로세스를 단계별로 설명하는 전체 예시와 함께, 적절한 컨테이너 이미지 URI 및 인스턴스 구성을 선택할 수 있도록 참조 표도 제공합니다. 이 접근 방식을 사용하면 모델 사용자 지정을 위해 SageMaker AI의 관리형 인프라를 활용하면서 미세 조정 워크플로를 프로그래밍 방식으로 제어할 수 있습니다. 자세한 내용은 [SageMaker AI 예측기를 사용하여 훈련 작업 실행](https://docs.aws.amazon.com//sagemaker/latest/dg/docker-containers-adapt-your-own-private-registry-estimator.html)을 참조하세요.

### 참조 테이블
<a name="nova-model-training-jobs-reference-table"></a>

샘플 노트북을 실행하기 전에 다음 표를 참조하여 적절한 컨테이너 이미지 URI 및 인스턴스 구성을 선택합니다.

**이미지 URI 선택**


| 방법 | 이미지 URI | 
| --- | --- | 
|  SFT 이미지 URI  | 708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-SFT-latest | 
|  DPO 이미지 URI  | 708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-DPO-latest | 

**인스턴스 유형 및 개수 선택**


| 모델 | 미세 조정 작업 유형 | 기법 유형 | 인스턴스 유형 | 권장 인스턴스 수 | 허용된 인스턴스 수 | 
| --- | --- | --- | --- | --- | --- | 
| Amazon Nova Micro | SFT | LoRA | g5.12xlarge, g6.12xlarge, g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  | LoRA\$1전체 순위 | g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  |  | p4d.24xlarge | 2 | 2, 4, 8 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 1 | 1, 2, 4, 8 | 
|  | DPO | LoRA | g5.12xlarge, g6.12xlarge, g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  | LoRA\$1전체 순위 | p4d.24xlarge, p5.48xlarge, p5en.48xlarge | 2 | 2, 4, 8 | 
| Amazon Nova Lite | SFT | LoRA | g5.12xlarge, g6.12xlarge, g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 1 | 1, 4, 8, 16 | 
|  |  | LoRA\$1전체 순위 | p4d.24xlarge | 4 | 4, 8, 16 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 2 | 2, 4, 8, 16 | 
|  | DPO | LoRA | g5.48xlarge, g6.48xlarge | 1 | 1 | 
|  |  | LoRA\$1전체 순위 | p4d.24xlarge, p5.48xlarge, p5en.48xlarge | 4 | 4, 8, 16 | 
| Amazon Nova Pro | SFT | LoRA | p4d.24xlarge | 6 | 6, 12, 24 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 3 | 3, 6, 12, 24 | 
|  |  | LoRA\$1전체 순위 | p5.48xlarge, p5en.48xlarge | 6 | 6, 12, 24 | 
|  | DPO | LoRA | p4d.24xlarge | 6 | 6, 12, 24 | 
|  |  | LoRA\$1전체 순위 | p4d.24xlarge | 12 | 12, 24 | 
|  |  |  | p5.48xlarge, p5en.48xlarge | 4 | 4, 8, 16 | 

### 샘플 노트북
<a name="nova-model-training-jobs-notebook"></a>

다음 샘플 노트북은 훈련 작업을 실행하는 방법을 보여줍니다. SageMaker 훈련 작업을 사용하여 Nova 모델을 사용자 지정하는 방법에 대한 추가 시작하기 노트북은 [Use a SageMaker AI estimator to run a training job](https://docs.aws.amazon.com//sagemaker/latest/dg/docker-containers-adapt-your-own-private-registry-estimator.html)을 참조하세요.

```
# 1. Install dependencies

!pip install sagemaker==2.254.1

# 2. Import dependencies and initialize sagemaker session

import sagemaker,boto3

sm = boto3.client('sagemaker', region_name='us-east-1')
sagemaker_session = sagemaker.session.Session(boto_session=boto3.session.Session(), sagemaker_client=sm)

# 3. Configure your job
# Define the core configuration for launching a SageMaker Training Job. This includes input/output S3 URIs, container image, hardware setup, and other runtime parameters. Update the placeholders below before submitting the job.

job_name = "<Your Job Name>"

input_s3_uri = "<S3 path to input data>"
validation_s3_uri = "<S3 path to validation data>" # optional, leave blank if no validation data

output_s3_uri = "<S3 path to output location>"

image_uri = "<Image URI from documentation>" # you can choose the image for SFT/DPO
instance_type = "ml.p5.48xlarge" # do not change
instance_count = <Integer number of hosts> # change hosts as needed. Refer to documentation for allowed values based on model type.
role_arn = "<IAM Role you want to use to run the job>"
recipe_path = "<Local path to the recipe file>"
output_kms_key = "<KMS key arn to encrypt trained model in Amazon-owned S3 bucket>" # optional, leave blank for Amazon managed encryption

# 4. Launch SageMaker Training Job
# This block sets up and runs the SageMaker training job using the PyTorch estimator. It configures the training image, hardware, input channels, and TensorBoard integration. Validation data is included if provided.

from sagemaker.debugger import TensorBoardOutputConfig
from sagemaker.pytorch import PyTorch
from sagemaker.inputs import TrainingInput

tensorboard_output_config = TensorBoardOutputConfig(
    s3_output_path=output_s3_uri,
)

estimator = PyTorch(
    output_path=output_s3_uri,
    base_job_name=job_name,
    role=role_arn,
    instance_count=instance_count,
    instance_type=instance_type,
    training_recipe=recipe_path,
    sagemaker_session=sagemaker_session,
    image_uri=image_uri,
    tensorboard_output_config=tensorboard_output_config, # Add the setting for using TensorBoard.
    disable_profiler=True,
    debugger_hook_config=False,
    output_kms_key=output_kms_key
)

trainingInput = TrainingInput(
    s3_data=input_s3_uri,
    distribution='FullyReplicated',
    s3_data_type='Converse'
)

if (validation_s3_uri):
    validationInput = TrainingInput(
        s3_data=validation_s3_uri,
        distribution='FullyReplicated',
        s3_data_type='Converse'
    )

    estimator.fit(inputs={"train": trainingInput, "validation": validationInput}) # inputs must be called "train" and "validation", do not change
else:
    estimator.fit(inputs={"train": trainingInput})
```

## 하이퍼파라미터 최적화 지침
<a name="nova-model-hyperparameter"></a>

Nova LLM 모델을 효과적으로 미세 조정하려면 하이퍼파라미터를 신중하게 선택해야 합니다. 이 섹션에서는 기본 레시피 구조와 구성 요소에 대해 설명하지만 특정 사용 사례에 맞게 하이퍼파라미터를 최적화하려면 종종 추가적인 지침이 필요합니다. 하이퍼파라미터 선택, 모범 사례 및 최적화 전략에 대한 포괄적인 권장 사항은 [하이퍼파라미터 선택](https://docs.aws.amazon.com//nova/latest/userguide/customize-fine-tune-hyperparameters.html)을 참조하세요. 이 리소스는 데이터세트 특성 및 훈련 목표에 따라 적절한 학습률, 배치 크기, 훈련 에포크 및 기타 중요 파라미터를 선택하는 방법에 대한 자세한 지침을 제공합니다. 최적의 모델 성능을 얻으려면 레시피 구성을 미세 조정할 때 이 가이드를 참조하는 것이 좋습니다.

에포크, 학습률 및 학습 워밍업 단계의 최소값, 최대값 및 기본값에 대한 자세한 내용은 [이해 모델의 하이퍼파라미터](https://docs.aws.amazon.com//nova/latest/userguide/fine-tune-hyperparameters-understanding-models.html)를 참조하세요.

**일반적인 레시피 수정**

다음은 특정 사용 사례에 따른 몇 가지 일반적인 레시피 조정입니다.
+ **소규모 데이터세트(예시 1,000개 미만)**

  ```
  training_config:
      max_epochs: 2  # More passes through a smaller dataset
  model:
      hidden_dropout: 0.1  # Increase regularization
      weight_decay: 0.01   # Increase regularization
  ```
+ **제한된 컴퓨팅으로 효율성 향상**

  ```
  peft:
      peft_scheme: "lora"
      lora_tuning:
  ```
+ **복잡한 명령 조정**

  ```
  optim:
      lr: 5e-6  # Lower learning rate for more stable learning
      sched:
          warmup_steps: 100  # Longer warmup for stability
  ```