WaytoAGI 飛書ナレッジベースへ · 1 億+ 回のアクセス、誰でも利用できます →
WaytoAGI

ナレッジベース · 学習ロードマップ

WaytoAGI InternVL3-8B ローカル導入完全ガイド(RTX 50シリーズ対応)

書生浦語の最新マルチモーダル大規模言語モデルInternVL3-8BをWindows環境にローカルで導入する方法を詳しく解説します。RTX 50シリーズのグラフィックカードに完全対応しており、PyTorch cu128の環境構築、モデルのダウンロード、依存関係のインストールから対話型テストスクリプトの実行まで、初めての方でも簡単に進められます。WaytoAGIで最新のマルチモーダルAIを自分のPCで体験しましょう。

InternVL3ローカル導入多モーダルモデルRTX50PyTorch cu128

AI により中国語から翻訳されています。問題があればフィードバックボタンからお知らせください。

著者:二師兄

事前に必要なソフトウェア:nodejsとpython

必須ソフトウェア:vscode、trae、cursorのいずれでも可

  1. プロジェクト用にtrain_and_deployフォルダーを作成します(名前は自由に変更できます)

  2. dataフォルダーを新規作成し、その中にtest.jpgという名前でテスト画像を1枚配置します

  3. モデルをダウンロードします。保存先の例:F:\train_and_deploy\models

https://internvl.github.io/blog/2025-04-11-InternVL-3.0/ から、使用環境に合ったサイズのモデルをダウンロードします。HFまたはModelScope(魔搭)を選び、linkをクリックするとモデルのダウンロードページに移動できます

以下では8bを例に説明します

  1. vscodeなどのIDEツールで、rain_and_deployフォルダーを開きます

  2. 環境を新規作成します:

python
conda create -n internvl3 python=3.10
  1. 環境を有効化します
python
conda activate internvl3
  1. 依存パッケージをインストールします
  • pytorchとcudaのインストールが必要です。https://pytorch.org/

  • 自分のハードウェアに適したバージョンを選びます。50シリーズのグラフィックスカードでは、2.7.0とcuda128を使用できます

  • ターミナルのコマンドラインに以下のコマンドを入力してインストールします
python
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128

  • transformersをインストールします
python
pip install transformers
  1. まずは簡単な対話ができるように、シンプルな対話インターフェースを作成します
  • train_and_deployフォルダーにtest_internvl3.pyを新規作成します

  • 以下のコードを貼り付けます。モデルのパスとテスト画像のパスを忘れずに変更してください

python

# test_internvl3.py - InternVL3-8Bモデルの簡易テストスクリプト

import os
import argparse
from PIL import Image
import torch
import torchvision.transforms as transforms
from transformers import AutoTokenizer, AutoModel
import time

def parse_args():
    parser = argparse.ArgumentParser(description="InternVL3-8Bモデルの対話型テスト")
    parser.add_argument("--model_path", type=str, default="F:/train_and_deploy/models/InternVL3-8B",
                        help="モデルのパス。デフォルトはF:/train_and_deploy/models/InternVL3-8B")
    parser.add_argument("--image", type=str, default="data/test.jpg",
                        help="テスト画像のパス。デフォルトはdata/test.jpg")
    parser.add_argument("--device", type=str, default="cuda",
                        help="実行デバイス。デフォルトはcuda")
    return parser.parse_args()

