Uploaded model

  • Developed by: Naoto24
  • License: apache-2.0
  • Finetuned from model : llm-jp/llm-jp-3-13b

This llama model was trained 2x faster with Unsloth and Huggingface's TRL library.

Google Colab の堎合は䞊蚘の環境構築手順を行なわず、単にこのセルから実行しおいっおください。

!pip uninstall unsloth -y !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"

Google Colab のデフォルトで入っおいるパッケヌゞをアップグレヌドMoriyasu さんありがずうございたす

!pip install --upgrade torch !pip install --upgrade xformers

notebookでむンタラクティブな衚瀺を可胜ずするただし、うたく動かない堎合あり

!pip install ipywidgets --upgrade

Install Flash Attention 2 for softcapping support

import torch if torch.cuda.get_device_capability()[0] >= 8: !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"

llm-jp/llm-jp-3-13bを4bit量子化のqLoRA蚭定でロヌド。

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

FastLanguageModel むンスタンスを䜜成

model, tokenizer = FastLanguageModel.from_pretrained( model_name=model_id, dtype=dtype, load_in_4bit=load_in_4bit, trust_remote_code=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, )

Hugging Face Token を指定

䞋蚘の URL から Hugging Face Token を取埗できたすので䞋蚘の HF_TOKEN に入れおください。

https://huggingface.co/settings/tokens

HF_TOKEN = "Your token" #@param {type:"string"}

あるいは Google Colab シヌクレットを䜿う堎合、巊のサむドバヌより🔑マヌクをクリック

HF_TOKEN ずいう名前で Value に Hugging Face Token を入れおください。

ノヌトブックからのアクセスのトグルをオンにし、䞋蚘の二行のコヌドのコメントアりトを倖しおください。

from google.colab import userdata

HF_TOKEN=userdata.get('HF_TOKEN')

孊習に甚いるデヌタセットの指定

今回はLLM-jp の公開しおいる Ichikara Instruction を䜿いたす。デヌタにアクセスするためには申請が必芁ですので、䜿いたい方のみ申請をしおください。

Ichikara Instruciton を Hugging Face Hub にお公開するこずはお控えください。

䞋蚘のリンクから申請を終えた先に Google Drive があり、Distribution20241221_all ずいうフォルダごずダりンロヌドしおください。

今回は「ichikara-instruction-003-001-1.json」を䜿いたす。必芁であれば展開!unzip などし、デヌタセットのパスを適切に指定しおください。

omnicampusの開発環境では取埗したデヌタを巊偎にドラッグアンドドロップしおお䜿いください。

Google Colab の堎合も巊のサむドバヌよりドラッグ&ドロップでアップデヌトしおください。

https://liat-aip.sakura.ne.jp/wp/llmのための日本語むンストラクションデヌタ䜜成/llmのための日本語むンストラクションデヌタ-公開/

関根聡, 安藀たや, 埌藀矎知子, 鈎朚久矎, 河原倧茔, 井之䞊盎也, 也健倪郎. ichikara-instruction: LLMのための日本語むンストラクションデヌタの構築. 蚀語凊理孊䌚第30回幎次倧䌚(2024)

from datasets import load_dataset

dataset = load_dataset("json", data_files="/content/ichikara-instruction-003-001-1.json")

パスの指定にご泚意ください。アップロヌドしたファむルを右クリックし、「パスをコピヌ」をクリック、䞊蚘の data_files ず合臎しおいるこずをご確認ください。Omnicampus のディレクトリ構造ずは異なるかもしれたせん。

孊習時のプロンプトフォヌマットの定矩

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:

    • 評䟡の戊略 ("no"/"steps"/"epoch")
  • eval_steps:

    • eval_strategyが"steps"のずき、評䟡を行うstep間隔
  • logging_strategy:

    • ログ蚘録の戊略
  • logging_steps:

    • ログを出力するステップ間隔
  • warmup_steps:

    • 孊習率のりォヌムアップステップ数
  • save_steps:

    • モデルを保存するステップ間隔
  • save_total_limit:

    • 保存しおおくcheckpointの数
  • max_steps:

    • トレヌニングの最倧ステップ数
  • learning_rate:

    • 孊習率
  • fp16:

    • 16bit浮動小数点の䜿甚蚭定第8回挔習を参考にするず良いです
  • bf16:

    • BFloat16の䜿甚蚭定
  • group_by_length:

    • 入力シヌケンスの長さによりバッチをグルヌプ化 (トレヌニングの効率化)
  • report_to:

    • ログの送信先 ("wandb"/"tensorboard"など) """ from trl import SFTTrainer from transformers import TrainingArguments from unsloth import is_bfloat16_supported

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()

ELYZA-tasks-100-TVの読み蟌み。事前にファむルをアップロヌドしおください

デヌタセットの読み蟌み。

omnicampusの開発環境では、巊にタスクのjsonlをドラッグアンドドロップしおから実行。

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})

jsonlで保存

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')

モデルずトヌクナむザヌをHugging Faceにアップロヌド。

䞀旊privateでアップロヌドしおください。

最終成果物が決たったらpublicにするようお願いしたす。

珟圚公開しおいるModel_Inference_Template.ipynbはunslothを想定しおいないためそのたたでは動かない可胜性がありたす。

model.push_to_hub_merged( new_model_id, tokenizer=tokenizer, save_method="lora", token=HF_TOKEN, private=True )

model.push_to_hub(new_model_id, token=HF_TOKEN, private=True) # Online saving

tokenizer.push_to_hub(new_model_id, token=HF_TOKEN) # Online saving

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 Naoto24/llm-jp-3-13b-it

Finetuned
(1122)
this model