針對 Phi Silica 進行 LoRA 微調

您可以使用低階適應 (LoRA) 來微調 Phi Silica 模型,以增強其在特定使用案例中的效能。透過使用 LoRA 來優化 Microsoft Windows 本地語言模型 Phi Silica,您可以獲得更精確的結果。此過程包括訓練 LoRA 適配器,然後在推論期間應用它,以提升模型的準確度。

注意

Phi Silica 功能在中國無法使用。

先決條件

  • 您已確定一個需要增強 Phi Silica 回應的使用案例。
  • 您已選擇評估標準來決定什麼是「好的回應」。
  • 您已嘗試過 Phi Silica API,但它們不符合您的評估標準。

訓練您的適配器 (Adapter)

若要訓練用於微調 Windows 11 上 Phi Silica 模型的 LoRA 適配器,您必須先產生訓練過程將使用的資料集。

產生用於 LoRA 適配器的資料集

若要產生資料集,您需要將資料分割為兩個檔案

  • train.json:用於訓練適配器。
  • test.json:用於在訓練期間及之後評估適配器的效能。

這兩個檔案都必須使用 JSON 格式,其中每一行是一個獨立的 JSON 物件,代表單一樣本。每個樣本應包含使用者與助理之間交換的訊息列表。

每個訊息物件需要兩個欄位

  • content:訊息文字。
  • role"user""assistant",指出發送者。

請參閱以下範例

{"messages": [{"content": "Hello, how do I reset my password?", "role": "user"}, {"content": "To reset your password, go to the settings page and click 'Reset Password'.", "role": "assistant"}]}

{"messages": [{"content": "Can you help me find nearby restaurants?", "role": "user"}, {"content": "Sure! Here are some restaurants near your location: ...", "role": "assistant"}]}

{"messages": [{"content": "What is the weather like today?", "role": "user"}, {"content": "Today's forecast is sunny with a high of 25°C.", "role": "assistant"}]}

訓練提示

  • 每一行樣本結尾不需要逗號。
  • 請包含盡可能多且多樣化的高品質範例。為獲得最佳結果,請在您的 train.json 檔案中收集至少幾千個訓練樣本。
  • test.json 檔案可以較小,但應涵蓋您預期模型處理的互動類型。
  • 建立 train.jsontest.json 檔案,每一行包含一個 JSON 物件,每個物件包含使用者與助理之間簡短的來回對話。資料的品質與數量將大大影響您 LoRA 適配器的有效性。

訓練 LoRA 適配器

若要訓練 LoRA 適配器,您需要滿足以下必要條件

請按照下列步驟建立工作區並開始微調工作

  1. 導覽至 Model Tools (模型工具) > Fine-tuning (微調) 並選取 New Project (新增專案)

  2. 從模型目錄中選取 "microsoft/phi-silica" 並選取 Next (下一步)

  3. 在對話方塊中,選取專案資料夾並輸入專案名稱。系統將為該專案開啟一個新的 VS Code 視窗。

    Screenshot of creating fine-tuning project in AITK.

  4. 從方法清單中選取 "LoRA"。

    Screenshot of selecting LoRA method.

  5. Data (資料) > Training Dataset name (訓練資料集名稱)Test Dataset name (測試資料集名稱) 下,選取您的 train.jsontest.json 檔案。

  6. 選取 Run with Cloud (使用雲端執行)

    Screenshot of filling fine-tuning job parameters.

  7. 在對話方塊中,選取用於存取 Azure 訂閱的 Microsoft 帳戶。

  8. 選取帳戶後,從訂閱下拉式選單中選取一個資源群組。

  9. 請注意,您的微調工作將成功啟動並顯示工作狀態。

    使用 Refresh (重新整理) 按鈕手動更新狀態。微調工作平均需要 45 到 60 分鐘才能完成。

  10. 工作完成後,您可以選擇下載剛訓練好的 LoRA 適配器,方法是選取 Download (下載),並選取 Show Metrics (顯示指標) 來檢查微調指標。

    Screenshot of downloading adapter and showing metrics

LoRA 微調建議

超參數選擇

為 LoRA 微調設定的預設超參數應能提供合理的基準微調以供比較。我們已盡力找到適用於大多數使用案例和資料集的預設值。

不過,我們也保留了靈活性,讓您在需要時可以掃描參數。

訓練超參數

我們的標準參數搜尋空間為

參數名稱 最小值 最大值 分佈
learning_rate 1e-4 1e-2 Log-uniform
weight_decay 1e-5 1e-1 Log-uniform
adam_beta1 0.9 0.99 Uniform
adam_beta2 0.9 0.999 Uniform
adam_epsilon 1e-9 1e-6 Log-uniform
num_warmup_steps 0 10000 Uniform
lora_dropout 0 0.5 Uniform

我們也搜尋學習率排程器,選擇 linear_with_warmupcosine_with_warmup 其中之一。如果 num_warmup_steps 參數設定為 0,則您可以同等地使用線性或餘弦選項。

