This model is based on a model originally licensed under the Apache License 2.0, fine-tuned using a dataset licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC-BY-NC-SA 4.0).

As a result of the dataset's licensing terms, this model and any derived works are distributed under the CC-BY-NC-SA 4.0 license.

Please note that the Apache License 2.0 conditions apply to the base model, but the CC-BY-NC-SA 4.0 license restricts the commercial use of this fine-tuned version.

Uploaded model

  • Developed by: daichira
  • License: cc-by-nc-sa-4.0
  • Finetuned from model : llm-jp/llm-jp-3-13b

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

README.md

llm-jp-3-13b-finetune2

概要

このプロジェクトは、Hugging Face上で提供される言語モデルllm-jp/llm-jp-3-13bを基盤とし、LoRA (Low-Rank Adaptation) を使用して特定のデータセットで微調整を行ったモデルllm-jp-3-13b-finetune2を公開するものです。このREADMEは、元のコードを再現可能な形でセットアップ、トレーニング、推論の手順を示します。


前提条件

このプロジェクトを実行するには、以下の環境とツールが必要です:

  • Python 3.8以上
  • Google Colabまたはローカル環境 (GPU推奨)
  • Hugging Faceアクセストークン (HF_TOKEN)

セットアップ手順

1. ライブラリのインストール

Google Colabの場合、以下のコマンドを使用して必要なライブラリをインストールします:

!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
!pip install ipywidgets --upgrade

Flash Attention 2をサポートするために、以下をインストールします:

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

2. モデルとトークナイザーのロード

以下のコードを使用して、Hugging Faceからベースモデルをロードし、LoRAの設定を適用します:

from transformers import AutoModelForCausalLM, AutoTokenizer
from unsloth import FastLanguageModel

max_seq_length = 512
dtype = None
load_in_4bit = True
model_id = "llm-jp/llm-jp-3-13b"
new_model_id = "llm-jp-3-13b-finetune2"

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

データセットの準備

以下のコードでデータセットをロードし、フォーマットを適用します:

!pip install datasets
from datasets import load_dataset

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

prompt = """### 指示
{}
### 回答
{}"""
EOS_TOKEN = tokenizer.eos_token

def formatting_prompts_func(examples):
    input_text = examples["text"]
    output_text = examples["output"]
    return {"formatted_text": prompt.format(input_text, output_text) + EOS_TOKEN}

dataset = dataset.map(formatting_prompts_func, num_proc=4)

トレーニングの設定

以下の手順でトレーニングを設定します:

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",
    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,
        learning_rate=2e-4,
        fp16=not is_bfloat16_supported(),
        bf16=is_bfloat16_supported(),
        group_by_length=True,
        seed=3407,
        output_dir="outputs",
    ),
)

# 学習実行
torch.cuda.empty_cache()
trainer.train()

推論

以下のコードでトレーニング済みモデルを使用して推論を行います:

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
from tqdm import tqdm
import json

HF_TOKEN = "Your_token_Write権限"
model_name = "daichira/llm-jp-3-13b-finetune2"

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=False,
)

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    quantization_config=bnb_config,
    device_map="auto",
    token=HF_TOKEN
)

tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True, 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 = ""

results = []
for data in tqdm(datasets):
    input_text = data["input"]
    prompt = f"### 指示\n{input_text}\n### 回答\n"

    tokenized_input = tokenizer.encode(prompt, add_special_tokens=False, return_tensors="pt").to(model.device)
    with torch.no_grad():
        outputs = model.generate(
            tokenized_input,
            max_new_tokens=100,
            do_sample=False,
            repetition_penalty=1.2
        )[0]
    output = tokenizer.decode(outputs[tokenized_input.size(1):], skip_special_tokens=True)

    results.append({"task_id": data["task_id"], "input": input_text, "output": output})

import re
model_name = re.sub(".*/", "", model_name)
with open(f"./{model_name}-outputs.jsonl", 'w', encoding='utf-8') as f:
    for result in results:
        json.dump(result, f, ensure_ascii=False)
        f.write('\n')

注意事項

  • 本モデルは日本語専用で設計されています。
  • 再現性を確保するため、ランダムシードを固定しています (seed=3407)。
  • モデルのパラメータ量が大きいため、十分なGPUメモリを確保してください (推奨: 16GB以上)。

''''

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 daichira/llm-jp-3-13b-finetune2

Finetuned
(1124)
this model