Tabula-8B言語モデルによるテーブルデータの予測

はじめに

今回は、テーブルデータの予測タスクを言語モデルで行う Tabula-8B を試してみました。

テーブルデータの予測といえば XGBoost や LightGBM などの勾配ブースティング手法が一般的ですが、Tabula-8B はテーブルデータの推論に特化して学習された言語モデルを使って予測を行います。

arxiv.org

Tabula-8Bとは

Tabula-8Bは、テーブルデータを入力とし、各種推論タスクを解くことを目的とした言語モデルです。データフレームの行情報を自然言語のテキストとしてシリアライズ(直列化)してモデルに与えることで、目的変数の予測を行います。

入力データの構造、ルールは以下のrtfmリポジトリの実装に従います。

github.com

テーブルデータの入力形式

データフレームの情報を言語モデルに入力するため、専用のシリアライザを利用してテキストのプロンプトを構築します。 推論の形式には、例示を与えない 0-shot と、いくつか例を示してから予測させる Few-shot の2パターンがあります。

0-shot の場合

予測したいデータの「指示+特徴量+質問」をつなげ、最後に <|endinput|> を置いてモデルの入力を止めます。モデルはこの直後に続く正解(天候など)を生成します。

Predict the weather_today ... (特徴量) ... What is the value of weather_today? ||Sunny||Partly Sunny||Cloudy||Partly Cloudy||Rain||<|endinput|>

Few-shot の場合

1件のデータ(ショット)は「指示+特徴量+質問」の後に正解が出力され、<|endcompletion|> という特殊なトークンで区切られます。 これをいくつか並べた後に、最後に予測したいデータの末尾を ... <|endinput|> で止めてモデルに入力します。

Predict the weather_today ... (例1の特徴量) ... <|endinput|>Partly Sunny<|endcompletion|>Predict the weather_today ... (例2の特徴量) ... <|endinput|>Sunny<|endcompletion|>Predict the weather_today ... (予測対象の特徴量) ... <|endinput|>

このように、予測したい目的変数とその候補となる選択肢、および各種特徴量をつなげた文字列として構築し、言語モデルに入力しています。

実行手順

実際に必要なリポジトリの準備から予測を実行するまでの手順を説明します。

準備とモデルのダウンロード

はじめに、予測用モジュールが含まれるリポジトリと、Tabula-8Bのモデルをクローンします。 以下の実行コマンドを用いて取得します。

git clone https://github.com/mlfoundations/rtfm.git git clone https://huggingface.co/mlfoundations/tabula-8b

Python 3.11 等の新しめの環境で実行する場合、リポジトリの requirements.txt をそのまま使うとバージョン制限によりエラーが発生することがあります。そのため、動作に必要な以下の最小限のライブラリを個別にインストールします。

torch
torchvision
torchaudio
transformers
accelerate
pandas

推論クラスの実装とモデルロード

Few-Shot での予測を容易にするため、推論環境用のクラスを用意します。

本来は rtfm リポジトリに含まれる予測クラスを利用したいところですが、ライブラリの依存関係(特定の Python 3.8 環境を想定している箇所など)により、新しい環境ではインポートエラーが発生する場合がありました。そのため、ここではリポジトリの実装から推論に必要なコア部分だけを抽出したクラスを作成しています。

import sys
import os
import pandas as pd
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig

# rtfmモジュールをパスに追加(先ほどcloneしたローカルのrtfmディレクトリを指定)
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "rtfm")))

try:
    from rtfm.serialization.serializers import BasicSerializerV2
    from rtfm.configs import SerializerConfig
    from rtfm.special_tokens import QA_SEP_TOKEN, EOC_TOKEN
except ImportError as e:
    raise ImportError(
        f"rtfmモジュールのインポートに失敗しました。詳細: {e}"
    )

