コンテンツにスキップ

DB統合型フェデレーテッド学習 - LLMタイプ別集約

[!NOTE] 最新の実装状況は 機能実装ステータス (Remaining Functionality) を参照してください。

実装ノート(アーティファクト): トレーニングスクリプトが出力する artifact_manifest.json と推奨CLIフラグについては docs/implementation/ARTIFACT_MANIFESTS.md を参照してください。

概要

EvoSpikeNetのフェデレーテッド学習は、データベースに保存されたLLMモデルのタイプに基づいて、自動的に最適な集約方法を選択します。

なぜタイプ別集約が必要か?

問題点

従来のFedAvg(Federated Averaging)では、すべてのモデルを均等に扱います。しかし、EvoSpikeNetの分散脳システムでは:

  1. 異なるLLMタイプが共存: Text, MultiModal, Vision, Audio
  2. 評価基準が異なる: テキストはパープレキシティ、視覚は物体検出精度
  3. モダリティ間の特性が違う: 音声はWER、マルチモーダルはモダリティバランス

解決策

LLMタイプ別に最適化された集約ロジックを適用することで:

  • ✅ 各タイプに適した評価指標で重み付け
  • ✅ DBからタイプ情報を自動取得
  • ✅ 高品質なモデルを優先的に集約

LLMタイプとDB連携

データベーススキーマ

class DataArtifact(Base):
    artifact_id = Column(UUID, primary_key=True)
    session_id = Column(UUID, ForeignKey("execution_sessions.session_id"))
    artifact_type = Column(String)  # 'model', 'log', etc.
    llm_type = Column(String)       # ★ここが重要!
    name = Column(String)
    data = Column(LargeBinary)
    file_path = Column(String)
    created_at = Column(DateTime)

LLMタイプの値

  • SpikingEvoTextLM - テキスト専用LLM
  • SpikingEvoMultiModalLM - マルチモーダルLLM
  • SpikingEvoVisionEncoder - 視覚エンコーダー
  • SpikingEvoAudioEncoder - 音声エンコーダー

タイプ別集約ロジック

1. SpikingEvoTextLM(テキストLLM)

# 評価指標
- perplexityパープレキシティ: 低いほど良い
- loss損失: 低いほど良い

# 重み付け計算
perplexity_score = 1.0 / (1.0 + log(perplexity))
loss_score = 1.0 / (1.0 + loss)
quality_score = (perplexity_score + loss_score) / 2

# 集約
adjusted_weight = num_examples × quality_score

特徴: パープレキシティと損失が低いモデルを優先

2. SpikingEvoMultiModalLM(マルチモーダルLLM)

# 評価指標
- text_accuracy: テキスト精度
- image_accuracy: 画像精度
- audio_accuracy: 音声精度

# モダリティバランス
modality_balance = min(text_acc, image_acc, audio_acc)
avg_accuracy = (text_acc + image_acc + audio_acc) / 3

# 重み付け(調和平均でバランス重視)
quality_score = 2 × modality_balance × avg_accuracy /
                (modality_balance + avg_accuracy)

# 集約
adjusted_weight = num_examples × quality_score

特徴: すべてのモダリティで均等に高性能なモデルを優先

3. SpikingEvoVisionEncoder(視覚エンコーダー)

# 評価指標
- object_detection_accuracy: 物体検出精度
- edge_detection_accuracy: エッジ検出精度
- image_classification_accuracy: 画像分類精度

# 重み付け
vision_score = 0.4 × object_detection_acc +
               0.3 × edge_detection_acc +
               0.3 × image_classification_acc

# 集約
adjusted_weight = num_examples × (1.0 + vision_score)

特徴: 物体検出を最優先、エッジ検出と分類も考慮

4. SpikingEvoAudioEncoder(音声エンコーダー)

# 評価指標
- speech_recognition_accuracy: 音声認識精度
- word_error_rate (WER): 単語誤り率低いほど良い
- noise_robustness: ノイズ耐性

# 重み付け
wer_score = 1.0 - min(wer, 1.0)
audio_score = 0.5 × speech_recognition_acc +
              0.3 × wer_score +
              0.2 × noise_robustness

# 集約
adjusted_weight = num_examples × (1.0 + audio_score)

特徴: 音声認識精度とWERを重視、ノイズ耐性も考慮

使用方法

1. DB統合型サーバーの起動

# 環境変数の設定
export DATABASE_URL="postgresql://user:password@localhost/evospikenet"

# サーバー起動(自動LLMタイプ検出)
python examples/run_fl_server_with_db.py \
    --strategy hybrid \
    --num-rounds 10 \
    --min-clients 3 \
    --use-type-based-aggregation

# 特定のLLMタイプのみ集約
python examples/run_fl_server_with_db.py \
    --strategy hybrid \
    --target-llm-type SpikingEvoTextLM \
    --use-type-based-aggregation

2. クライアント側の実装

import flwr as fl
try:
    from evospikenet.federated import EvoSpikeNetClient
except Exception:
    EvoSpikeNetClient = None

class MyClient(fl.client.NumPyClient):
    def fit(self, parameters, config):
        # 訓練処理
        # ...

        # メトリクスにLLMタイプを含める★重要★
        metrics = {
            'llm_type': 'SpikingEvoTextLM',  # ★ここでタイプを指定
            'loss': 0.05,
            'perplexity': 12.5,
            'accuracy': 0.94
        }

        # num_examples はクライアント実装に依存
        num_examples = 100
        return parameters, num_examples, metrics

# クライアント起動(ガード付き)
fl.client.start_numpy_client(
    server_address="localhost:8080",
    client=MyClient()
)

3. プログラムからの使用

try:
    from evospikenet.federated_strategy import create_db_integrated_strategy
