Downloads · 30 days
0
hatsukaze86/llm-jp-3-13b-20241127-hatsukaze4-4-4_lora
llm-jp-3-13b-20241127-hatsukaze4-4-4_lora is a machine learning model from hatsukaze86. Use it for the machine learning task on the model card, and read the license before you ship it in a product. It is set up for transformers. The card lists the license as apache-2.0.
- Developed by: hatsukaze86 - License: apache-2.0 - Finetuned from model : llm-jp/llm-jp-3-13b
Downloads · 30 days
0
Access
Public
Updated Dec 16, 2024
Repo size
501 MB
Likes
0
Public
Click a slice to open those files.
.safetensors501 MB · 99%
From the Hugging Face model README
This llama model was trained 2x faster with Unsloth and Huggingface's TRL library.
以下は、作成したコードの全体です。google-colab上で動作します。 基本的に実施したことは、次の通りです。 1.パラメータ調整 2.ichikaraのデータセット2種での学習ののち、elyza-tasks-100を用いて更に学習 3.ichikaraは、データセットを成形する上で、うまく読み込みできなかったデータを1種類除外しています。
使用上の注意点 1.リソース節約のため、実行終了時に自動でセッションを削除します。そのため、出力したjsonファイルはdriveに自動的に上がります。ファイルパスを適切に設定してください。 2.WAN-DBやHFのKeyはシークレットから読み込みます。こちらも、事前設定をお願いします。 3.データセットも、Drive上のデータを自動読み込みにしています。適切にパスを変更して使用してください
メイン コンテンツにスキップ LoRA_template_unsloth_20241127_hatsukaze4-4-4.ipynb LoRA_template_unsloth_20241127_hatsukaze4-4-4.ipynb_ 最終編集: 12月15日 最終課題コンペ用 Fine-tuning テンプレート(unsloth) 最終課題コンペにて Fine-tuning を行ないたい方に向けの Fine-tuning コードです。 こちらは L4 を利用できない受講生の方向けにUnslothを用いたものとなっております。 Google Colab の無料版で利用可能な T4 でも動作可能になっています。 環境設定の難易度が高いので、慎重に取り組んでいただければと思います。
terminalでのconda環境構築(Omnicampusの環境などの場合) 事前にterminalで環境構築の必要があります。Google Colabでは不要です。
wget "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
bash Miniforge3-$(uname)-$(uname -m).sh
export PATH=/root/miniforge3/bin:$PATH
conda init
conda create --name unsloth_env python=3.10 pytorch-cuda=12.1 pytorch cudatoolkit xformers -c pytorch -c nvidia -c xformers -y
conda activate unsloth_env
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps "trl<0.9.0" peft accelerate bitsandbytes
conda install -c conda-forge ipykernel
python -m ipykernel install --user --name=unsloth_env --display-name "Python (unsloth_env)"
修正したコード 修正内容:google colab pro+用、終了後の自動ランタイム削除、jsonファイル保存場所のdriveへの変更
[ ] from google.colab import runtime from google.colab import drive drive.mount('/content/drive') Mounted at /content/drive
[ ]
!pip uninstall unsloth -y !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
[ ]
!pip install --upgrade torch !pip install --upgrade xformers Requirement already satisfied: torch in /usr/local/lib/python3.10/dist-packages (2.5.1+cu121) Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch) (3.16.1) Requirement already satisfied: typing-extensions>=4.8.0 in /usr/local/lib/python3.10/dist-packages (from torch) (4.12.2) Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch) (3.4.2) Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch) (3.1.4) Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch) (2024.9.0) Requirement already satisfied: sympy==1.13.1 in /usr/local/lib/python3.10/dist-packages (from torch) (1.13.1) Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.10/dist-packages (from sympy==1.13.1->torch) (1.3.0) Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch) (3.0.2) Collecting xformers Downloading xformers-0.0.28.post3-cp310-cp310-manylinux_2_28_x86_64.whl.metadata (1.0 kB) Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from xformers) (1.26.4) Requirement already satisfied: torch==2.5.1 in /usr/local/lib/python3.10/dist-packages (from xformers) (2.5.1+cu121) Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch==2.5.1->xformers) (3.16.1) Requirement already satisfied: typing-extensions>=4.8.0 in /usr/local/lib/python3.10/dist-packages (from torch==2.5.1->xformers) (4.12.2) Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch==2.5.1->xformers) (3.4.2) Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch==2.5.1->xformers) (3.1.4) Requirement already satisfied: fsspec in /usr/local/lib/python3.10/dist-packages (from torch==2.5.1->xformers) (2024.9.0) Requirement already satisfied: sympy==1.13.1 in /usr/local/lib/python3.10/dist-packages (from torch==2.5.1->xformers) (1.13.1) Requirement already satisfied: mpmath<1.4,>=1.1.0 in /usr/local/lib/python3.10/dist-packages (from sympy==1.13.1->torch==2.5.1->xformers) (1.3.0) Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch==2.5.1->xformers) (3.0.2) Downloading xformers-0.0.28.post3-cp310-cp310-manylinux_2_28_x86_64.whl (16.7 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 16.7/16.7 MB 101.0 MB/s eta 0:00:00 Installing collected packages: xformers Successfully installed xformers-0.0.28.post3 修正したコード 修正内容:wandb
[ ] !pip install wandb Requirement already satisfied: wandb in /usr/local/lib/python3.10/dist-packages (0.18.7) Requirement already satisfied: click!=8.0.0,>=7.1 in /usr/local/lib/python3.10/dist-packages (from wandb) (8.1.7) Requirement already satisfied: docker-pycreds>=0.4.0 in /usr/local/lib/python3.10/dist-packages (from wandb) (0.4.0) Requirement already satisfied: gitpython!=3.1.29,>=1.0.0 in /usr/local/lib/python3.10/dist-packages (from wandb) (3.1.43) Requirement already satisfied: platformdirs in /usr/local/lib/python3.10/dist-packages (from wandb) (4.3.6) Requirement already satisfied: protobuf!=4.21.0,!=5.28.0,<6,>=3.19.0 in /usr/local/lib/python3.10/dist-packages (from wandb) (3.20.3) Requirement already satisfied: psutil>=5.0.0 in /usr/local/lib/python3.10/dist-packages (from wandb) (5.9.5) Requirement already satisfied: pyyaml in /usr/local/lib/python3.10/dist-packages (from wandb) (6.0.2) Requirement already satisfied: requests<3,>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from wandb) (2.32.3) Requirement already satisfied: sentry-sdk>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from wandb) (2.19.2) Requirement already satisfied: setproctitle in /usr/local/lib/python3.10/dist-packages (from wandb) (1.3.4) Requirement already satisfied: setuptools in /usr/local/lib/python3.10/dist-packages (from wandb) (75.1.0) Requirement already satisfied: typing-extensions<5,>=4.4 in /usr/local/lib/python3.10/dist-packages (from wandb) (4.12.2) Requirement already satisfied: six>=1.4.0 in /usr/local/lib/python3.10/dist-packages (from docker-pycreds>=0.4.0->wandb) (1.17.0) Requirement already satisfied: gitdb<5,>=4.0.1 in /usr/local/lib/python3.10/dist-packages (from gitpython!=3.1.29,>=1.0.0->wandb) (4.0.11) Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.0.0->wandb) (3.4.0) Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.0.0->wandb) (3.10) Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.0.0->wandb) (2.2.3) Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.0.0->wandb) (2024.8.30) Requirement already satisfied: smmap<6,>=3.0.1 in /usr/local/lib/python3.10/dist-packages (from gitdb<5,>=4.0.1->gitpython!=3.1.29,>=1.0.0->wandb) (5.0.1) 修正したコード 修正内容:wandb設定
[ ] #学習状況を可視化 import wandb import os from google.colab import userdata
api_key = userdata.get('WANDB_APIKEY')
wandb.login(key=api_key) wandb.init(project="llm-lecture-2024-competition")
[ ]
#!pip install ipywidgets --upgrade
[ ]
import torch if torch.cuda.get_device_capability()[0] >= 8: !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3" Requirement already satisfied: packaging in /usr/local/lib/python3.10/dist-packages (24.2) Collecting ninja Downloading ninja-1.11.1.2-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.whl.metadata (5.3 kB) Requirement already satisfied: einops in /usr/local/lib/python3.10/dist-packages (0.8.0) Collecting flash-attn>=2.6.3 Downloading flash_attn-2.7.2.post1.tar.gz (3.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.1/3.1 MB 28.0 MB/s eta 0:00:00 Preparing metadata (setup.py) ... done Using cached ninja-1.11.1.2-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (422 kB) Building wheels for collected packages: flash-attn Building wheel for flash-attn (setup.py) ... done Created wheel for flash-attn: filename=flash_attn-2.7.2.post1-cp310-cp310-linux_x86_64.whl size=190160474 sha256=0b454d9e650bfc437cc71335080172a5d05f51eab355636c9d5b7321fec7318e Stored in directory: /root/.cache/pip/wheels/da/ec/5b/b2c37a8e4f755ad82492a822463bca0817f0e0e11de874b550 Successfully built flash-attn Installing collected packages: ninja, flash-attn Successfully installed flash-attn-2.7.2.post1 ninja-1.11.1.2 モデルのロード 以下のコードでモデルを読み込みます。 受講生の方からご指摘頂いたのですが、unslothでgemma2を読み込むと、自動でunslothが作成した非公式モデルがダウンロードされるようです。 対処方法がわからない受講生はLLM-jp-3のみをご利用ください!
[ ]
#HF_TOKEN = "" #@param {type:"string"}
#from google.colab import userdata HF_TOKEN=userdata.get('HF_TOKEN') 修正したコード 修正内容:max_seq_lengthを512から1024へ
[ ]
from unsloth import FastLanguageModel import torch max_seq_length = 1024 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能 dtype = None # Noneにしておけば自動で設定 load_in_4bit = True # 今回は13Bモデルを扱うためTrue
model_id = "llm-jp/llm-jp-3-13b" new_model_id = "llm-jp-3-13b-20241127-hatsukaze4-4-4" #Fine-Tuningしたモデルにつけたい名前、it: Instruction Tuning
model, tokenizer = FastLanguageModel.from_pretrained( model_name=model_id, dtype=dtype, load_in_4bit=load_in_4bit, trust_remote_code=True, )
model = FastLanguageModel.get_peft_model( model, r = 32, #8~128で設定 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 = True,#変更 loftq_config = None, max_seq_length = max_seq_length, )
[ ] #Z# 学習に用いるデータセットの指定
#from datasets import load_dataset
#dataset = load_dataset("json", data_files="/content/drive/MyDrive/Colab Notebooks/Student_LLM/input/ichikara-instruction-003-001-1.json")
[ ] from datasets import load_dataset
data_files = [ "/content/drive/MyDrive/Colab Notebooks/Student_LLM/input/ichikara-instruction-003-001-1.json", "/content/drive/MyDrive/Colab Notebooks/Student_LLM/input/ichikara-instruction-003-002-1(-3479).json" ]
dataset = load_dataset("json", data_files=data_files)
prompt = """### 指示 {}
{}"""
EOS_TOKEN = tokenizer.eos_token
def formatting_prompts_func(examples): input_text = examples["text"] # 入力データ output_text = examples["output"] # 出力データ # プロンプトの作成 formatted_text = prompt.format(input_text, output_text) + EOS_TOKEN # 新しいフィールド "formatted_text" を返す return {"formatted_text": formatted_text}
dataset = dataset.map( formatting_prompts_func, num_proc=4 # 並列処理数を指定 )
print(dataset)
[ ]
print(dataset["train"]["formatted_text"][3])
言葉の単位には、小さいものから順に「単語」→「文節」→「文」→「段落」→「文章」があります。 この5つの単位の違いを説明しなさい。
日本語において、「言葉の単位」は5つあります。 1つずつ見ていくと、 ・文章・・・1冊の本、1編の論文、1件のレポートなどはそれ全体で1つの文章ということになります。「言葉の単位」で最大の単位です。
・段落・・・「文章」を意味内容で区切ったひとまとまりのことを指します。日本語では、1字下げ(段落の先頭を1文字空ける)のルールがあります。
・文・・・句点「。」によって区切られるひと続きの言葉のことを言い、必ず文の終わりには「。」を付けます。
・文節・・・文を「意味の通じる最小の単位」まで区切ったものをいいます。 文:自分で薪を割れ、二重に温まる。 文節分け:自分で / 薪を / 割れ、 / 二重に / 温まる。/
・単語・・・文節をさらに区切って、もうこれ以上分けることができない「言葉の単位として最小の単位」です。 単語分け:自分 / で / 薪 / を / 割れ、/ 二重 / に / 温まる。/
となります。</s> 修正したコード 修正内容:wandb設定、TrainingArgumentsパラメータ修正
[ ] """ training_arguments: 学習の設定
output_dir: -トレーニング後のモデルを保存するディレクトリ
per_device_train_batch_size:
per_device_eval_batch_size:
gradient_accumulation_steps:
optim:
num_train_epochs:
eval_strategy:
eval_steps:
logging_strategy:
logging_steps:
warmup_steps:
save_steps:
save_total_limit:
max_steps:
learning_rate:
fp16:
bf16:
group_by_length:
report_to:
trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset=dataset["train"],# max_seq_length = max_seq_length, dataset_text_field="formatted_text", packing = False, neftune_noise_alpha = 5,#NEFTune設定 args = TrainingArguments( per_device_train_batch_size = 8,# gradient_accumulation_steps = 4,# num_train_epochs = 3,# logging_steps = 10, weight_decay = 0.01, warmup_ratio = 0.05, #warmup_steps = 100, optim = "adamw_torch_fused", save_steps = 100, save_total_limit = 2, max_steps = -1, learning_rate = 2e-4,# lr_scheduler_type = 'cosine', max_grad_norm = 1.0, fp16 = False, bf16 = True, group_by_length = True,#FalseからTrueへ seed = 3407, output_dir = "outputs",# report_to = "wandb", evaluation_strategy = 'no',# #eval_steps = 50, auto_find_batch_size = False,#追加 ), )
現在のメモリ使用量を表示
[ ] #@title 現在のメモリ使用量を表示 gpu_stats = torch.cuda.get_device_properties(0) start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3) max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3) print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.") print(f"{start_gpu_memory} GB of memory reserved.") GPU = NVIDIA A100-SXM4-40GB. Max memory = 39.564 GB. 8.709 GB of memory reserved. 学習実行
[ ] #@title 学習実行 model.config.use_cache = False trainer_stats = trainer.train() model.config.use_cache = True
[ ]
elyza_dataset = load_dataset("elyza/ELYZA-tasks-100")
def formatting_prompts_func_elyza(examples): input_text = examples["input"] # ELYZA データセットの 'input' フィールド output_text = examples["output"] # ELYZA データセットの 'output' フィールド text = prompt.format(input_text, output_text) + EOS_TOKEN # プロンプトの作成 return {"formatted_text": text} # 新しいフィールド "formatted_text" を返す
elyza_dataset = elyza_dataset["test"].map( formatting_prompts_func_elyza, num_proc=4, # 並列処理数を指定 )
elyza_dataset
[ ]
trainer_elyza = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset=elyza_dataset,# max_seq_length = max_seq_length, dataset_text_field="formatted_text", packing = False, neftune_noise_alpha = 5,#NEFTune設定 args = TrainingArguments( per_device_train_batch_size = 2,# gradient_accumulation_steps = 4,# num_train_epochs = 5,# logging_steps = 5, weight_decay = 0.01, warmup_ratio = 0.05, #warmup_steps = 100, optim = "adamw_torch_fused", save_steps = 10, save_total_limit = 2, max_steps = -1, learning_rate = 2e-4,# lr_scheduler_type = 'cosine', max_grad_norm = 1.0, fp16 = False, bf16 = True, group_by_length = True,#FalseからTrueへ seed = 3407, output_dir = "outputs",# report_to = "wandb", evaluation_strategy = 'no',# #eval_steps = 50, auto_find_batch_size = False,#追加 ), )
[ ] model.config.use_cache = False trainer_stats_elyza = trainer_elyza.train() model.config.use_cache = True
[ ]
import json datasets = [] with open("/content/drive/MyDrive/Colab Notebooks/Student_LLM/input/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 = "" 修正したコード 修正内容:max_new_tokensを512から1024へ
[ ]
from tqdm import tqdm
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 = 1024, 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}) 100%|██████████| 100/100 [14:31<00:00, 8.72s/it] 修正したコード 修正内容:google colab pro+用、jsonファイル保存場所のdriveへの変更
[ ]
with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f: for result in results: json.dump(result, f, ensure_ascii=False) f.write('\n')
save_dir = '/content/drive/MyDrive/Colab Notebooks/Student_LLM/output/'
file_path = f"{save_dir}{new_model_id}_output.jsonl"
with open(file_path, 'w', encoding='utf-8') as f: for result in results: json.dump(result, f, ensure_ascii=False) f.write('\n') モデルとトークナイザーをHugging Faceにアップロードします。 本コードではLoRAのアダブタのみを保存します。 このアダプタを用いた推論方法はModel_Inference_Template_unsloth_20241127.ipynbをご参照ください。
一旦privateでアップロードしてください。 https://docs.unsloth.ai/basics/saving-and-using-models
[ ]
model.push_to_hub_merged( new_model_id+"_lora", tokenizer=tokenizer, save_method="lora", token=HF_TOKEN, private=True ) 修正したコード 修正内容:google colab pro+用、終了後の自動ランタイム削除
[ ]
runtime.unassign() Colab の有料サービス - 契約解除はこちら
データセット使用させていただきました。有難うございました。 https://liat-aip.sakura.ne.jp/wp/llmのための日本語インストラクションデータ作成/llmのための日本語インストラクションデータ-公開/
関根聡, 安藤まや, 後藤美知子, 鈴木久美, 河原大輔, 井之上直也, 乾健太郎. ichikara-instruction: LLMのための日本語インストラクションデータの構築. 言語処理学会第30回年次大会(2024)