規模言語モデル入門Ⅱ〜生成型LLMの実装と評価(2024)のソースコードを参考して作成します。
1LoRAチューニング¶
#!pip install transformers[ja,torch] datasets matplotlib japanize-matplotlib peft fugashi unidic-lite 1.1データセットの準備¶
from pprint import pprint
from datasets import load_dataset
# Hugging Face Hub上のllm-book/wrime-sentimentのリポジトリから
# データを読み込む
train_dataset = load_dataset("llm-book/wrime-sentiment", split="train")
valid_dataset = load_dataset("llm-book/wrime-sentiment", split="validation")
# pprintで見やすく表示する
pprint(train_dataset[0]){'datetime': '2012/7/31 23:48',
'label': 1,
'sentence': 'ぼけっとしてたらこんな時間。チャリあるから食べにでたいのに…',
'user_id': 1}
pprint(train_dataset.features)
{'datetime': Value(dtype='string', id=None),
'label': ClassLabel(names=['positive', 'negative'], id=None),
'sentence': Value(dtype='string', id=None),
'user_id': Value(dtype='int64', id=None)}
1.2トークナイザ¶
from transformers import AutoTokenizer
# Hugging Face Hub上のモデル名を指定
model_name = "cl-tohoku/bert-base-japanese-v3"
# モデル名からトークナイザを読み込む
tokenizer = AutoTokenizer.from_pretrained(model_name)
# トークナイザのクラス名を確認
print(type(tokenizer).__name__)BertJapaneseTokenizer
/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/transformers/tokenization_utils_base.py:1617: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be deprecated in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884
warnings.warn(
encoded_input = tokenizer("これはテストです。")
pprint(encoded_input){'attention_mask': [1, 1, 1, 1, 1, 1, 1],
'input_ids': [2, 12538, 465, 14985, 13037, 385, 3],
'token_type_ids': [0, 0, 0, 0, 0, 0, 0]}
tokenizer.convert_ids_to_tokens(encoded_input["input_ids"])['[CLS]', 'これ', 'は', 'テスト', 'です', '。', '[SEP]']1.3データセット統計の可視化¶
from collections import Counter
import japanize_matplotlib
import matplotlib.pyplot as plt
from datasets import Dataset
from tqdm import tqdm
plt.rcParams["font.size"] = 18 # 文字サイズを大きくする
def visualize_text_length(dataset: Dataset):
"""データセット中のテキストのトークン数の分布をグラフとして描画"""
# データセット中のテキストの長さを数える
length_counter = Counter()
for data in tqdm(dataset):
length = len(tokenizer.tokenize(data["sentence"]))
length_counter[length] += 1
# length_counterの値から棒グラフを描画する
plt.bar(length_counter.keys(), length_counter.values(), width=1.0)
plt.xlabel("トークン数")
plt.ylabel("事例数")
plt.show()
visualize_text_length(train_dataset)
visualize_text_length(valid_dataset)
100%|██████████| 20149/20149 [00:01<00:00, 14694.70it/s]

100%|██████████| 1608/1608 [00:00<00:00, 11939.01it/s]

def visualize_labels(dataset: Dataset):
"""データセット中のラベル分布をグラフとして描画"""
# データセット中のラベルの数を数える
label_counter = Counter()
for data in dataset:
label_id = data["label"]
label_name = dataset.features["label"].names[label_id]
label_counter[label_name] += 1
# label_counterを棒グラフとして描画する
plt.bar(label_counter.keys(), label_counter.values(), width=1.0)
plt.xlabel("ラベル")
plt.ylabel("事例数")
plt.show()
visualize_labels(train_dataset)
visualize_labels(valid_dataset)

1.4データセットの前処理¶
from transformers import BatchEncoding
def preprocess_text_classification(
example: dict[str, str | int]
) -> BatchEncoding:
"""文書分類の事例のテキストをトークナイズし、IDに変換"""
encoded_example = tokenizer(example["sentence"], max_length=512)
# モデルの入力引数である"labels"をキーとして格納する
encoded_example["labels"] = example["label"]
return encoded_example
encoded_train_dataset = train_dataset.map(
preprocess_text_classification,
remove_columns=train_dataset.column_names,
)
encoded_valid_dataset = valid_dataset.map(
preprocess_text_classification,
remove_columns=valid_dataset.column_names,
)Parameter 'function'=<function preprocess_text_classification at 0x7c1259c3f6a0> of the transform datasets.arrow_dataset.Dataset._map_single couldn't be hashed properly, a random hash was used instead. Make sure your transforms and parameters are serializable with pickle or dill for the dataset fingerprinting and caching to work. If you reuse this transform, the caching mechanism will consider it to be different from the previous calls and recompute everything. This warning is only showed once. Subsequent hashing failures won't be showed.
Loading...
Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=True` to explicitly truncate examples to max length. Defaulting to 'longest_first' truncation strategy. If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy more precisely by providing a specific strategy to `truncation`.
Loading...
1.5モデルの準備¶
from transformers import AutoModelForSequenceClassification, BitsAndBytesConfig
import bitsandbytes as bnb
import torch
compute_dtype = getattr(torch, "float16")
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=False,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=compute_dtype,
)
class_label = train_dataset.features["label"]
label2id = {label: id for id, label in enumerate(class_label.names)}
id2label = {id: label for id, label in enumerate(class_label.names)}
base_model = AutoModelForSequenceClassification.from_pretrained(
model_name,
num_labels=class_label.num_classes,
label2id=label2id, # ラベル名からIDへの対応を指定
id2label=id2label, # IDからラベル名への対応を指定
quantization_config=bnb_config
)
print(type(base_model).__name__)`low_cpu_mem_usage` was None, now set to True since model is quantized.
Some weights of BertForSequenceClassification were not initialized from the model checkpoint at cl-tohoku/bert-base-japanese-v3 and are newly initialized: ['classifier.bias', 'classifier.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
BertForSequenceClassification
import peft
peft_config = peft.LoraConfig(
task_type=peft.TaskType.SEQ_CLS, # モデルが解くタスクのタイプを指定
r=8, # 差分行列のランク
lora_alpha=32, # LoRA層の出力のスケールを調節するハイパーパラメータ
lora_dropout=0.1, # LoRA層に適用するドロップアウト
inference_mode=False, # 推論モードの設定(今回は学習時なのでFalse)
)
model = peft.get_peft_model(base_model, peft_config)
print(type(model).__name__)PeftModelForSequenceClassification
model.print_trainable_parameters()
trainable params: 296,450 || all params: 111,505,156 || trainable%: 0.2659
1.6ミニバッチ構築¶
#data_collator は、データの前処理を行うためのオブジェクトです。具体的には、バッチ処理の際に入力データのシーケンス長を揃えるために使用されます。
from transformers import DataCollatorWithPadding
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
batch_inputs = data_collator(encoded_train_dataset[0:4])
pprint({name: tensor.size() for name, tensor in batch_inputs.items()}){'attention_mask': torch.Size([4, 36]),
'input_ids': torch.Size([4, 36]),
'labels': torch.Size([4]),
'token_type_ids': torch.Size([4, 36])}
1.7訓練の実行¶
from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir="output_wrime_lora", # 結果の保存フォルダ
per_device_train_batch_size=32, # 訓練時のバッチサイズ
per_device_eval_batch_size=32, # 評価時のバッチサイズ
learning_rate=2e-4, # 学習率
lr_scheduler_type="linear", # 学習率スケジューラの種類
warmup_ratio=0.1, # 学習率のウォームアップの長さを指定
num_train_epochs=3, # エポック数
save_strategy="epoch", # チェックポイントの保存タイミング
logging_strategy="epoch", # ロギングのタイミング
evaluation_strategy="epoch", # 検証セットによる評価のタイミング
load_best_model_at_end=True, # 訓練後に開発セットで最良のモデルをロード
metric_for_best_model="accuracy", # 最良のモデルを決定する評価指標
fp16=True, # 自動混合精度演算の有効化
report_to="none", # 外部ツールへのログを無効化
)/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/transformers/training_args.py:1545: FutureWarning: `evaluation_strategy` is deprecated and will be removed in version 4.46 of 🤗 Transformers. Use `eval_strategy` instead
warnings.warn(
import numpy as np
def compute_accuracy(
eval_pred: tuple[np.ndarray, np.ndarray]
) -> dict[str, float]:
"""予測ラベルと正解ラベルから正解率を計算"""
predictions, labels = eval_pred
# predictionsは各ラベルについてのスコア
# 最もスコアの高いインデックスを予測ラベルとする
predictions = np.argmax(predictions, axis=1)
return {"accuracy": (predictions == labels).mean()}
from transformers import Trainer
trainer = Trainer(
model=model,
train_dataset=encoded_train_dataset,
eval_dataset=encoded_valid_dataset,
data_collator=data_collator,
args=training_args,
compute_metrics=compute_accuracy,
)
trainer.train()
/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/accelerate/accelerator.py:494: FutureWarning: `torch.cuda.amp.GradScaler(args...)` is deprecated. Please use `torch.amp.GradScaler('cuda', args...)` instead.
self.scaler = torch.cuda.amp.GradScaler(**kwargs)
/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/torch/nn/parallel/_functions.py:71: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.
warnings.warn(
Loading...
/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/torch/nn/parallel/_functions.py:71: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.
warnings.warn(
/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/torch/nn/parallel/_functions.py:71: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.
warnings.warn(
/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/torch/nn/parallel/_functions.py:71: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.
warnings.warn(
TrainOutput(global_step=945, training_loss=0.17979497354497354, metrics={'train_runtime': 169.1342, 'train_samples_per_second': 357.391, 'train_steps_per_second': 5.587, 'total_flos': 2988703002246600.0, 'train_loss': 0.17979497354497354, 'epoch': 3.0})1.8訓練後のモデルの評価¶
# 検証セットでモデルを評価
eval_metrics = trainer.evaluate(encoded_valid_dataset)
pprint(eval_metrics)/home/lvzeyu/anaconda3/envs/llm-ft/lib/python3.11/site-packages/torch/nn/parallel/_functions.py:71: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.
warnings.warn(
Loading...
{'epoch': 3.0,
'eval_accuracy': 0.9309701492537313,
'eval_loss': 0.17510245740413666,
'eval_runtime': 1.9986,
'eval_samples_per_second': 804.578,
'eval_steps_per_second': 13.009}