學習率、學習率排程器與預熱步驟數量 (warmup steps) 三者彼此互動。將其中兩個保持固定並改變第三個,將能讓您更深入了解它們如何改變訓練輸出。

權重衰減 (weight decay) 和 LoRA dropout 參數旨在協助控制過度擬合。如果您發現適配器在訓練集與評估集之間的泛化能力不佳,請嘗試增加這些參數的值。

adam_ 參數會影響 Adam 優化器在訓練步驟中的行為。有關該優化器的詳細資訊,請參閱 PyTorch 文件。

公開的其他許多參數,類似於 PEFT 程式庫中名稱相同的對應參數。有關這些參數的詳細資訊,請參閱 transformers 文件。

資料超參數

資料超參數 train_nsamplestest_nsamples 分別控制訓練和測試所需的樣本數。使用訓練集中更多的樣本通常是個好主意。使用更多的測試樣本可獲得雜訊較少的測試指標,但每次評估執行所需的時間會更長。

train_batch_sizetest_batch_size 參數分別控制訓練和測試時每個批次使用的樣本數。通常測試時使用的批次可以比訓練時更多,因為執行測試範例消耗的 GPU 記憶體比訓練範例少。

train_seqlentest_seqlen 參數控制訓練和測試序列的長度。一般而言,越長越好,直到達到 GPU 記憶體限制為止。預設值應該能提供良好的平衡。

選擇系統提示 (System Prompt)

我們發現,在選擇訓練用的系統提示時,保持簡單(1 到 2 個句子)同時鼓勵模型以您想要的格式產生輸出,是一個有效策略。我們也發現,在訓練與推論時使用稍微不同的系統提示,可以改善結果。

您的期望輸出與基礎模型之間的差異越大,系統提示對您的幫助就越大。

例如,如果您只是訓練基礎模型的風格微調(例如使用簡單語言以吸引年輕讀者),您可能根本不需要系統提示。

不過,如果您的期望輸出具有更多結構,您就會希望使用系統提示來引導模型。例如,如果您需要帶有特定鍵值的 JSON 表格,系統提示的第一句話可以描述模型回應應具備的平實語言格式。第二句話則可進一步指定 JSON 表格格式的外觀。在訓練時使用第一句話,並在推論時使用這兩句話,或許能為您提供想要的結果。

參數

所有可微調的參數清單已附加於此。如果某個參數未出現在工作流程頁面的 UI 中,請手動將其新增至 <your_project_path>/<model_name>/lora/lora.yaml

