Transformers
Safetensors
unsloth
Inference Endpoints

wandbのeval結果 image/png

wandbのtrain結果 image/png

Uses

下記を実行してください。GoogleColabを想定して記載しています。

# 必要なライブラリをインストール
%%capture
!pip install unsloth
!pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
!pip install -U torch
!pip install -U peft
# 必要なライブラリを読み込み
from unsloth import FastLanguageModel
from peft import PeftModel
import torch
import json
from tqdm import tqdm
import re
# ベースとなるモデルと学習したLoRAのアダプタ(Hugging FaceのIDを指定)。
model_id = "llm-jp/llm-jp-3-13b"
adapter_id = "SarahMars/11a_ichikara_magpie_WikiQA"
HF_TOKEN = <YOUR HuggingFace TOKEN>
# unslothのFastLanguageModelで元のモデルをロード。
dtype = None # Noneにしておけば自動で設定
load_in_4bit = True # 今回は13Bモデルを扱うためTrue

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=model_id,
    dtype=dtype,
    load_in_4bit=load_in_4bit,
    trust_remote_code=True,
)
# 元のモデルにLoRAのアダプタを統合。
model = PeftModel.from_pretrained(model, adapter_id, token = HF_TOKEN)
# タスクとなるデータの読み込み。
# 事前にデータをアップロードしてください。
datasets = []
with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
    item = ""
    for line in f:
      line = line.strip()
      item += line
      if item.endswith("}"):
        datasets.append(json.loads(item))
        item = ""
# モデルを用いてタスクの推論。

# 推論するためにモデルのモードを変更
FastLanguageModel.for_inference(model)

results = []
for dt in tqdm(datasets):
  input = dt["input"]

  prompt = f"""### 指示\n{input}\n### 回答\n"""

  inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)

  outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
  prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]

  results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
# 結果をjsonlで保存。

# ここではadapter_idを元にファイル名を決定しているが、ファイル名は任意で問題なし。
json_file_id = re.sub(".*/", "", adapter_id)
with open(f"/content/{json_file_id}_output.jsonl", 'w', encoding='utf-8') as f:
    for result in results:
        json.dump(result, f, ensure_ascii=False)
        f.write('\n')

Preprocessing [optional]

L4で40分程度でElyza-100-tasksの推論が可能

Training Hyperparameters

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=model_id,
    dtype=dtype,
    load_in_4bit=load_in_4bit,
    trust_remote_code=True,
    # use_exact_model_name=True
)

# SFT用のモデルを用意
model = FastLanguageModel.get_peft_model(
    model,
    r = 32,
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",], # 線形層だけターゲットにする
    lora_alpha = 32,
    lora_dropout = 0.05,
    bias = "none",
    use_gradient_checkpointing = "unsloth",
    random_state = 3407,
    use_rslora = False,
    loftq_config = None,
    max_seq_length = max_seq_length,
)
trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset=train_dataset, # dataset["train"],
    eval_dataset=eval_dataset,
    max_seq_length = max_seq_length,
    dataset_text_field="output",
    packing = False,
    # neftune_noise_alpha=5, # ★★NEFTune設定 paper and hacks参照
    args = TrainingArguments(
        evaluation_strategy="steps",  # 検証をステップごとに実行
        eval_steps=100,   # 100             # 100ステップごとに検証
        per_device_train_batch_size = 4,
        per_device_eval_batch_size= 8,
        gradient_accumulation_steps = 4,
        num_train_epochs = 1,# 3
        logging_steps = 100,
        warmup_steps = 10,
        save_steps=100,
        save_total_limit=2,
        max_steps=-1,
        learning_rate = 1e-4, # 2e-4
        fp16 = not is_bfloat16_supported(),
        bf16 = is_bfloat16_supported(),
        group_by_length=True,
        seed = 3407,
        output_dir = new_model_id,
        report_to = "wandb",
        auto_find_batch_size=True, # 追加:これを入れないとGPUメモリがオーバーフローする可能性がある。自分で設定したものよりも優先される。
        push_to_hub=True, # Hugging Faceにcheckpointsをsaveする。
        metric_for_best_model="eval_loss", # Early Stopping の基準となる指標を指定
        greater_is_better=False, # 基準指標が大きいほうが良い場合は True、小さいほうが良い場合は False を設定
        # early_stopping_patience
        load_best_model_at_end=True, # Early Stopping に必須
    ),
    callbacks=[EarlyStoppingCallback(early_stopping_patience=3)],  # Early Stopping を追加
)

Evaluation

20% of the dataset was used for evaluation

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model is not currently available via any of the supported Inference Providers.
The model cannot be deployed to the HF Inference API: The model has no pipeline_tag.

Model tree for SarahMars/11a_ichikara_magpie_WikiQA

Finetuned
(1120)
this model

Datasets used to train SarahMars/11a_ichikara_magpie_WikiQA