> 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-chu/finetuning-from-last-checkpoint.md). Agents can also search and read this documentation through its [MCP server](https://unsloth.ai/docs/~gitbook/mcp).

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

チェックポイント機能により、ファインチューニングの進捗を保存して一時停止し、後で続行できます。

編集する必要があります `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はどう行いますか？

評価損失が減少しないためにファインチューニング／学習の実行を停止または一時停止したい場合は、学習プロセスを停止する 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", # Early stopping用の保存済みチェックポイントの保存先
        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,  # もっと高く設定することも可能 - どれだけ損失が減少すれば
                                     # 早期停止とみなすかを設定します。たとえば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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
