Downloads · 30 days
0
malcoln/llm-jp-3-13b-it
llm-jp-3-13b-it is a machine learning model from malcoln. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
"""LoRAtemplateunsloth2.ipynb のコピー20241215
Downloads · 30 days
0
Access
Public
Updated Dec 16, 2024
Repo size
3.5 GB
Likes
0
Public
Click a slice to open those files.
.safetensors501 MB · 99%
From the Hugging Face model README
"""LoRA_template_unsloth2.ipynb のコピー_20241215
Automatically generated by Colab.
Original file is located at https://colab.research.google.com/drive/1yHYpESP_kCA0nh-fwvPOcwj3DOp2G1eI
最終課題コンペにて Fine-tuning を行ないたい方に向けの Fine-tuning コードです。
Unsloth を使うことで Google Colab の無料で利用可能な T4 でも動作可能になっています。
環境設定の難易度が高いので、慎重に取り組んでいただければと思います。
事前にterminalで環境構築の必要があります。Google Colabでは不要です。
# conda環境の構築
wget "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh"
# このコマンドではいくつか質問があるので答えて下さい。おそらくインストール先のデフォルトは/root/miniforge3かと思います
bash Miniforge3-$(uname)-$(uname -m).sh
# 以下、インストール先が/root/miniforge3であることを前提とします
export PATH=/root/miniforge3/bin:$PATH
conda init
# ここで一度、terminalを立ち上げ直す必要があります。
# 以下のリンク先に従い環境を作ります。
# https://docs.unsloth.ai/get-started/installation/conda-install
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
# jupyter notebook用のセットアップ。
conda install -c conda-forge ipykernel
python -m ipykernel install --user --name=unsloth_env --display-name "Python (unsloth_env)"
"""
!pip uninstall unsloth -y !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
from google.colab import drive drive.mount('/content/drive')
!pip install --upgrade torch !pip install --upgrade xformers
!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"
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig from unsloth import FastLanguageModel import torch max_seq_length = 512 # unslothではRoPEをサポートしているのでコンテキスト長は自由に設定可能 dtype = None # Noneにしておけば自動で設定 load_in_4bit = True # 今回は8Bクラスのモデルを扱うためTrue
model_id = "llm-jp/llm-jp-3-13b" new_model_id = "llm-jp-3-13b-it" #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, 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, )
HF_TOKEN = "" #@param {type:"string"}
from google.colab import output output.enable_custom_widget_manager()
"""Support for third party widgets will remain active for the duration of the session. To disable support:"""
from google.colab import output output.disable_custom_widget_manager()
from datasets import load_dataset
dataset = load_dataset("json", data_files="/content/ichikara-instruction-003-001-1.json")
prompt = """### 指示 {}
{}"""
""" formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる """ EOS_TOKEN = tokenizer.eos_token # トークナイザーのEOSトークン(文末トークン) def formatting_prompts_func(examples): input = examples["text"] # 入力データ output = examples["output"] # 出力データ text = prompt.format(input, output) + EOS_TOKEN # プロンプトの作成 return { "formatted_text" : text, } # 新しいフィールド "formatted_text" を返す pass
dataset = dataset.map( formatting_prompts_func, num_proc= 4, # 並列処理数を指定 )
dataset
print(dataset["train"]["formatted_text"][3])
""" 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, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, num_train_epochs = 1, logging_steps = 10, warmup_steps = 10, save_steps=100, save_total_limit=2, max_steps=-1, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), group_by_length=True, seed = 3407, output_dir = "outputs", report_to = "none", ), )
#@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.")
#@title 学習実行 trainer_stats = trainer.train()
import json 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 = ""
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 = 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})
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')
model.push_to_hub_merged( new_model_id, tokenizer=tokenizer, save_method="lora", token=HF_TOKEN, private=True )
import jupyter_beeper b = jupyter_beeper.Beeper() for _ in range(4): b.beep(frequency=10, secs=0.1, blocking=True) b.beep(frequency=1000, secs=1.5, blocking=True) b.beep(frequency=1250, secs=0.3, blocking=True) b.beep(frequency=1500, secs=0.3, blocking=True) b.beep(frequency=2000, secs=2.0, blocking=True)