⚾

結局マルチモーダルAIって何?[実装編]

に公開
2025/11/28

はじめに

この記事は以下の記事の続編です。
https://zenn.dev/dxclab/articles/048cbfe84150d2
前回の記事ではマルチモーダルAIが何か、どのような仕組みなのかについて説明しました。
今回は前回説明したものを使ってマルチモーダルRAGを実装してみます。

使用するもの

今回使用するツール、ライブラリは以下です。

  • open_clip (CLIPの学習済みモデルが公開されている)
  • transformers (BLIPの学習済みモデルが公開されている)
  • Pytorch (CLIPもBLIPもPytorchベースで書かれている)
  • Chromadb (ベクトルデータベースとして採用)
  • sentence_transformers
  • デバイス (CPU)

使用した画像

今回は以下のスポーツ選手の画像をローカルのdatasetディレクトリに保存します。
それぞれsho.jpg , gita.jpg , Lebron.jpg , Giannis.jpg , messi.jpg , neymer.png の名前で保存します。

  • 大谷翔平選手(ロサンゼルスドジャーズ・野球)
  • 柳田悠岐選手(福岡ソフトバンクホークス・野球)
  • レブロンジェームス選手(ロサンゼルスレイカーズ・バスケットボール)
  • ヤニスアデトクンボ選手(ミルウォーキー・バックス・バスケットボール)
  • リオネルメッシ選手(インテル・マイアミCF・サッカー)
  • ネイマールジュニア選手(サントスFC・サッカー)

CLIPを使った画像検索

前回説明した通り、CLIPは入力された文字と類似度が高い画像を返してくれます。
これを利用して画像検索システムを作ってみます。

ベクトルデータベースに画像を挿入する

ローカルのdatabaseディレクトリに保存した画像を読み込んで、CLIPを使って画像をEncodeしてChromaに保存します。
これを関数でひとまとめにすると下のようなコードになります。

def create_collection(model: Any, preprocess: Any, device=config["device"]):
    os.makedirs(config["database_path"], exist_ok=True)
    client = chromadb.PersistentClient(path=config["database_path"])
    collection_name = "rag_image_collection"
    collection = client.get_or_create_collection(
        name=collection_name,
        metadata={"hnsw:space": "cosine"},
    )

    # dataset以下のディレクトリから画像を取得
    assets_dir = Path(__file__).parent / "dataset"
    image_files = list(assets_dir.glob("*.jpg")) + list(assets_dir.glob("*.png"))

    embeddings = []
    metadata = []
    ids = []  # 各データの一意ID(ファイル名)

    with torch.no_grad():
        for file in image_files:
            print(f" Processing : {file.name}")
            image = Image.open(file).convert("RGB")
            image_tensor = preprocess(image).unsqueeze(0).to(device)
            image_embedding = model.encode_image(image_tensor).cpu().numpy()[0]
            print(image_embedding.shape)

            embeddings.append(image_embedding)
            metadata.append(
                {
                    "image_path": str(file.absolute()),
                    "data_type": "image",
                }
            )
            ids.append(file.name)

    if embeddings:
        print(f"データの挿入をします : {len(embeddings)}件")
        collection.add(embeddings=embeddings, metadatas=metadata, ids=ids)
        print("--処理完了--")

画像検索で画像のパスを返して欲しいので、Embeddingしたデータと一緒に画像のパスをデータベースに保存します。
また、modelとpreprocessは後ほど定義します。

ベクトルデータベースから検索する

先ほど、画像をデータベースに挿入したので、検索する関数を作成します。先ほど定義したデータベースのパスとコレクション名を指定してデータベースを呼び出します。
次に、受け取ったqueryを同じモデルでEmbeddingして、それを基に画像を検索するようにします。
検索結果は類似度とファイルのパスを返すようにします。

def search_collection(model: Any, tokenizer: Any, query: str, device: str):
    client = chromadb.PersistentClient(path=config["database_path"])
    collection = client.get_collection(name="rag_image_collection")

    with torch.no_grad():
        text_tokens = tokenizer(query).to(device)
        query_embedding = model.encode_text(text_tokens).cpu().numpy()[0]
        results = collection.query(query_embeddings=[query_embedding], n_results=3)

        search_results = []
        if results["ids"] and results["ids"][0]:
            found_ids = results["ids"][0]
            found_metadatas = results["metadatas"][0]
            found_distances = results["distances"][0]

            for i in range(len(found_ids)):
                image_path = (
                    found_metadatas[i].get("image_path") if found_metadatas[i] else None
                )
                search_results.append(
                    {
                        "id": found_ids[i],
                        "image_path": image_path,
                        "distance": found_distances[i],
                    }
                )
    return search_results

