微軟Phi-4多模態實踐指南

微軟Phi-4多模態實踐指南

微軟正式擴充套件了其 Phi-4 系列,推出了 Phi-4-mini-instruct (3.8B) 和 Phi-4-multimodal (5.6B),對之前釋出的以高階推理能力著稱的 Phi-4 (14B) 型號進行了補充。這些新增功能大大增強了多語言支援、推理和數學技能,並引入了多模態功能。

這種輕量級開放式多模態模型整合了文字、視覺和語音處理功能,可在不同資料格式之間進行無縫互動。Phi-4 Multimodal 擁有 128K 標記上下文長度和 5.6B 引數,是一款功能強大的工具,可在裝置上執行和低延遲推理。

在本文中,我們將深入探討 Phi-4-multimodal,這是一種最先進的多模態小語言模型(SLM),能夠處理文字、視覺和音訊輸入。我們還將探討實際的動手實現,幫助開發人員將生成式人工智慧整合到現實世界的應用中。

Phi-4多模態:人工智慧發展的飛躍

Phi-4多模態

Source: Phi

Phi-4多模態的主要特點

Phi-4 多模態是一種尖端的人工智慧模型,旨在處理多種輸入型別。以下是它的獨特之處:

  • 統一多模態處理:與需要為不同輸入型別建立獨立管道的傳統模型不同,Phi-4 利用其低秩介面卡(LoRAs)混合物,將語音、視覺和文字整合到一個處理空間中。
  • 先進的訓練技術:該模型經過了監督微調、直接偏好優化(DPO)和人類反饋強化學習(RLHF),確保了高準確性和安全輸出。
  • 多語言支援:文字處理支援 22 種語言,而視覺和音訊功能則增強了對全球主要語言的理解。
  • 優化效率:專為在裝置上執行而設計,Phi-4 可最大限度地減少計算開銷,同時保持最先進的效能。

支援的模式和語言

Phi-4 Multimodal 可處理文字、視覺和音訊輸入,因此用途非常廣泛。以下是每種模式的語言支援明細:

模態 支援語言
Text Arabic, Chinese, Czech, Danish, Dutch, English, Finnish, French, German, Hebrew, Hungarian, Italian, Japanese, Korean, Norwegian, Polish, Portuguese, Russian, Spanish, Swedish, Thai, Turkish, Ukrainian
Vision English
Audio English, Chinese, German, French, Italian, Japanese, Spanish, Portuguese

Phi-4多模態的結構進步

1. 統一表示空間

Phi-4 的 LoRAs 混合架構允許同時處理語音、視覺和文字。與需要不同子模式的早期模型不同,Phi-4 在同一框架內處理所有輸入,大大提高了效率和一致性。

2. 可擴充套件性和效率

  • 針對低延遲推理進行了優化,非常適合移動和邊緣計算應用。
  • 支援更大的詞彙集,增強了跨多模態輸入的語言推理能力。
  • 採用更小但功能強大的引數化(5.6B 個引數),可在不影響效能的情況下進行高效部署。

3. 改進人工智慧推理

得益於其綜合視覺和音訊輸入的能力,Phi-4 在需要圖表/表格理解和文件推理的任務中表現出色。基準測試表明,與其他最先進的多模態模型相比,Phi-4 的準確性更高,尤其是在結構化資料解釋方面。

Phi-4多模態架構

Source: Link

視覺處理管道

視覺編碼器

  • 處理影象輸入並將其轉換為一系列特徵表示(標記)。
  • 可能使用預訓練視覺模型(如 CLIP、視覺轉換器)。

標記合併:減少視覺標記的數量,在保留資訊的同時提高效率。

視覺投影儀:將視覺標記轉換為與標記化器相容的格式,以便進一步處理。

音訊處理管道

音訊編碼器

  • 處理原始音訊並將其轉換為特徵標記序列。
  • 可能基於語音到文字或波形模型(如 Wav2Vec2、Whisper)。

音訊投影儀:將音訊嵌入對映到相容的標記空間,以便與語言模型融合。

標記化和融合

  • 標記化器通過在標記序列中插入影象和音訊佔位符來整合來自視覺、音訊和文字的資訊。
  • 然後將這種統一的表示法傳送給語言模型。

Phi-4 Mini模型

核心的 Phi-4 Mini 模型負責推理、生成響應和融合多模態資訊。

堆疊變壓器層:它採用基於轉換器的架構來處理多模態輸入。

LoRA 自適應(Low-Rank Adaptation):

  • 使用 LoRA(低秩自適應)對視覺(LoRAᵥ)和音訊(LoRAₐ)模型進行微調。
  • LoRA 有助於有效調整預訓練的權重,而不會顯著增加模型的大小。

