勾配ブースティング決定木を用いた言語モデルの実装
このプロジェクトは、LightGBMを使用した言語モデルの学習データ生成パイプラインです。 従来のニューラルネットワークベースの言語モデルとは異なり、勾配ブースティング決定木を用いてテキスト生成を行います。
.
├── src/ # ソースコード
│ ├── gblm_data/ # データ処理モジュール
│ │ ├── __init__.py
│ │ ├── config.py # 設定管理
│ │ ├── corpus.py # コーパス読み込み
│ │ ├── vocab.py # 語彙構築
│ │ ├── tokenizer.py # トークナイザ
│ │ └── dataset.py # データセット生成
│ └── gblm_model/ # モデル学習・推論モジュール
│ ├── __init__.py
│ ├── config.py # モデル設定
│ ├── metrics.py # 評価指標
│ ├── train.py # 学習パイプライン
│ └── inference.py # 推論・テキスト生成
├── scripts/ # 実行スクリプト
│ ├── build_vocab.py # 語彙構築
│ ├── make_dataset.py # データセット生成
│ ├── train_gblm.py # モデル学習
│ ├── sample_gblm.py # テキスト生成
│ ├── chat_gblm.py # インタラクティブチャット
│ └── analyze_vocab_coverage.py # カバレッジ分析
├── data/ # データファイル
│ └── cleaned_merged_fairy_tales_without_eos.txt
├── artifacts/ # 生成ファイル
│ ├── vocab.json # 語彙(頻度ベース)
│ ├── vocab_coverage80.json # 語彙(80%カバレッジ)
│ ├── tokenizer.json # トークナイザ
│ ├── gblm_data.npz # 学習データ
│ ├── train.npz # 訓練データ
│ ├── val.npz # 検証データ
│ └── gblm_model.txt # 学習済みモデル
├── docs/ # ドキュメント
│ ├── gblm_gb_language_model_design.md
│ └── gblm_lightgbm_model_and_pipeline_design.md
├── tests/ # テストコード
│ ├── test_gblm_data.py # データ処理モジュールのテスト
│ ├── test_gblm_model.py # モデル学習・推論のテスト
│ └── test_scripts.py # スクリプトのインポートテスト
├── experiments/ # 実験用ディレクトリ
├── pyproject.toml # プロジェクト設定
├── pytest.ini # pytestの設定
└── README.md # このファイル
uv venv
source .venv/bin/activate # Linux/Mac
# または
.venv\Scripts\activate # Windowsuv pip install pandas numpyLightGBMとscikit-learnも必要です:
uv pip install lightgbm scikit-learnテスト用にpytestも必要です:
uv pip install pytestテキストコーパスから語彙を構築し、トークナイザを作成します。
python scripts/build_vocab.py \
--corpus data/cleaned_merged_fairy_tales_without_eos.txt \
--output-dir artifacts \
--min-freq 3 \
--top-k 3000 \
--verboseパラメータ:
--corpus: 入力テキストファイルのパス--output-dir: 出力ディレクトリ(デフォルト: artifacts)--min-freq: 語彙に含める最小出現頻度(デフォルト: 5)--top-k: 語彙サイズの上限(デフォルト: 5000)--lowercase: テキストを小文字化(デフォルト: True)--max-docs: 処理する最大ドキュメント数
構築したトークナイザを使用して、GBLM用の学習データを生成します。
python scripts/make_dataset.py \
--corpus data/cleaned_merged_fairy_tales_without_eos.txt \
--tokenizer artifacts/tokenizer.json \
--output-dir artifacts \
--context-length 16 \
--max-samples 100000 \
--split \
--verboseパラメータ:
--corpus: 入力テキストファイルのパス--tokenizer: トークナイザファイルのパス--context-length: コンテキストウィンドウサイズ(デフォルト: 16)--max-samples: 生成する最大サンプル数--split: 訓練/検証セットの分割を行う--val-ratio: 検証セットの割合(デフォルト: 0.1)--shuffle: サンプルをシャッフル(デフォルト: True)--seed: 乱数シード(デフォルト: 42)
LightGBMを使用してGBLMモデルを学習します。
python scripts/train_gblm.py \
--num-boost-round 500 \
--early-stopping-rounds 20 \
--learning-rate 0.05 \
--num-leaves 64主要パラメータ:
--num-boost-round: ブースティングラウンド数(デフォルト: 500)--early-stopping-rounds: 早期停止ラウンド数(デフォルト: 20)--learning-rate: 学習率(デフォルト: 0.1)--num-leaves: 決定木の葉の数(デフォルト: 64)--min-data-in-leaf: 葉の最小データ数(デフォルト: 20)
学習済みモデルを使用してテキストを生成します。
python scripts/sample_gblm.py \
--prompt "Once upon a time" \
--max-new-tokens 100 \
--sampling top_k \
--top-k 10 \
--temperature 0.8パラメータ:
--prompt: 生成開始テキスト--max-new-tokens: 生成する最大トークン数--sampling: サンプリング方法(greedy, top_k, top_p, temperature)--top-k: top-kサンプリングのk値--top-p: top-pサンプリングのp値--temperature: 温度パラメータ(低いほど決定的)
学習済みモデルを使用してインタラクティブなチャットセッションを開始します。
python scripts/chat_gblm.py \
--context-length 16 \
--max-new-tokens 32 \
--sampling top_k \
--top-k 16 \
--temperature 1.0主要機能:
- REPLループ: ユーザーの入力を受け取り、モデルの応答を生成
- ローリングコンテキストウィンドウ: 会話履歴を自動的に管理し、コンテキスト長を超えた場合は最新のトークンのみを保持
- 会話管理:
resetコマンドで会話をリセット可能 - 統計表示:
--show-statsフラグで会話統計を表示
使用例:
# 基本的な使用
python scripts/chat_gblm.py
# 統計情報付きで実行
python scripts/chat_gblm.py --show-stats
# カスタム設定で実行
python scripts/chat_gblm.py \
--context-length 16 \
--max-new-tokens 50 \
--sampling top_p \
--top-p 0.9 \
--temperature 0.8チャット内コマンド:
exit,quit,:q: チャットセッションを終了reset: 会話履歴をクリアして新しいセッションを開始Ctrl+CまたはCtrl+D: チャットを終了
パラメータ:
--context-length: コンテキストウィンドウサイズ(トレーニング時と同じ値を使用、デフォルト: 16)--max-new-tokens: 各ターンで生成する最大トークン数(デフォルト: 32)--sampling: サンプリング方法(greedy, top_k, top_p)--top-k: top-kサンプリングのk値(デフォルト: 16)--top-p: top-pサンプリングのp値(デフォルト: 0.9)--temperature: 温度パラメータ(デフォルト: 1.0)--show-stats: 各ターン後に会話統計を表示
生成されるデータセットは以下の形式です:
- X: shape=(N, L)のコンテキスト行列
- N: サンプル数
- L: コンテキスト長
- 各行は過去LトークンのトークンID
- y: shape=(N,)の次トークンID配列
from src.gblm_model.config import GBLMTrainConfig, PathsConfig, TrainSplitConfig, LightGBMConfig
from src.gblm_model.train import train_gblm
from pathlib import Path
# 設定
cfg = GBLMTrainConfig(
paths=PathsConfig(artifacts_dir=Path("artifacts")),
split=TrainSplitConfig(valid_size=0.1, shuffle=True),
lgbm=LightGBMConfig(
learning_rate=0.05,
num_leaves=64,
num_boost_round=500,
early_stopping_rounds=20
)
)
# 学習実行
booster, metrics = train_gblm(cfg)
print(f"Valid accuracy: {metrics['valid_accuracy']:.4f}")
print(f"Valid perplexity: {metrics['valid_perplexity']:.2f}")from src.gblm_model.inference import load_booster, generate_text
from src.gblm_model.train import load_tokenizer
from pathlib import Path
# モデルとトークナイザの読み込み
artifacts_dir = Path("artifacts")
tokenizer = load_tokenizer(artifacts_dir / "tokenizer.json")
booster = load_booster(artifacts_dir / "gblm_model.txt")
# テキスト生成
text = generate_text(
booster=booster,
tokenizer=tokenizer,
prompt="Once upon a time",
context_length=16,
max_new_tokens=100,
sampling="top_k",
top_k=10,
temperature=0.8
)
print(text)python scripts/build_vocab.py \
--corpus your_data.csv \
--is-csv \
--text-column "text" \
--output-dir artifacts各行または段落が1つのドキュメントとして扱われます。
JSONファイルで設定を管理することも可能です:
{
"vocab": {
"min_freq": 5,
"top_k": 5000,
"lowercase": true,
"max_docs": null
},
"dataset": {
"context_length": 16,
"max_samples": 200000,
"shuffle": true,
"random_seed": 42
},
"paths": {
"corpus_file": "data/corpus.txt",
"artifacts_dir": "artifacts",
"is_csv": false
}
}設定ファイルを使用する場合:
python scripts/build_vocab.py --config config.jsonvocab.json: 語彙リストと頻度情報tokenizer.json: トークナイザの設定と語彙マッピングgblm_data.npz: 全データセットtrain.npz,val.npz: 訓練/検証分割データgblm_model.txt: 学習済みLightGBMモデルgblm_train_metrics.json: 学習時の評価指標*_metadata.json: 各データセットのメタ情報build_stats.json,dataset_stats.json: 統計情報
全てのテストを実行:
pytest特定のモジュールのテストを実行:
pytest tests/test_gblm_data.py # データ処理のテスト
pytest tests/test_gblm_model.py # モデルのテスト
pytest tests/test_scripts.py # スクリプトのテスト詳細な出力を表示:
pytest -v-
test_gblm_data.py: データ処理モジュールの単体テスト
- コーパス読み込み
- 語彙構築
- トークナイゼーション
- データセット生成
- 設定管理
-
test_gblm_model.py: モデル学習・推論の単体テスト
- 設定クラス
- 評価指標計算
- 最小データでの学習
- テキスト生成
- 完全パイプラインテスト
-
test_scripts.py: CLIスクリプトのインポートテスト
- 全スクリプトがインポート可能か確認
- スクリプトの構造チェック
--max-docsで処理するドキュメント数を制限--max-samplesで生成サンプル数を制限--context-lengthを小さくする
--min-freqを下げる--top-kを増やす
- 依存パッケージが全てインストールされているか確認
- Python 3.8以上を使用しているか確認
PYTHONPATHにプロジェクトルートが含まれているか確認
MIT