LLMが回答を生成するようにする

ベクトルデータベースから検索した結果のsearch_resultを受け取ってqueryを基に返事を返してもらうようにします。

def generate_answer(query: str, search_result: list[Any]):
    print("\n --回答生成中--")

    context = "検索された関連画像情報:\n"
    for i, result in enumerate(search_result, 1):
        context += f"{i}. 距離={result['distance']}, パス={result['image_path']}\n"

    prompt = f"""
    以下の画像情報を参考に、質問に答えてください。該当のimage_pathも教えてください。

    質問: {query}

    {context}

    回答:
    """

    response = llm.invoke(prompt)
    # ChatResultオブジェクトから本文を取得
    return response.content

メイン処理

これまで、作成した関数を使ってメインの処理をします。
model,preprocessはopen_clipで公開されている「'ViT-B-32'」を使用し、pretrainモデルは「'openai'」を使用します。

parser = argparse.ArgumentParser(description="マルチモーダルRAG with CLIP デモ")
parser.add_argument("--create", action="store_true", help="コレクションを作成して画像を登録")
parser.add_argument("--query", type=str, default="cat", help="検索クエリ(--search時に使用)")

args = parser.parse_args()


# モデル初期化
model, _, preprocess = open_clip.create_model_and_transforms(
    config["vision_model"], pretrained=config["pretrained"], device=config["device"]
)
tokenizer = open_clip.get_tokenizer(config["vision_model"])
model.eval()

# コレクション作成
if args.create:
    create_collection(model, preprocess, config["device"])

# 検索処理
search_results = search_collection(model, tokenizer, args.query, config["device"])
print("--検索結果--")
for result in search_results:
    print(f"  - 距離: {result['distance']}, パス: {result['image_path']}")

# 回答生成
if search_results:
    answer = generate_answer(args.query, search_results)
    print(f"\n 質問: {args.query}")
    print(f" 回答: {answer}")
else:
    print(f"\n 質問: {args.query}")
    print(" 関連する結果が見つかりませんでした")

実行してみる

以上のコードをまとめてCLIP.pyに保存し、以下のコマンドで実行します。

uv run CLIP.py --query "Is there a baseball player?"

実行すると以下のように、クエリーと類似度の高い画像とそれのパスが表示されます。

では、ここで実際にはディレクトリ内にないテニス選手がいるかを聞いてみます。

uv run CLIP.py --query "Is there a tennis player?"

実行すると実際にはテニス選手がいないにも関わらずテニス選手がいることになっています。
クエリーと最も距離が近い画像が選ばれているので、実際がどうかに関わらず結果を答えてしまっているようです。

BLIPを使った画像検索

BLIPもCLIPのコードとほとんど同じですが、CLIPと異なるのはCLIPが画像をEncodeして保存するのに対して、BLIPは画像にキャプションをつけて、そのキャプションをEmbeddingしてデータベースに保存する点です。

ベクトルデータベースにキャプションを挿入する

CLIPの時と同様にChromaデータベースにデータを保存します。BLIPを使って画像からキャプションを生成し、それと一緒に画像ファイルのディレクトリも保存します。

def create_collection(embedding_model:Any,preprocess:Any,blip_model:Any):
    client = chromadb.PersistentClient(path = "./database/BLIP")
    collection_name = "BLIP_collection" 
    collection = client.get_or_create_collection(name = collection_name)

    image_dir = Path(__file__).parent / "dataset"
    image_file = list(image_dir.glob("*.jpg")) + list(image_dir.glob("*.png"))

    embeddings = []
    metadata=[]
    ids =[]

    for file in image_file:
        print(f"Processing: {file.name}")
        image = Image.open(file).convert("RGB")
        image_tensor = preprocess(image,return_tensors="pt").to(config["device"])
        out = blip_model.generate(**image_tensor)
        caption = preprocess.decode(out[0],skip_special_tokens=True)
        caption_embeddings = embedding_model.encode(caption).tolist()

        embeddings.append(caption_embeddings)
        metadata.append({
            "image_path":str(file.absolute()),
            "document":caption
        })
        ids.append(file.name)

    if embeddings:
        print(f"データの挿入をします : {len(embeddings)}件")
        collection.add(embeddings=embeddings, metadatas=metadata, ids=ids)
        print("--処理完了--")

ベクトルデータベースから検索する

ここの箇所はCLIPのものとほとんど変わりません

