

# SageMaker トレーニングジョブでの Nova 2.0 の教師ありファインチューニング (SFT)
<a name="nova-sft-2-smtj"></a>

## 前提条件
<a name="nova-model-training-jobs-prerequisites2"></a>

トレーニングジョブを始める前に、以下の要件を確認してください。
+ トレーニングジョブの入力データと出力を格納する Amazon S3 バケット。両方に 1 つのバケットを使用することも、データタイプごとに個別のバケットを使用することもできます。トレーニング用の他のすべてのリソースを作成する AWS リージョンと同じ場所にバケットがあることを確認します。詳細については、「[汎用バケットの作成](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)」を参照してください。
+ トレーニングジョブを実行するアクセス許可がある IAM ロール。必ず IAM ポリシーを `AmazonSageMakerFullAccess` にアタッチしてください。詳細については、「[SageMaker AI 実行ロールの使用方法](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html)」を参照してください。
+ Amazon Nova の基本レシピについては、「[Amazon Nova レシピの取得](nova-model-recipes.md#nova-model-get-recipes)」を参照してください。

## SFT とは?
<a name="nova-2-what-is-sft"></a>

教師ありファインチューニング (SFT) は、ラベル付き入出力ペアを使用して言語モデルをトレーニングします。このモデルは、プロンプトとレスポンスで構成されるデモンストレーションの例から学習し、特定のタスク、指示、または望ましい動作に合わせて機能を改善します。

SFT がユースケースに適しているかどうかを判断するには、 [教師ありファインチューニング (SFT)](nova-fine-tune.md) を参照してください。

## トレーニングジョブを開始する
<a name="nova-2-starting-training"></a>

### データの準備
<a name="nova-2-data-preparation"></a>

SFT トレーニングデータを準備するためのデータ形式、サポートされている機能、制約、およびベストプラクティスについては、[Amazon Nova 2 での SFT のデータの準備](nova-data-prep-sft-2.md) を参照してください。

### データのアップロード
<a name="nova-2-uploading-data"></a>

データセットは、SageMaker トレーニングジョブがアクセスできるバケットにアップロードする必要があります。必要な許可の設定の詳細については、「[前提条件](https://docs.aws.amazon.com/sagemaker/latest/dg/nova-model-general-prerequisites.html)」を参照してください。

### ハイパーパラメータの選択とレシピの更新
<a name="nova-2-selecting-hyperparameters"></a>

Nova 2.0 のセットアップは、Nova 1.0 のセットアップとほぼ同じです。入力データが S3 にアップロードされたら、GitHub のファインチューニングフォルダにある [SageMaker HyperPod Recipes](https://github.com/aws/sagemaker-hyperpod-recipes/tree/main/recipes_collection/recipes/fine-tuning/nova) のレシピを使用します。Nova 2.0 Lite では、ユースケースに基づいて更新できる主要なハイパーパラメータの一部を以下に示します。以下は、Nova 2.0 Lite SFT PEFT レシピの例です。コンテナ画像 URI の場合、`708977205387.dkr.ecr.us-east-1.amazonaws.com/nova-fine-tune-repo:SM-TJ-SFT-V2-latest` を使用して SFT ファインチューニングジョブを実行します。

**入力例**

```
run:  
  name: {peft_recipe_job_name}  
  model_type: amazon.nova-2-lite-v1:0:256k  
  model_name_or_path: {peft_model_name_or_path}  
  data_s3_path: {train_dataset_s3_path} # SageMaker HyperPod (SMHP) only and not compatible with SageMaker Training jobs. Note replace my-bucket-name with your real bucket name for SMHP job  
  replicas: 4                      # Number of compute instances for training, allowed values are 4, 8, 16, 32  
  output_s3_path: ""               # Output artifact path (Hyperpod job-specific; not compatible with standard SageMaker Training jobs). Note replace my-bucket-name with your real bucket name for SMHP job  
  
training_config:  
  max_steps: 10                   # Maximum training steps. Minimal is 4.  
  save_steps: 10                      # How many training steps the checkpoint will be saved. Should be less than or equal to max_steps  
  save_top_k: 1                    # Keep top K best checkpoints. Note supported only for SageMaker HyperPod jobs. Minimal is 1.  
  max_length: 32768                # Sequence length (options: 8192, 16384, 32768 [default], 65536)  
  global_batch_size: 32            # Global batch size (options: 32, 64, 128)  
  reasoning_enabled: true          # If data has reasoningContent, set to true; otherwise False  
  
  lr_scheduler:  
    warmup_steps: 15               # Learning rate warmup steps. Recommend 15% of max_steps  
    min_lr: 1e-6                   # Minimum learning rate, must be between 0.0 and 1.0  
  
  optim_config:                    # Optimizer settings  
    lr: 1e-5                       # Learning rate, must be between 0.0 and 1.0  
    weight_decay: 0.0              # L2 regularization strength, must be between 0.0 and 1.0  
    adam_beta1: 0.9                # Exponential decay rate for first-moment estimates, must be between 0.0 and 1.0  
    adam_beta2: 0.95               # Exponential decay rate for second-moment estimates, must be between 0.0 and 1.0  
  
  peft:                            # Parameter-efficient fine-tuning (LoRA)  
    peft_scheme: "lora"            # Enable LoRA for PEFT  
    lora_tuning:  
      alpha: 64                    # Scaling factor for LoRA weights ( options: 32, 64, 96, 128, 160, 192),  
      lora_plus_lr_ratio: 64.0
```

レシピには、Nova 1.0 とほぼ同じハイパーパラメータも含まれています。注目すべきハイパーパラメータは次のとおりです。
+ `max_steps` – ジョブを実行するステップの数。通常、1 つのエポック (データセット全体で 1 回実行) の場合、ステップ数 = データサンプル数/グローバルバッチサイズ。ステップ数が多く、グローバルバッチサイズが小さいほど、ジョブの実行に時間がかかります。
+ `reasoning_enabled` – データセットの推論モードを制御します。オプション:
  + `true`: 推論モードを有効にします (高推論に相当)
  + `false`: 推論モードを無効にします

  注: SFT の場合、推論の労力レベルをきめ細かく制御することはできません。`reasoning_enabled: true` を設定すると、完全な推論機能が有効になります。
+ `peft.peft_scheme` – これを「lora」に設定すると、PEFT ベースのファインチューニングが有効になります。null (引用符なし) に設定すると、フルランクのファインチューニングが有効になります。

### トレーニングジョブの開始
<a name="nova-2-start-job"></a>

```
from sagemaker.pytorch import PyTorch  
  
# define OutputDataConfig path  
if default_prefix:  
    output_path = f"s3://{bucket_name}/{default_prefix}/{sm_training_job_name}"  
else:  
    output_path = f"s3://{bucket_name}/{sm_training_job_name}"  

output_kms_key = "<KMS key arn to encrypt trained model in Amazon-owned S3 bucket>" # optional, leave blank for Amazon managed encryption
  
recipe_overrides = {  
    "run": {  
        "replicas": instance_count,  # Required  
        "output_s3_path": output_path  
    },  
}  
  
estimator = PyTorch(  
    output_path=output_path,  
    base_job_name=sm_training_job_name,  
    role=role,  
    disable_profiler=True,  
    debugger_hook_config=False,  
    instance_count=instance_count,  
    instance_type=instance_type,  
    training_recipe=training_recipe,  
    recipe_overrides=recipe_overrides,  
    max_run=432000,  
    sagemaker_session=sagemaker_session,  
    image_uri=image_uri,
    output_kms_key=output_kms_key,
    tags=[  
        {'Key': 'model_name_or_path', 'Value': model_name_or_path},  
    ]  
)  
  
print(f"\nsm_training_job_name:\n{sm_training_job_name}\n")  
print(f"output_path:\n{output_path}")
```

```
from sagemaker.inputs import TrainingInput  
  
train_input = TrainingInput(  
    s3_data=train_dataset_s3_path,  
    distribution="FullyReplicated",  
    s3_data_type="Converse",  
)  
  
estimator.fit(inputs={"validation": val_input}, wait=False)
```

**注記**  
検証データセットの受け渡しは、Nova 2.0 Lite の教師ありファインチューニングではサポートされていません。

ジョブを開始するには:
+ データセットパスとハイパーパラメータを使用してレシピを更新します
+ ノートブックで指定されたセルを実行してトレーニングジョブを送信します

ノートブックがジョブの送信を処理し、ステータスの追跡を行います。