8-7 Microsoft: Phi-4 モデル

学習目標

Pythonプログラムを使用してHugging FaceプラットフォームからFlorenceモデルをダウンロードし、マルチモーダル入力(テキスト、画像、音声)を使用してPhi-4に質問し、回答を取得します。

Phi-4とは?

Phi-4は、Microsoftが開発したマルチモーダルな大規模モデルで、テキスト、画像、音声を同時に理解できます。まるで「音声コマンドを理解する」AIの頭脳のようなものです。テキスト、写真、録音データを入力すると、指示に従って動作します。

Phi-4でできること

1. 画像理解:画像と質問を入力して回答を生成します。

2. 音声認識/翻訳:音声を入力してテキストに変換したり、特定の言語に翻訳したりします。

使い始めるには?

1. 以下は、Phi-4を使って画像の説明文、音声の文字起こし、翻訳を行うサンプルプログラムです。

import requests
import torch
import os
import io
from PIL import Image
import soundfile as sf
from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
from urllib.request import urlopen

# Define model path
model_path = "microsoft/Phi-4-multimodal-instruct"

# Load model and processor
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_path, 
    device_map="cuda", 
    torch_dtype="auto", 
    trust_remote_code=True, 
    attn_implementation='flash_attention_2',
    cache_dir="./model",
).cuda()

# Load generation config
generation_config = GenerationConfig.from_pretrained(model_path, cache_dir="./model")

# Define prompt structure
user_prompt = '<|user|>'
assistant_prompt = '<|assistant|>'
prompt_suffix = '<|end|>'

# Part 1: Image Processing
print("\n--- IMAGE PROCESSING ---")
image_url = 'https://www.ilankelman.org/stopsigns/australia.jpg'
prompt = f'{user_prompt}<|image_1|>What is shown in this image?{prompt_suffix}{assistant_prompt}'
print(f'>>> Prompt\n{prompt}')

# Download and open the image
image = Image.open(requests.get(image_url, stream=True).raw)
inputs = processor(text=prompt, images=image, return_tensors='pt').to('cuda:0')

# Generate model response
generate_ids = model.generate(
    **inputs,
    max_new_tokens=1000,
    generation_config=generation_config,
)
generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
response = processor.batch_decode(
    generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)[0]
print(f'>>> Response\n{response}')

# Part 2: Audio Processing
print("\n--- AUDIO PROCESSING ---")
audio_url = "https://upload.wikimedia.org/wikipedia/commons/b/b0/Barbara_Sahakian_BBC_Radio4_The_Life_Scientific_29_May_2012_b01j5j24.flac"
speech_prompt = "Transcribe the audio to text, and then translate the audio to French. Use as a separator between the original transcript and the translation."
prompt = f'{user_prompt}<|audio_1|>{speech_prompt}{prompt_suffix}{assistant_prompt}'
print(f'>>> Prompt\n{prompt}')

# Download and open the audio file
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                  "AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/143.0.0.0 Safari/537.36"
}
response = requests.get(audio_url, headers=headers)
response.raise_for_status()
audio, samplerate = sf.read(io.BytesIO(response.content))
inputs = processor(text=prompt, audios=[(audio, samplerate)], return_tensors='pt').to('cuda:0')

# Generate model response
generate_ids = model.generate(
    **inputs,
    max_new_tokens=1000,
    generation_config=generation_config,
)
generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
response = processor.batch_decode(
    generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)[0]
print(f'>>> Response\n{response}')

2. 実行すると、以下のような応答が表示されます。

参考資料:

microsoft/Phi-4-multimodal-instruct · Hugging Face

 

Copyright © 2026 YUAN High-Tech Development Co., Ltd.
All rights reserved.