def search_collection(embedding_model:Any,query:Any):
    client = chromadb.PersistentClient(path="./database/BLIP")
    collection = client.get_collection(name = "BLIP_collection")


    query_embeddings = embedding_model.encode(query).tolist()
    result = collection.query(query_embeddings=[query_embeddings],n_results=3)
    search_results = []
    if result["ids"] and result["ids"][0]:
        found_ids = result["ids"][0]
        found_metadatas = result["metadatas"][0]

        for i in range(len(found_ids)):
            image_path = (
                found_metadatas[i].get("image_path") if  found_metadatas[i] else None
            )
            document =(
                found_metadatas[i].get("document") if found_metadatas[i] else None
            )
            search_results.append({
                "id":found_ids[i],
                "image_path": image_path,
                "document":document
            })
    return search_results

LLMが回答を生成するようにする

CLIPの場合と同様です。

    print("\n --回答生成中--")

    context = "検索されたもの:"
    for i,result in enumerate(search_result,1):
        context += f"{i},ドキュメント={result["document"]},パス={result["image_path"]}\n"

    prompt = f"""
    以下の画像情報を参考に、質問に答えてください。該当のimage_pathも教えてください。

    質問: {query}

    {context}

    回答:
    """

    response = llm.invoke(prompt)
    # ChatResultオブジェクトから本文を取得
    return response.content

メイン処理

CLIPの場合とほとんど同じですが、BLIPのモデルはSalesforceの「blip-image-captioning-base」を使用し、embeddingモデルには「all-MiniLM-L6-v2」を使用しています。

parser = argparse.ArgumentParser(description="マルチモーダルRAG with BLIP デモ")
parser.add_argument("--create", action="store_true", help="コレクションを作成して画像を登録")
parser.add_argument("--query", type=str, default="find images about baseball player", help="検索クエリ(--search時に使用)")

args = parser.parse_args()

model_id = "Salesforce/blip-image-captioning-base"
preprocess = BlipProcessor.from_pretrained(model_id)
blip_model = BlipForConditionalGeneration.from_pretrained(model_id).to(config['device'])
embedding_model = SentenceTransformer("all-MiniLM-L6-v2", device=config['device'])


if args.create:
    create_collection(embedding_model,preprocess,blip_model)
search_result = search_collection(embedding_model,args.query)

if search_result:
    final_answer = generate_answer(args.query,search_result)
    print(f"\n 質問: {args.query}")
    print(f" 回答: {final_answer}")

実行してみる

以上のコードをまとめて、BLIP.pyに保存して実行します

 uv run BLIP.py --query "find images about baseball player"

実行すると、画像のパスに加えて、キャプションをつけて答えてくれます

CLIPの時と同様にテニス選手がいるか聞いてみます。

 uv run CLIP.py --query "Is there a tennis player?"

実行するとCLIPの時と違ってテニス選手がいないときちんと答えてくれました。

CLIPとBLIPの比較

CLIPの限界

CLIPは、画像とテキストを比較してこのテキストは画像の内容をどの程度よく説明しているか? というスコア(類似度)を計算します。

「テニス選手」の質問への回答プロセス:

  1. クエリ:「テニス選手がいるか?」
  2. CLIPは、このクエリをベクトル化し、データベース内の全画像ベクトルと比較します。
  3. CLIPは、データベース内の「野球選手」や「バスケットボール選手」の画像が、他の無関係な画像よりもクエリの「スポーツ選手」という概念に最も近いと判断します。
  4. 最も距離が近い画像を返します。
  5. LLMは、テニス選手がいるか?という質問と、最も類似度が高い画像はSho.jpgであるという情報を受け取ります。
  6. そこでLLMは最も近いものを見つけた=質問に答えられると解釈し、その画像パスを指して肯定的に回答してしまいます。

BLIPの強み

BLIPはまず画像を野球選手やバスケットボール選手という確定したキャプションに変換し、それをベクトル化してデータベースに保存しています。

「テニス選手」の質問への回答プロセス:

  1. クエリ:「テニス選手がいるか?」
  2. 検索プロセスは、このクエリとデータベース内の野球選手、バスケットボール選手といったキャプションベクトルを比較します。
  3. 野球やバスケットボールは、テニスとは別のスポーツであるため、類似度(距離)はCLIPの画像ベクトル検索の時よりも低くなります。
  4. LLMは、検索結果のコンテキストを見て、テニス選手という情報を持つ画像は、データベースから見つからなかったと正しく推論し、否定的に回答します。

さいごに

CLIPとBLIPを用いて、マルチモーダルAIを実装してみました。近年の技術の発展のスピードはとんでもなく早く、気が付かない間に新しい技術がどんどん盛り込まれていくので、トレンドに乗りつつもその技術がどのようにして成り立っているのかは継続的にキャッチアップしていこうと思います。

DXC Lab

Discussion