Phi-4架構如何工作?

  1. 影象和音訊輸入分別由各自的編碼器處理。
  2. 編碼表示通過投影層與語言模型的標記空間保持一致。
  3. 標記化器融合資訊,為 Phi-4 Mini 模型的處理做好準備。
  4. 經 LoRA 增強的 Phi-4 Mini 模型可根據多模態上下文生成基於文字的輸出。

不同基準上的Phi-4多模態比較

Phi-4多模態音訊和視訊基準

Phi-4多模態音訊和視訊基準

Source: Link

這些基準可以評估模型在 AI2D、ChartQA、DocVQA 和 InfoVQA 中的能力,這些資料集是評估多模態模型的標準資料集,尤其是在視覺問題解答(VQA)和文件理解方面。

s_AI2D(AI2D 基準)

  1. 評估圖表和影象推理。
  2. Phi-4-multimodal-instruct(68.9)的表現優於InternOmni-7B (53.9)Gemini-2.0-Flash-Lite (62)
  3. Gemini-2.0-Flash (69.4)略微優於 Phi-4,而Gemini-1.5-Pro (67.7)則略低於 Phi-4。

s_ChartQA(圖表問題解答)

  1. 側重於解釋圖表。
  2. Phi-4-multimodal-instruct(69)優於所有其他模型。
  3. 其次是InternOmni-7B (56.1),但 Gemini-2.0-Flash (51.3) 和 Gemini-1.5-Pro (46.9) 的表現要差得多。

s_DocVQA(文件 VQA – 閱讀文件和提取資訊)

  1. 評估模型理解和回答文件問題的能力。
  2. Phi-4-multimodal-instruct(87.3)遙遙領先。
  3. Gemini-2.0-Flash (80.3)Gemini-1.5-Pro (78.2)表現良好,但仍落後於 Phi-4。

s_InfoVQA(基於資訊的視覺化問題解答)

  1. 測試模型提取和推理影象資訊的能力。
  2. Phi-4-multimodal-instruct(63.7)再次成為表現最好的模型。
  3. Gemini-1.5-Pro (66.1)稍微領先,但其他 Gemini 模型表現不佳。

多模態模型基準測試對比

Source: Link

Phi-4多模態語音基準

Phi-4多模態語音基準

Source: Link

  1. Phi-4-Multimodal-Instruct 在語音識別方面表現出色,在 FLEURS、OpenASR 和 CommonVoice 中擊敗了所有競爭對手。
  2. Phi-4 在語音翻譯方面表現不佳,不如 WhisperV3、Qwen2-Audio 和 Gemini 模型。
  3. 語音質量保證是一個弱點,Gemini-2.0-Flash 和 GPT-4o-RT 遙遙領先。
  4. Phi-4 在音訊理解方面很有競爭力,但 Gemini-2.0-Flash 略勝一籌。
  5. 語音總結能力一般,GPT-4o-RT 略勝一籌。

多模態語音基準測試對比

Source: Link

Phi-4多模態視覺基準

Phi-4多模態視覺基準

Source: Link

  • Phi-4 在 OCR、文件智慧和科學推理方面表現出色。
  • 它在多模態任務中表現出色,但在視訊感知和一些數學相關基準測試中卻落在了後面。
  • 它與 Gemini-2.0-Flash 和 GPT-4o 等模型競爭激烈,但在多影象和物體存在任務方面仍有改進空間。

多模態視覺基準測試對比

Phi-4多模態視覺質量雷達圖

Phi-4多模態視覺質量雷達圖

Source: Link

雷達圖的主要啟示

1. Phi-4-多模態教學的優勢

  • 擅長視覺科學推理:Phi-4 在這一類別中得分最高,超過了大多數競爭對手。
  • 在流行的綜合基準測試中表現突出:它躋身於頂級模型之列,這表明它在多模態任務中的整體效能十分強勁。
  • 在物體視覺存在驗證方面具有競爭力:它在驗證影象中物體是否存在方面的表現與排名靠前的模型類似。
  • 在圖表推理方面表現尚可:雖然不是最好的,但 Phi-4 在這一領域仍保持著競爭優勢。

2. Phi-4 的弱點

  • 在視覺數學推理方面表現不佳:Gemini-2.0-Flash 和 GPT-4o 在這一領域表現出色。
  • 在多影象感知方面落後:與 GPT-4o 和 Gemini-2.0-Flash 等模型相比,Phi-4 在處理多影象或基於視訊的感知方面較弱。
  • 在文件智慧方面表現一般:雖然它的表現不錯,但與一些競爭對手相比,它在這一類別中並不是最好的。

親身體驗:實施Phi-4多模態

微軟提供的開源資源允許開發人員探索 Phi-4 多模態的功能。下面,我們將探討使用 Phi-4 多模態實際應用。