def main():
    args = parse_args()
    
    # CUDAが利用可能か確認
    if args.device == "cuda" and not torch.cuda.is_available():
        print("CUDAが利用できないため、CPUに切り替えます")
        args.device = "cpu"
    
    # モデルを読み込む
    print(f"モデルを読み込み中: {args.model_path}")
    model = AutoModel.from_pretrained(
        args.model_path,
        torch_dtype=torch.bfloat16,  # BF16を使用するとメモリ消費を削減できます
        low_cpu_mem_usage=True,
        trust_remote_code=True
    ).to(args.device).eval()
    
    # トークナイザーを読み込む
    tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True)
    
    # 画像が存在することを確認
    if not os.path.exists(args.image):
        print(f"エラー: 画像 {args.image} が存在しません")
        return
    
    # 画像を読み込む
    print(f"画像を読み込み中: {args.image}")
    image = Image.open(args.image)
    if image.mode != "RGB":
        image = image.convert("RGB")
    
    # preprocessor_config.jsonに基づいて画像の前処理を構築
    image_processor = transforms.Compose([
        transforms.Resize(448),  # preprocessor_config.jsonから取得したサイズ
        transforms.CenterCrop(448),  # preprocessor_config.jsonから取得したサイズ
        transforms.ToTensor(),
        transforms.Normalize(
            mean=[0.485, 0.456, 0.406],  # preprocessor_config.jsonから取得した正規化パラメータ
            std=[0.229, 0.224, 0.225]  # preprocessor_config.jsonから取得した正規化パラメータ
        )
    ])
    
    # 画像を処理
    with torch.no_grad():
        # 前処理を適用
        pixel_values = image_processor(image).unsqueeze(0)
        
        # 画像をbfloat16型に変換し、モデルが期待する型に合わせる
        pixel_values = pixel_values.to(dtype=torch.bfloat16, device=args.device)
    
    # 対話型チャット
    history = []
    print("\n=== InternVL3-8B 対話型チャット ===")
    print("'exit'を入力するとチャットを終了します")
    print("'clear'を入力すると会話履歴を消去します\n")
    
    while True:
        question = input("質問: ")
        
        if question.lower() == 'exit':
            break
        elif question.lower() == 'clear':
            history = []
            print("会話履歴を消去しました")
            continue
        
        # 必要に応じて画像マーカーを追加
        if not history and '<image>' not in question:
            question = '<image>\n' + question
        
        try:
            print("モデルが思考中...")
            start_time = time.time()
            
            # 生成パラメータを設定
            generation_config = {
                "max_new_tokens": 1024,
                "do_sample": True,
                "temperature": 0.6,
                "top_p": 0.8,
            }
            
            # 回答を生成
            with torch.no_grad():
                # chatメソッドを使用
                response = model.chat(
                    tokenizer=tokenizer,
                    pixel_values=pixel_values,
                    question=question,
                    history=history,
                    generation_config=generation_config,
                    return_history=True,
                    verbose=False
                )
            
            # 履歴を更新
            history = response[1]
            end_time = time.time()
            
            # 回答を表示
            print(f"\n回答 (所要時間 {end_time - start_time:.2f}秒):")
            print(response[0])
            print("-" * 50)
            
        except Exception as e:
            print(f"エラー: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    main()
  • 保存後、ターミナルで次のコマンドを入力します:
python
python test_internvl3.py

正常に起動したら、質問を入力すると回答が得られます。

特定の画像を指定する場合は、次のように入力します(画像のパスを置き換えてください):

python
python test_internvl3.py --image あなたの画像パス.jpg


# 例:python test_internvl3.py --image  F:\train_and_deploy\data\images\marine\clownfish\クマノミ_2.jpg

  1. gradioのWebページを使用する:
  • gradioをインストールします
python
conda activate internvl3
pip install gradio
pip install opencv-python
  • gradio_web_demo.pyという名前のPythonファイルを新規作成します

  • このPythonファイルを開いてコードをコピーします。モデルのパスを忘れずに置き換えてください

python
import gradio as gr
import torch
from PIL import Image
from transformers import AutoTokenizer, AutoModel
import torchvision.transforms as transforms


# モデルとトークナイザーを読み込む(高速化のため、読み込みは一度だけ行う)
MODEL_PATH = "F:/train_and_deploy/models/InternVL3-8B"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
model = AutoModel.from_pretrained(
    MODEL_PATH,
    torch_dtype=torch.bfloat16,
    low_cpu_mem_usage=True,
    trust_remote_code=True
).to(DEVICE).eval()

# 画像の前処理
image_processor = transforms.Compose([
    transforms.Resize(448),
    transforms.CenterCrop(448),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

def internvl3_chat(image, question, history=[]):
    # 画像の前処理
    with torch.no_grad():
        pixel_values = image_processor(image).unsqueeze(0).to(dtype=torch.bfloat16, device=DEVICE)
    # 質問に画像マーカーを追加
    if not history and '<image>' not in question:
        question = '<image>\n' + question
    # 生成設定
    generation_config = {
        "max_new_tokens": 1024,
        "do_sample": True,
        "temperature": 0.6,
        "top_p": 0.8,
    }
    # 推論
    with torch.no_grad():
        response = model.chat(
            tokenizer=tokenizer,
            pixel_values=pixel_values,
            question=question,
            history=history,
            generation_config=generation_config,
            return_history=True,
            verbose=False
        )
    answer, new_history = response
    return answer, new_history

# Gradioインターフェース
with gr.Blocks() as demo:
    gr.Markdown("# InternVL3-8B Web Demo")
    with gr.Row():
        with gr.Column():
            image_input = gr.Image(type="pil", label="画像をアップロード")
            question_input = gr.Textbox(label="質問を入力してください", placeholder="例:この画像の内容を説明してください")
            submit_btn = gr.Button("送信")
        with gr.Column():
            answer_output = gr.Textbox(label="モデルの回答")
    state = gr.State([])  # 会話履歴を保存するために使用

    def on_submit(image, question, history):
        answer, new_history = internvl3_chat(image, question, history)
        return answer, new_history

    submit_btn.click(
        on_submit,
        inputs=[image_input, question_input, state],
        outputs=[answer_output, state]
    )

demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
  • ターミナルでpyファイルを実行します
python
python gradio_web_demo.py

ブラウザで127.0.0.7860を開きます