except Exception:
    create_db_integrated_strategy = None

if create_db_integrated_strategy is not None:
    strategy = create_db_integrated_strategy(
        db_session_factory=SessionLocal,
        strategy_type="hybrid",
        target_llm_type="SpikingEvoMultiModalLM",
        use_type_based_aggregation=True,
        min_fit_clients=3
    )

    # Flowerサーバーを起動
    fl.server.start_server(
        server_address="0.0.0.0:8080",
        config=fl.server.ServerConfig(num_rounds=10),
        strategy=strategy
    )
else:
    print("create_db_integrated_strategy not available in this environment; ensure evospikenet.federated_strategy is installed.")

DBからモデルを取得

最新モデルの取得

# Example: fetch latest models from DB (guarded)
try:
    from evospikenet.db import get_latest_models_by_type
except Exception:
    get_latest_models_by_type = None

if get_latest_models_by_type is not None:
    models = get_latest_models_by_type(llm_type='SpikingEvoTextLM')
    for model_info in models:
        print(f"Model: {model_info['artifact_id']}")
        print(f"  Type: {model_info['llm_type']}")
        print(f"  Created: {model_info['created_at']}")
        print(f"  Session: {model_info['session_id']}")
else:
    print("DB helper get_latest_models_by_type not available; inspect evospikenet.db for DB utilities.")

モデルのロード

try:
    from evospikenet.federated_strategy import load_model_from_artifact
except Exception:
    load_model_from_artifact = None

if load_model_from_artifact is not None:
    artifact_id = "some-artifact-uuid"
    model = load_model_from_artifact(artifact_id)
    if model:
        print("Model loaded successfully:", getattr(model, 'artifact_id', None))
    else:
        print("Model not found or failed to load")
else:
    print("load_model_from_artifact not available; check evospikenet.federated_strategy.")

ケース2: マルチモーダルLLMの自動検出

# サーバー起動(LLMタイプ自動検出)
python examples/run_fl_server_with_db.py \
    --strategy hybrid \
    --num-rounds 10

# 出力例
[INFO] Round 1: Target LLM type = SpikingEvoMultiModalLM (auto-detected)
[DEBUG] MultiModal LLM client-1: balance=0.82, quality=0.875
[DEBUG] MultiModal LLM client-2: balance=0.91, quality=0.923
[INFO] Selected aggregator: client-2 (hybrid score: 0.945)

ケース3: 視覚エンコーダーの集約

# サーバー起動
python examples/run_fl_server_with_db.py \
    --target-llm-type SpikingEvoVisionEncoder \
    --strategy performance_based \
    --num-rounds 8

# 出力例
[INFO] Round 1: Target LLM type = SpikingEvoVisionEncoder
[DEBUG] Vision Encoder client-1: vision_score=0.789
[DEBUG] Vision Encoder client-2: vision_score=0.845
[INFO] Selected aggregator: client-2 (performance score: 0.912)

タイプ別集約の無効化

タイプ別集約を使用せず、標準FedAvgを使いたい場合:

python examples/run_fl_server_with_db.py \
    --no-type-based-aggregation \
    --strategy pfc_centric

ベストプラクティス

1. クライアント側

# ✅ 推奨: メトリクスに必ず llm_type を含める
metrics = {
    'llm_type': 'SpikingEvoTextLM',
    'loss': 0.05,
    'perplexity': 12.5,
    # タイプ固有のメトリクス
}

# ❌ 非推奨: llm_type がないと自動検出できない
metrics = {
    'loss': 0.05,
    'accuracy': 0.94
}

2. サーバー側

# ✅ 推奨: target_llm_type を明示的に指定
strategy = create_db_integrated_strategy(
    db_session_factory=SessionLocal,
    target_llm_type='SpikingEvoTextLM',  # 明示的に指定
    use_type_based_aggregation=True
)

# ⚠️ 注意: 自動検出は混在する場合に便利だが、予測が難しい
strategy = create_db_integrated_strategy(
    db_session_factory=SessionLocal,
    target_llm_type=None,  # 自動検出
    use_type_based_aggregation=True
)

3. メトリクスの命名規則

LLMタイプ 必須メトリクス オプションメトリクス
SpikingEvoTextLM perplexity, loss bleu_score, rouge_score
SpikingEvoMultiModalLM text_accuracy, image_accuracy, audio_accuracy cross_modal_coherence
SpikingEvoVisionEncoder object_detection_accuracy edge_detection_accuracy, accuracy
SpikingEvoAudioEncoder speech_recognition_accuracy, word_error_rate noise_robustness

トラブルシューティング

Q1: "No clients with target LLM type" エラー

原因: 指定したLLMタイプのクライアントが接続していない

解決策:

# target_llm_type を None にして自動検出
python examples/run_fl_server_with_db.py --target-llm-type None

Q2: メトリクスが反映されない

原因: クライアントから送信されるメトリクスにタイプ固有の情報がない

解決策:

# クライアント側でメトリクスを追加
metrics = {
    'llm_type': 'SpikingEvoTextLM',
    'perplexity': calculate_perplexity(),  # ★追加
    'loss': current_loss
}

Q3: DATABASE_URL エラー

原因: 環境変数が設定されていない

解決策:

export DATABASE_URL="postgresql://user:pass@localhost/evospikenet"
python examples/run_fl_server_with_db.py

まとめ

DB統合型フェデレーテッド学習により:

  1. 自動LLMタイプ検出: DBからタイプ情報を取得
  2. タイプ別最適化: 各LLMに適した集約ロジック
  3. 高品質モデル優先: メトリクスベースの重み付け
  4. 柔軟な設定: 自動検出と明示的指定の両方サポート

が実現されます。