# DeepSpeed

[DeepSpeed](https://www.deepspeed.ai/)は、数十億パラメータを持つ大規模モデルの分散学習のために、速度とスケーラビリティを重視して設計されたライブラリです。その核となるのは、オプティマイザ状態（ZeRO-1）、勾配（ZeRO-2）、パラメータ（ZeRO-3）をデータ並列プロセス間でシャード化するZero Redundancy Optimizer（ZeRO）です。これによりメモリ使用量が大幅に削減され、数十億パラメータのモデルへの学習スケーリングが可能になります。さらにメモリ効率を引き出すために、ZeRO-Offloadは最適化処理中にCPUリソースを活用することで、GPUの計算負荷とメモリ使用量を削減します。

これらの2つの機能は🤗 Accelerateでサポートされており、🤗 PEFTと組み合わせて使用できます。

## `bitsandbytes`量子化 + LoRAとの互換性

以下は、ファインチューニングにおけるPEFTのLoRA、[`bitsandbytes`](https://github.com/TimDettmers/bitsandbytes)ライブラリ、およびDeepSpeed Zeroステージ間の互換性をまとめた表です。DeepSpeed Zero-1および2は推論時には影響を与えません。ステージ1はオプティマイザの状態をシャーディングし、ステージ2はオプティマイザの状態と勾配をシャーディングするためです。

| DeepSpeedステージ   | 互換性がありますか？ |
|---|---|
| Zero-1 |  🟢 |
| Zero-2   |  🟢 |
| Zero-3  |  🟢 |

DeepSpeed Stage 3 + QLoRA については、以下のセクション [PEFT QLoRA と DeepSpeed ZeRO3 を使用して複数 GPU 上で大規模モデルをファインチューニングする](#use-peft-qlora-and-deepspeed-with-zero3-for-finetuning-large-models-on-multiple-gpus) を参照してください。

これらの観察を確認するために、[Transformers Reinforcement Learning (TRL) library](https://github.com/huggingface/trl)の[公式サンプルスクリプト](https://github.com/huggingface/trl/tree/main/examples)を、QLoRA + PEFTと、[こちら](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs)で入手可能なaccelerate設定を使用して実行しました。これらの実験は、2x NVIDIA T4 GPU上で実行しました。

# PEFTとDeepSpeedのZeRO3を使用して、複数デバイスおよび複数ノードで大規模モデルのファインチューニングを行う

このガイドのセクションでは、SFT（教師ありファインチューニング）を実行するためのDeepSpeedの[学習スクリプト](https://github.com/huggingface/peft/blob/main/examples/sft/train.py)の使い方を学びます。スクリプトを設定して、単一のマシン上の8xH100 80GB GPUで、LoRAとZeRO-3を使用してLlama-70BモデルのSFTを行います。accelerateの設定を変更することで、複数マシンへのスケーリングも設定できます。

## 設定

🤗 Accelerate を使用して、[DeepSpeed 設定ファイルを作成する](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script)以下のコマンドを実行することから始めます。`--config_file` フラグを使用すると、設定ファイルを特定の場所に保存できます。指定しない場合、🤗 Accelerate のキャッシュ内に `default_config.yaml` として保存されます。

設定ファイルは、学習スクリプトを起動する際のデフォルトオプションを設定するために使用されます。

```bash
accelerate config --config_file deepspeed_config.yaml
```

セットアップに関するいくつかの質問が表示されるので、以下の引数を設定してください。この例ではZeRO-3を使用するため、該当するオプションを選択してください。

```bash
`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them. Pass the same value as you would pass via cmd argument else you will encounter mismatch error.
`gradient_clipping`: Enable gradient clipping with value. Don't set this as you will be passing it via cmd arguments.
`offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2. Set this as `none` as don't want to enable offloading.
`offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3. Set this as `none` as don't want to enable offloading.
`zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3. Set this to `True`.
`zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3. Set this to `True`.
`mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training. Set this to `True`.
```

これらが完了すると、対応する設定は以下のようになります。[deepspeed_config.yaml](https://github.com/huggingface/peft/blob/main/examples/sft/configs/deepspeed_config.yaml) は config フォルダにあります。

```yml
compute_environment: LOCAL_MACHINE                                                                                                                                           
debug: false
deepspeed_config:
  deepspeed_multinode_launcher: standard
  gradient_accumulation_steps: 4
  offload_optimizer_device: none
  offload_param_device: none
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 8
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

## 起動コマンド

起動コマンドは[run_peft_deepspeed.sh](https://github.com/huggingface/peft/blob/main/examples/sft/run_peft_deepspeed.sh)にあり、以下にも示されています:
```bash
accelerate launch --config_file "configs/deepspeed_config.yaml"  train.py \
--seed 100 \
--model_name_or_path "meta-llama/Llama-2-70b-hf" \
--dataset_name "smangrul/ultrachat-10k-chatml" \
--chat_template_format "chatml" \
--add_special_tokens False \
--append_concat_token False \
--splits "train,test" \
--max_seq_len 2048 \
--num_train_epochs 1 \
--logging_steps 5 \
--log_level "info" \
--logging_strategy "steps" \
--eval_strategy "epoch" \
--save_strategy "epoch" \
--push_to_hub \
--hub_private_repo True \
--hub_strategy "every_save" \
--bf16 True \
--packing True \
--learning_rate 1e-4 \
--lr_scheduler_type "cosine" \
--weight_decay 1e-4 \
--warmup_steps 0 \
--max_grad_norm 1.0 \
--output_dir "llama-sft-lora-deepspeed" \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 8 \
--gradient_accumulation_steps 4 \
--gradient_checkpointing True \
--use_reentrant False \
--dataset_text_field "content" \
--use_flash_attn True \
--use_peft_lora True \
--lora_r 8 \
--lora_alpha 16 \
--lora_dropout 0.1 \
--lora_target_modules "all-linear" \
--use_4bit_quantization False
```

rank=8、alpha=16 を使用し、すべての線形層を対象として LoRA を適用している点に注意してください。DeepSpeed の設定ファイルを渡し、ultrachat データセットの部分集合で 70B の Llama モデルをファインチューニングしています。

## 重要な部分

スクリプトの中身をもう少し詳しく見ていきましょう。何が起きているのか、どのように動作するのかを理解するために。

最初に知っておくべきことは、DeepSpeed の設定が渡されているため、このスクリプトは分散学習に DeepSpeed を使用しているという点です。[SFTTrainer](https://huggingface.co/docs/trl/v1.18.2/en/sft_trainer#trl.SFTTrainer) クラスは、渡された peft 設定を使用して PEFT モデルを作成するすべての処理を担当します。その後、`trainer.train()` を呼び出すと、[SFTTrainer](https://huggingface.co/docs/trl/v1.18.2/en/sft_trainer#trl.SFTTrainer) は内部で 🤗 Accelerate を使用して、DeepSpeed 設定に基づいてモデル、オプティマイザー、トレーナーを準備し、DeepSpeed エンジンを生成して学習を実行します。主なコードスニペットは以下の通りです：

```python
# trainer
trainer = SFTTrainer(
    model=model,
    processing_class=tokenizer,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
    peft_config=peft_config,
)
trainer.accelerator.print(f"{trainer.model}")

# train
checkpoint = None
if training_args.resume_from_checkpoint is not None:
    checkpoint = training_args.resume_from_checkpoint
trainer.train(resume_from_checkpoint=checkpoint)

# saving final model
trainer.save_model()
```

## メモリ使用量

上記の例では、以下のスクリーンショットに示すように、GPUごとのメモリ消費量は64 GB（80%）です：

    

トレーニング実行時のGPUメモリ使用量

## その他のリソース
You can also refer this blog post [Falcon 180B Finetuning using 🤗 PEFT and DeepSpeed](https://medium.com/@sourabmangrulkar/falcon-180b-finetuning-using-peft-and-deepspeed-b92643091d99) on how to finetune 180B Falcon model on 16 A100 GPUs on 2 machines.

# PEFT QLoRAとDeepSpeedのZeRO3を使用して、複数のGPUで大型モデルのファインチューニングを行う

このセクションでは、2X40GBのGPUで70BのLlamaモデルをファインチューニングするために、QLoRAとDeepSpeed Stage-3をどのように使用するかを説明します。これには、まず`bitsandbytes>=0.43.3`、`accelerate>=1.0.1`、`transformers>4.44.2`、`trl>0.11.4`、`peft>0.13.0`が必要です。Accelerateの設定を使用する際は、`zero3_init_flag`をtrueに設定する必要があります。以下は、[deepspeed_config_z3_qlora.yaml](https://github.com/huggingface/peft/blob/main/examples/sft/configs/deepspeed_config_z3_qlora.yaml)で見つかる設定です:

```yml
compute_environment: LOCAL_MACHINE                                                                                                                                           
debug: false
deepspeed_config:
  deepspeed_multinode_launcher: standard
  offload_optimizer_device: none
  offload_param_device: none
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 2
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

[run_peft_qlora_deepspeed_stage3.sh](https://github.com/huggingface/peft/blob/main/examples/sft/run_peft_qlora_deepspeed_stage3.sh) に用意されている起動コマンドは以下の通りです。
```
accelerate launch --config_file "configs/deepspeed_config_z3_qlora.yaml"  train.py \
--seed 100 \
--model_name_or_path "meta-llama/Llama-2-70b-hf" \
--dataset_name "smangrul/ultrachat-10k-chatml" \
--chat_template_format "chatml" \
--add_special_tokens False \
--append_concat_token False \
--splits "train,test" \
--max_seq_len 2048 \
--num_train_epochs 1 \
--logging_steps 5 \
--log_level "info" \
--logging_strategy "steps" \
--eval_strategy "epoch" \
--save_strategy "epoch" \
--push_to_hub \
--hub_private_repo True \
--hub_strategy "every_save" \
--bf16 True \
--packing True \
--learning_rate 1e-4 \
--lr_scheduler_type "cosine" \
--weight_decay 1e-4 \
--warmup_steps 0 \
--max_grad_norm 1.0 \
--output_dir "llama-sft-qlora-dsz3" \
--per_device_train_batch_size 2 \
--per_device_eval_batch_size 2 \
--gradient_accumulation_steps 2 \
--gradient_checkpointing True \
--use_reentrant True \
--dataset_text_field "content" \
--use_flash_attn True \
--use_peft_lora True \
--lora_r 8 \
--lora_alpha 16 \
--lora_dropout 0.1 \
--lora_target_modules "all-linear" \
--use_4bit_quantization True \
--use_nested_quant True \
--bnb_4bit_compute_dtype "bfloat16" \
--bnb_4bit_quant_storage_dtype "bfloat16"
```

4ビットパラメータのパッキングに使用するデータ型を示す新しい引数`bnb_4bit_quant_storage_dtype`が渡されている点に注意してください。例えば、`bfloat16`に設定すると、量子化後に**32/4 = 8**個の4ビットパラメータがまとめてパッキングされます。

学習コードの観点では、重要なコードの変更点は以下の通りです：

```diff
...

bnb_config = BitsAndBytesConfig(
    load_in_4bit=args.use_4bit_quantization,
    bnb_4bit_quant_type=args.bnb_4bit_quant_type,
    bnb_4bit_compute_dtype=compute_dtype,
    bnb_4bit_use_double_quant=args.use_nested_quant,
+   bnb_4bit_quant_storage=quant_storage_dtype,
)

...

model = AutoModelForCausalLM.from_pretrained(
    args.model_name_or_path,
    quantization_config=bnb_config,
    trust_remote_code=True,
    attn_implementation="flash_attention_2" if args.use_flash_attn else "eager",
+   dtype=quant_storage_dtype or torch.float32,
)
```

`AutoModelForCausalLM` の `dtype` は、`bnb_4bit_quant_storage` のデータ型と同じであることに注意してください。以上です。それ以外はすべて Trainer と TRL が処理します。

## メモリ使用量

上記の例では、GPUあたりのメモリ消費量は**36.6 GB**です。したがって、DeepSpeed Stage 3+LoRAでは8X80GBのGPU、DDP+QLoRAでは数台の80GB GPUが必要だった処理が、今では2X40GBのGPUで実行できます。これにより、大規模モデルのファインチューニングがより手軽に行えるようになります。

# PEFTとDeepSpeedのZeRO3およびCPUオフロードを使用して、単一のGPUで大型モデルのファインチューニングを行う
このガイドのセクションでは、DeepSpeedの[学習スクリプト](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py)の使い方を学びます。スクリプトを設定して、ZeRO-3とCPU Offloadを使用して、条件付き生成のための大規模モデルを学習します。

> [!TIP]
> 💡 はじめの一歩として、[causal language modeling](https://github.com/huggingface/peft/blob/main/examples/causal_language_modeling/peft_lora_clm_accelerate_ds_zero3_offload.py)および[conditional generation](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py)のトレーニングスクリプトの例をご覧ください。これらのスクリプトは、ご自身のアプリケーションに合わせて調整したり、タスクがスクリプトのものと類似している場合はそのまま使用したりできます。

## 設定

🤗 Accelerate を使用して、[DeepSpeed 設定ファイルを作成する](https://huggingface.co/docs/accelerate/quicktour#launching-your-distributed-script)以下のコマンドを実行することから始めます。`--config_file` フラグを使用すると、設定ファイルを特定の場所に保存できます。指定しない場合、🤗 Accelerate のキャッシュ内に `default_config.yaml` として保存されます。

設定ファイルは、学習スクリプトを起動する際のデフォルトオプションを設定するために使用されます。

```bash
accelerate config --config_file ds_zero3_cpu.yaml
```

セットアップに関するいくつかの質問が表示されるので、以下の引数を設定してください。この例では、ZeRO-3とCPU-Offloadを使用するため、これらのオプションを選択してください。

```bash
`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning
`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them.
`gradient_clipping`: Enable gradient clipping with value.
`offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2.
`offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3.
`zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3.
`zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3.
`mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training. 
```

[設定ファイル](https://github.com/huggingface/peft/blob/main/examples/conditional_generation/accelerate_ds_zero3_cpu_offload_config.yaml)の例は以下のようになります。最も重要なのは、`zero_stage`が`3`に設定されており、`offload_optimizer_device`と`offload_param_device`が`cpu`に設定されている点です。

```yml
compute_environment: LOCAL_MACHINE
deepspeed_config:
  gradient_accumulation_steps: 1
  gradient_clipping: 1.0
  offload_optimizer_device: cpu
  offload_param_device: cpu
  zero3_init_flag: true
  zero3_save_16bit_model: true
  zero_stage: 3
distributed_type: DEEPSPEED
downcast_bf16: 'no'
dynamo_backend: 'NO'
fsdp_config: {}
machine_rank: 0
main_training_function: main
megatron_lm_config: {}
mixed_precision: 'no'
num_machines: 1
num_processes: 1
rdzv_backend: static
same_network: true
use_cpu: false
```

## 重要な部分

スクリプトの中身をもう少し詳しく見ていきましょう。何が起きているのか、どのように動作するのかを理解するために。

[`main`](https://github.com/huggingface/peft/blob/2822398fbe896f25d4dac5e468624dc5fd65a51b/examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py#L103) 関数内では、スクリプトが[Accelerator](https://huggingface.co/docs/accelerate/v1.16.0/en/package_reference/accelerator#accelerate.Accelerator)クラスを作成し、分散学習に必要なすべての要件を初期化します。

> [!TIP]
> 💡 `main`関数内のモデルとデータセットは、自由に置き換えてください。データセットの形式がスクリプト内のものとは異なる場合、独自の前処理関数を作成する必要がある場合もあります。

このスクリプトは、使用している🤗 PEFT手法（ここではLoRA）の設定も作成します。[LoraConfig](/docs/peft/v0.22.0/ja/package_reference/lora#peft.LoraConfig)は、タスクタイプや、低ランク行列の次元、行列のスケーリング係数、LoRA層のドロップアウト確率といった重要なパラメータを指定します。別の🤗 PEFT手法を使用する場合は、`LoraConfig`を適切な[クラス](../package_reference/tuners)に置き換えてください。

```diff
 def main():
+    accelerator = Accelerator()
     model_name_or_path = "facebook/bart-large"
     dataset_name = "twitter_complaints"
+    peft_config = LoraConfig(
         task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
     )
```

Throughout the script, you'll see the [main_process_first](https://huggingface.co/docs/accelerate/v1.16.0/en/package_reference/accelerator#accelerate.Accelerator.main_process_first) and [wait_for_everyone](https://huggingface.co/docs/accelerate/v1.16.0/en/package_reference/accelerator#accelerate.Accelerator.wait_for_everyone) functions which help control and synchronize when processes are executed.

[get_peft_model()](/docs/peft/v0.22.0/ja/package_reference/peft_model#peft.get_peft_model) 関数は、ベースモデルと、先に準備した `peft_config` を受け取り、[PeftModel](/docs/peft/v0.22.0/ja/package_reference/peft_model#peft.PeftModel) を作成します:

```diff
  model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
+ model = get_peft_model(model, peft_config)
```

🤗 Accelerate の [prepare](https://huggingface.co/docs/accelerate/v1.16.0/en/package_reference/accelerator#accelerate.Accelerator.prepare) に、トレーニングに関連するすべてのオブジェクトを渡します。これにより、トレーニングの準備が整っていることが保証されます。

```py
model, train_dataloader, eval_dataloader, test_dataloader, optimizer, lr_scheduler = accelerator.prepare(
    model, train_dataloader, eval_dataloader, test_dataloader, optimizer, lr_scheduler
)
```

次のコードでは、`Accelerator`でDeepSpeedプラグインが使用されているかどうかを確認し、プラグインが存在する場合はZeRO-3を使用しているかどうかを確認します。この条件フラグは、モデルのパラメータがシャーディングされている場合、推論中に`generate`関数を呼び出す際にGPUを同期するために使用されます。

```py
is_ds_zero_3 = False
if getattr(accelerator.state, "deepspeed_plugin", None):
    is_ds_zero_3 = accelerator.state.deepspeed_plugin.zero_stage == 3
```

トレーニングループ内では、通常の`loss.backward()`の代わりに、設定に基づいて適切な`backward()`メソッドを使用する🤗 Accelerateの[backward](https://huggingface.co/docs/accelerate/v1.16.0/en/package_reference/accelerator#accelerate.Accelerator.backward)が使用されます:

```diff
  for epoch in range(num_epochs):
      with TorchTracemalloc() as tracemalloc:
          model.train()
          total_loss = 0
          for step, batch in enumerate(tqdm(train_dataloader)):
              outputs = model(**batch)
              loss = outputs.loss
              total_loss += loss.detach().float()
+             accelerator.backward(loss)
              optimizer.step()
              lr_scheduler.step()
              optimizer.zero_grad()
```

以上です！スクリプトの残りは、トレーニングループ、評価、さらにはHubへのプッシュまでを代行してくれます。

## 学習

学習スクリプトを起動するには、以下のコマンドを実行します。以前、設定ファイルを`ds_zero3_cpu.yaml`として保存したので、`--config_file`引数でパスをランチャーに渡す必要があります。

```bash
accelerate launch --config_file ds_zero3_cpu.yaml examples/conditional_generation/peft_lora_seq2seq_accelerate_ds_zero3_offload.py
```

トレーニング中のメモリ使用量を追跡する出力ログが表示され、完了すると、スクリプトは精度を返して、予測とラベルを比較します:

```bash
GPU Memory before entering the train : 1916
GPU Memory consumed at the end of the train (end-begin): 66
GPU Peak Memory consumed during the train (max-begin): 7488
GPU Total Peak Memory consumed during the train (max): 9404
CPU Memory before entering the train : 19411
CPU Memory consumed at the end of the train (end-begin): 0
CPU Peak Memory consumed during the train (max-begin): 0
CPU Total Peak Memory consumed during the train (max): 19411
epoch=4: train_ppl=tensor(1.0705, device='cuda:0') train_epoch_loss=tensor(0.0681, device='cuda:0')
100%|████████████████████████████████████████████████████████████████████████████████████████████| 7/7 [00:27<00:00,  3.92s/it]
GPU Memory before entering the eval : 1982
GPU Memory consumed at the end of the eval (end-begin): -66
GPU Peak Memory consumed during the eval (max-begin): 672
GPU Total Peak Memory consumed during the eval (max): 2654
CPU Memory before entering the eval : 19411
CPU Memory consumed at the end of the eval (end-begin): 0
CPU Peak Memory consumed during the eval (max-begin): 0
CPU Total Peak Memory consumed during the eval (max): 19411
accuracy=100.0
eval_preds[:10]=['no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint', 'no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint']
dataset['train'][label_column][:10]=['no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint', 'no complaint', 'no complaint', 'complaint', 'complaint', 'no complaint']
```

# 注意事項
1. PEFTとDeepSpeedを併用する場合のMergingは現在サポートされておらず、エラーが発生します。
2. CPUオフローディングを使用する場合、PEFTを使用してオプティマイザの状態と勾配をアダプタの重みのサイズまで縮小することによる主な利点はCPU RAMで実現され、GPUメモリに対する節約にはなりません。
3. CPU オフロードを有効にした状態で DeepSpeed Stage 3 と qlora を使用すると、CPU オフロードを無効にした場合と比較して、GPU メモリの使用量が増加します。

> [!TIP]
> 💡 重みのマージ（およびアンマージ）を必要とするコードがある場合、事前にDeepSpeed Zero-3でパラメータを手動で収集してみてください：
>
> ```python
> import deepspeed
>
> is_ds_zero_3 = ... # check if Zero-3
>
> with deepspeed.zero.GatheredParameters(list(model.parameters()), enabled= is_ds_zero_3):
>     model.merge_adapter()
>     # do whatever is needed, then unmerge in the same context if unmerging is required
>     ...
>     model.unmerge_adapter()
> ```