[

################## Basic config settings ##################
  {
    "groupId": "data",
    "fields": [
      {
        "name": "system_prompt",
        "type": "Optional",
        "defaultValue": null,
        "info": "Optional system prompt. If specified, the system prompt given here will be prepended to each example in the dataset as the system prompt when training the LoRA adapter. When running inference the same (or a very similar) system prompt should be used. Note: if a system prompt is specified in the training data, giving a system prompt here will overwrite the system prompt in the dataset.",
        "label": "System prompt"
      },
      {
        "name": "varied_seqlen",
        "type": "bool",
        "defaultValue": false,
        "info": "Varied sequence lengths in the calibration data. If False (default), training examples will be concatenated together until they are finetune_[train/test]_seqlen tokens long. This makes memory usage more consistent and predictable. If True, each individual example will be truncated to finetune_[train/test]_seqlen tokens. This can sometimes give better training performance, but also gives unpredictable memory usage. It can cause `out of memory` errors mid training, if there are long training examples in your dataset.",
        "label": "Allow varied sequence length in data"
      },
      {
        "name": "finetune_dataset",
        "type": "str",
        "defaultValue": "wikitext2",
        "info": "Dataset to finetune on.",
        "label": "Dataset name or path"
      },
      {
        "name": "finetune_train_nsamples",
        "type": "int",
        "defaultValue": 4096,
        "info": "Number of samples to load from the train set for finetuning.",
        "label": "Number of finetuning samples"
      },
      {
        "name": "finetune_test_nsamples",
        "type": "int",
        "defaultValue": 128,
        "info": "Number of samples to load from the test set for finetuning.",
        "label": "Number of test samples"
      },
      {
        "name": "finetune_train_batch_size",
        "type": "int",
        "defaultValue": 4,
        "info": "Batch size for finetuning training.",
        "label": "Training batch size"
      },
      {
        "name": "finetune_test_batch_size",
        "type": "int",
        "defaultValue": 8,
        "info": "Batch size for finetuning testing.",
        "label": "Test batch size"
      },
      {
        "name": "finetune_train_seqlen",
        "type": "int",
        "defaultValue": 2048,
        "info": "Maximum sequence length for finetuning training. Longer sequences will be truncated.",
        "label": "Max training sequence length"
      },
      {
        "name": "finetune_test_seqlen",
        "type": "int",
        "defaultValue": 2048,
        "info": "Maximum sequence length for finetuning testing. Longer sequences will be truncated.",
        "label": "Max test sequence length"
      }
    ]
  },
  {
    "groupId": "finetuning",
    "fields": [
      {
        "name": "early_stopping_patience",
        "type": "int",
        "defaultValue": 5,
        "info": "Number of evaluations with no improvement after which training will be stopped.",
        "label": "Early stopping patience"
      },
      {
        "name": "epochs",
        "type": "float",
        "defaultValue": 1,
        "info": "Number of total epochs to run.",
        "label": "Epochs"
      },
      {
        "name": "eval_steps",
        "type": "int",
        "defaultValue": 64,
        "info": "Number of training steps to perform before each evaluation.",
        "label": "Steps between evaluations"
      },
      {
        "name": "save_steps",
        "type": "int",
        "defaultValue": 64,
        "info": "Number of steps after which to save model checkpoint. This _must_ be a multiple of the number of steps between evaluations.",
        "label": "Steps between checkpoints"
      },
      {
        "name": "learning_rate",
        "type": "float",
        "defaultValue": 0.0002,
        "info": "Learning rate for training.",
        "label": "Learning rate"
      },
      {
        "name": "lr_scheduler_type",
        "type": "str",
        "defaultValue": "linear",
        "info": "Type of learning rate scheduler.",
        "label": "Learning rate scheduler",
        "optionValues": [
          "linear",
          "linear_with_warmup",
          "cosine",
          "cosine_with_warmup"
        ]
      },
      {
        "name": "num_warmup_steps",
        "type": "int",
        "defaultValue": 400,
        "info": "Number of warmup steps for learning rate scheduler. Only relevant for a _with_warmup scheduler.",
        "label": "Scheduler warmup steps (if supported)"
      }
    ]
  }



################## Advanced config settings ##################



  {
    "groupId": "advanced",
    "fields": [
      {
        "name": "seed",
        "type": "int",
        "defaultValue": 42,
        "info": "Seed for sampling the data.",
        "label": "Random seed"
      },
      {
        "name": "evaluation_strategy",
        "type": "str",
        "defaultValue": "steps",
        "info": "Evaluation strategy to use.",
        "label": "Evaluation strategy",
        "optionValues": [
          "steps",
          "epoch",
          "no"
        ]
      },
      {
        "name": "lora_dropout",
        "type": "float",
        "defaultValue": 0.1,
        "info": "Dropout rate for LoRA.",
        "label": "LoRA dropout"
      },
      {
        "name": "adam_beta1",
        "type": "float",
        "defaultValue": 0.9,
        "info": "Beta1 hyperparameter for Adam optimizer.",
        "label": "Adam beta 1"
      },
      {
        "name": "adam_beta2",
        "type": "float",
        "defaultValue": 0.95,
        "info": "Beta2 hyperparameter for Adam optimizer.",
        "label": "Adam beta 2"
      },
      {
        "name": "adam_epsilon",
        "type": "float",
        "defaultValue": 1e-08,
        "info": "Epsilon hyperparameter for Adam optimizer.",
        "label": "Adam epsilon"
      },
      {
        "name": "num_training_steps",
        "type": "Optional",
        "defaultValue": null,
        "info": "The number of training steps there will be. If not set (recommended), this will be calculated internally.",
        "label": "Number of training steps"
      },
      {
        "name": "gradient_accumulation_steps",
        "type": "int",
        "defaultValue": 1,
        "info": "Number of updates steps to accumulate before performing a backward/update pass.",
        "label": "gradient accumulation steps"
      },
      {
        "name": "eval_accumulation_steps",
        "type": "Optional",
        "defaultValue": null,
        "info": "Number of predictions steps to accumulate before moving the tensors to the CPU.",
        "label": "eval accumulation steps"
      },
      {
        "name": "eval_delay",
        "type": "Optional",
        "defaultValue": 0,
        "info": "Number of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy.",
        "label": "eval delay"
      },
      {
        "name": "weight_decay",
        "type": "float",
        "defaultValue": 0.0,
        "info": "Weight decay for AdamW if we apply some.",
        "label": "weight decay"
      },
      {
        "name": "max_grad_norm",
        "type": "float",
        "defaultValue": 1.0,
        "info": "Max gradient norm.",
        "label": "max grad norm"
      },
      {
        "name": "gradient_checkpointing",
        "type": "bool",
        "defaultValue": false,
        "info": "If True, use gradient checkpointing to save memory at the expense of slower backward pass.",
        "label": "gradient checkpointing"
      }
    ]
  }
]

修改 Azure 訂閱與資源群組

如果您想修改先前設定的 Azure 訂閱和資源群組,可以在 <your_project_path>/model_lab.workspace.provision.config 檔案中更新或移除它們。

使用 Phi Silica LoRA 適配器進行推論

重要

Phi Silica API 是受限存取功能的一部分(請參閱 LimitedAccessFeatures 類別)。如需詳細資訊或要求解鎖權杖,請使用 LAF 存取權杖要求表單

注意

使用 Phi Silica LoRA 適配器進行推論目前僅支援搭載 ARM 處理器的 Copilot+ 電腦。

使用 Windows AI API 進行推論:具有 LoRA 適配器的 Phi Silica

© . This site is unofficial and not affiliated with Microsoft.