所需軟體包

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
!pip flash_attn==2.7.4.post1 torch==2.6.0 transformers==4.48.2 accelerate==1.3.0 soundfile==0.13.1 pillow==11.1.0 scipy==1.15.2 torchvision==0.21.0 backoff==2.2.1 peft==0.13.2
!pip flash_attn==2.7.4.post1 torch==2.6.0 transformers==4.48.2 accelerate==1.3.0 soundfile==0.13.1 pillow==11.1.0 scipy==1.15.2 torchvision==0.21.0 backoff==2.2.1 peft==0.13.2
!pip flash_attn==2.7.4.post1 torch==2.6.0 transformers==4.48.2 accelerate==1.3.0 soundfile==0.13.1 pillow==11.1.0 scipy==1.15.2 torchvision==0.21.0 backoff==2.2.1 peft==0.13.2

必需匯入項

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
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
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

定義模型路徑

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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',
).cuda()
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', ).cuda()
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',
).cuda()

載入生成配置

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
generation_config = GenerationConfig.from_pretrained(model_path)
generation_config = GenerationConfig.from_pretrained(model_path)
generation_config = GenerationConfig.from_pretrained(model_path)

定義提示結構

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
user_prompt = '<|user|>'
assistant_prompt = '<|assistant|>'
prompt_suffix = '<|end|>'
user_prompt = '<|user|>' assistant_prompt = '<|assistant|>' prompt_suffix = '<|end|>'
user_prompt = '<|user|>'
assistant_prompt = '<|assistant|>'
prompt_suffix = '<|end|>'

影象處理

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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}')
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}')
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}')

下載和開啟影象

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
image = Image.open(requests.get(image_url, stream=True).raw)
inputs = processor(text=prompt, images=image, return_tensors='pt').to('cuda:0')
image = Image.open(requests.get(image_url, stream=True).raw) inputs = processor(text=prompt, images=image, return_tensors='pt').to('cuda:0')
image = Image.open(requests.get(image_url, stream=True).raw)
inputs = processor(text=prompt, images=image, return_tensors='pt').to('cuda:0')

生成響應

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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}')
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}')
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}')

輸入影象

中華門照片

輸出

The image shows a street scene with a red stop sign in the foreground. The stop sign is mounted on a pole with a decorative top. Behind the stop sign, there is a traditional Chinese building with red and green colors and Chinese characters on the signboard. The building has a tiled roof and is adorned with red lanterns hanging from the eaves. There are several people walking on the sidewalk in front of the building. A black SUV is parked on the street, and there are two trash cans on the sidewalk. The street is lined with various shops and signs, including one for 'Optus' and another for 'Kuo'. The overall scene appears to be in an urban area with a mix of modern and traditional elements.

同樣,您也可以進行音訊處理

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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 <sep> 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}')
# Downlowd and open audio file
audio, samplerate = sf.read(io.BytesIO(urlopen(audio_url).read()))
# Process with the model
inputs = processor(text=prompt, audios=[(audio, samplerate)], return_tensors='pt').to('cuda:0')
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}')
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 <sep> 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}') # Downlowd and open audio file audio, samplerate = sf.read(io.BytesIO(urlopen(audio_url).read())) # Process with the model inputs = processor(text=prompt, audios=[(audio, samplerate)], return_tensors='pt').to('cuda:0') 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}')
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 <sep> 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}')
# Downlowd and open audio file
audio, samplerate = sf.read(io.BytesIO(urlopen(audio_url).read()))
# Process with the model
inputs = processor(text=prompt, audios=[(audio, samplerate)], return_tensors='pt').to('cuda:0')
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}')

使用案例:

  • 通過實時語音轉錄實現人工智慧新聞報道。
  • 具有智慧互動功能的聲控虛擬助手。
  • 用於全球交流的實時多語言音訊翻譯。

Phi-4多模態技術的更多成果

1. Phi-4 多模態影象分析

2. Phi-4 多模態數學影象分析

多模態人工智慧和邊緣應用的未來

Phi-4多模態技術的一個突出特點是能夠在邊緣裝置上執行,這使其成為物聯網應用和計算資源有限環境的理想解決方案。

潛在的邊緣部署:

  • 智慧家居助手:整合到物聯網裝置中,實現高階家庭自動化。
  • 醫療保健應用:通過多模態分析改進診斷和患者監護。
  • 工業自動化:在製造業中實現人工智慧驅動的監控和異常檢測。

小結

微軟的 Phi-4 Multimodal 是人工智慧領域的一個突破,它將文字、視覺和語音處理無縫整合到一個緊湊、高效能的模型中。它是人工智慧助手、文件處理和多語言應用的理想選擇,為智慧、直觀的人工智慧解決方案帶來了新的可能性。

對於開發人員和研究人員來說,親手使用 Phi-4 可以實現從程式碼生成到實時語音翻譯和物聯網應用的尖端創新,從而推動多模態人工智慧的發展。

評論留言