class FewShotPredictor:
    """
    推論環境で使用するための、最小依存のFew-Shot予測ユーティリティクラス
    """
    def __init__(self, model_path: str, device: str = "auto", dtype="auto", quantization_config=None):
        print(f"モデル '{model_path}' をロードしています...")
        self.tokenizer = AutoTokenizer.from_pretrained(model_path)
        
        model_kwargs = {
            "pretrained_model_name_or_path": model_path,
            "device_map": device,
            "torch_dtype": dtype
        }
        
        if quantization_config is not None:
            model_kwargs["quantization_config"] = quantization_config
            
        self.model = AutoModelForCausalLM.from_pretrained(**model_kwargs)
        self.serializer = BasicSerializerV2(config=SerializerConfig())
        print("モデルのロードが完了しました。")
        
    def predict(
        self, 
        target_df: pd.DataFrame, 
        target_colname: str, 
        target_choices: list, 
        support_df: pd.DataFrame = None, 
        max_new_tokens: int = 20,
        verbose: bool = False
    ) -> str:
        prefix_text = f"Predict the {target_colname}"
        suffix_text = f"What is the value of {target_colname}?"
        
        few_shot_prompt = ""
        if support_df is not None and not support_df.empty:
            for i in range(len(support_df)):
                row_dict = support_df.iloc[i].copy().to_dict()
                label = str(row_dict.pop(target_colname, None))
                
                serialized_text = self.serializer(
                    row_dict,
                    prefix_text=prefix_text,
                    suffix_text=suffix_text,
                    choices=target_choices
                )
                shot_text = f"{serialized_text}{QA_SEP_TOKEN}{label}{EOC_TOKEN}"
                few_shot_prompt += shot_text
            
        target_dict = target_df.iloc[0].copy().to_dict()
        target_dict.pop(target_colname, None)
        
        target_serialized = self.serializer(
            target_dict,
            prefix_text=prefix_text,
            suffix_text=suffix_text,
            choices=target_choices
        )
        target_text = f"{target_serialized}{QA_SEP_TOKEN}"
        
        full_prompt = few_shot_prompt + target_text
        
        if verbose:
            print("========== LLM 入力プロンプト ==========")
            print(full_prompt)
            print("========================================")
        
        inputs = self.tokenizer(
            full_prompt, return_tensors="pt"
        ).to(self.model.device)
        
        with torch.no_grad():
            from rtfm.generation_utils import make_eoc_stopping_criterion
            stopping_criterion = make_eoc_stopping_criterion(inputs["input_ids"], self.tokenizer)
            outputs = self.model.generate(
                **inputs,
                max_new_tokens=max_new_tokens,
                pad_token_id=self.tokenizer.eos_token_id,
                stopping_criteria=[stopping_criterion]
            )
            
        generated_tokens = outputs[0][inputs["input_ids"].shape[1]:]
        prediction = self.tokenizer.decode(generated_tokens, skip_special_tokens=False).strip()
        
        if EOC_TOKEN in prediction:
            prediction = prediction.split(EOC_TOKEN)[0].strip()
            
        if "<|end_of_text|>" in prediction:
            prediction = prediction.split("<|end_of_text|>")[0].strip()
        if "<|eot_id|>" in prediction:
            prediction = prediction.split("<|eot_id|>")[0].strip()
            
        return prediction
# FewShotPredictorのロード
MODEL_PATH = "./tabula-8b"

predictor = FewShotPredictor(
    model_path=MODEL_PATH, 
    device="cuda"
)

カテゴリデータの予測

まずは天候などのカテゴリ変数を予測します。 あらかじめラベル付けされた過去のデータをサポートデータとして与え、Few-Shot形式で予測対象のデータを推論します。

実装した predict メソッドには以下の引数を指定します。

  • target_df: 予測したい対象のデータ(1行のDataFrame)
  • target_colname: 予測対象のカラム名
  • target_choices: 選択肢となるカテゴリのリスト。Tabula-8Bはこの中から回答を選びます。
  • support_df: Few-Shotの例として与える、正解ラベル付きの過去データ。
# 過去のデータ(1例)
# location: New York, temperature: 22, weather_today: Partly Sunny など

target_choices = ["Sunny", "Partly Sunny", "Cloudy", "Partly Cloudy", "Rain"]

prediction = predictor.predict(
    target_df=target_example,
    target_colname="weather_today",
    target_choices=target_choices,
    support_df=labeled_examples,
    verbose=True
)

print(prediction)

指定したターゲット行の特徴を捉え、「Sunny」などの正しいカテゴリがテキストとして生成されます。 提示した選択肢(target_choices)の中から、最も適切なものが生成結果として返ってくるのが特徴です。

連続値データの予測

物件の価格など、連続値のデータを予測する場合は、あらかじめ値の範囲をバケット化して離散的なカテゴリに変換する処理を行います。

ここでは、discretize_continuous_column を使って目的変数を指定した数(num_buckets)の範囲に分割しています。target_choices にはこの分割された範囲(例: "between 700.0 and 750.0" など)のリストを渡します。

その他の引数については、カテゴリデータの予測と同様です。

from rtfm.serialization.serialization_utils import discretize_continuous_column

# priceカラムを4つのバケットに分割
examples["price"] = discretize_continuous_column(examples["price"], num_buckets=4)
target_choices = examples["price"].unique().tolist()

prediction = predictor.predict(
    target_df=target_example,
    target_colname="price",
    target_choices=target_choices,
    support_df=labeled_examples,
    verbose=True
)

これにより、連続値の予測もカテゴリ分類と同様の手法でアプローチできるようになります。数値そのものを当てるのではなく「適切な範囲(バケット)を選ぶ」という形式に落とし込むことで、カテゴリ分類タスクに落とし込んでいます。

実行結果

カテゴリデータ予測では、与えられた特徴量をもとに正確に天候が予測されました。 また連続値予測においても、「between 700.0 and 750.0」や「greater than 850.0」などのように、離散化された範囲の文字列が予測結果として返ってきました。

少数のサポートラベルを与えるだけで、言語モデルがデータの傾向を推測し、適切な回答を出力できていることが確認できました。

おわりに

Tabula-8BとFew-Shotプロンプティングを利用したテーブルデータ予測について試しました。 表形式のデータテキストのシリアライズによって言語モデルで予測する試みは非常に興味深いです。