> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/jp/ji-ben/finetuning-from-last-checkpoint.md).

# 最後のチェックポイントからファインチューニング

を編集する必要があります `Trainer` まず `save_strategy` および `save_steps`。以下は、50ステップごとにチェックポイントをフォルダに保存します `outputs`.

```python
trainer = SFTTrainer(
    ....
    args = TrainingArguments(
        ....
        output_dir = "outputs",
        save_strategy = "steps",
        save_steps = 50,
    ),
)
```

次に、trainer では次を実行します：

```python
trainer_stats = trainer.train(resume_from_checkpoint = True)
```

これにより、最新のチェックポイントから開始して学習を続行します。

### Wandb 統合

```
# ライブラリをインストール
!pip install wandb --upgrade

# Wandb の設定
!wandb login <token>

import os

os.environ["WANDB_PROJECT"] = "<name>"
os.environ["WANDB_LOG_MODEL"] = "checkpoint"
```

次に `TrainingArguments()` で

```
report_to = "wandb",
logging_steps = 1, # 必要に応じて変更
save_steps = 100 # 必要に応じて変更
run_name = "<name>" # (オプション)
```

モデルを学習するには次を実行します `trainer.train()`; 学習を再開するには次を実行します

```
import wandb
run = wandb.init()
artifact = run.use_artifact('<username>/<Wandb-project-name>/<run-id>', type='model')
artifact_dir = artifact.download()
trainer.train(resume_from_checkpoint=artifact_dir)
```

## :question:早期終了を行うにはどうすればよいですか？

評価損失が減少しないためにファインチューニング／学習の実行を停止または一時停止したい場合は、学習プロセスを停止する early stopping を使用できます。使用するのは `EarlyStoppingCallback`.

いつものように、trainer と評価データセットを設定します。以下は、学習実行を停止するために使用されます。 `eval_loss` （評価損失）が 3 ステップほど経っても減少しない場合。

```python
from trl import SFTConfig, SFTTrainer
trainer = SFTTrainer(
    args = SFTConfig(
        fp16_full_eval = True,
        per_device_eval_batch_size = 2,
        eval_accumulation_steps = 4,
        output_dir = "training_checkpoints", # 早期終了用に保存されるチェックポイントの保存先
        save_strategy = "steps",             # モデルを N ステップごとに保存
        save_steps = 10,                     # モデルを保存するまでのステップ数
        save_total_limit = 3,                # ディスク容量節約のため、保存済みチェックポイントを 3 つだけ保持
        eval_strategy = "steps",             # N ステップごとに評価
        eval_steps = 10,                     # 評価を行うまでのステップ数
        load_best_model_at_end = True,       # early stopping では必須
        metric_for_best_model = "eval_loss", # early stop の基準にしたい指標
        greater_is_better = False,           # eval loss は低いほど良い
    ),
    model = model,
    tokenizer = tokenizer,
    train_dataset = new_dataset["train"],
    eval_dataset = new_dataset["test"],
)
```

次に、カスタマイズも可能なコールバックを追加します：

```python
from transformers import EarlyStoppingCallback
early_stopping_callback = EarlyStoppingCallback(
    early_stopping_patience = 3,     # eval loss が下がらない場合に待つステップ数
                                     # たとえば損失が増加しても、3 ステップ後に減少することがあります
    early_stopping_threshold = 0.0,  # より高く設定することも可能 - どれだけ損失が減少すれば
                                     # early stopping と見なすかを設定します。例えば 0.01 なら、損失が
                                     # 0.02 から 0.01 になった場合に、早期終了すると見なします。
)
trainer.add_callback(early_stopping_callback)
```

次に、通常どおり以下でモデルを学習します `trainer.train() 。`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://unsloth.ai/docs/jp/ji-ben/finetuning-from-last-checkpoint.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
