跳至主要内容

Phi 4 Multimodal:带演示项目的指南

学习如何使用微软的 Phi-4-multimodal 模型构建多模态语言辅导应用。
· 12分钟 阅读

使用 AI 探索

Phi-4-multimodal 是微软开发的一款轻量级多模态基础模型。它属于微软 Phi 系列的小型语言模型(SLM)。

在本教程中,我将一步步讲解如何使用 Phi-4-multimodal 构建一款多模态语言导师,可处理文本、图像与音频。该应用的核心功能包括:

  • 基于文本的学习:提供实时语法纠错、语言翻译、句子重写,以及基于上下文的词汇建议。
  • 基于图像的学习:从图像中提取并翻译文本,并对视觉内容进行摘要,帮助理解。
  • 基于音频的学习:将语音转换为文本,评估发音准确度,并实现多语言的实时语音翻译。

我们先快速介绍一下 Phi-4-multimodal 模型,然后开始构建应用。

什么是 Phi-4-Multimodal?

Phi-4-multimodal 是一款面向文本、视觉与语音处理的高级 AI 模型。它支持多种模态的无缝集成,非常适合语言学习类应用。其主要能力包括:

  • 文本处理:包括语法纠错、翻译与句子构建。
  • 视觉处理:Phi 4 可执行光学字符识别(OCR)、图像摘要与多模态交互。
  • 语音处理:支持自动语音识别(ASR)、提供发音反馈与语音到文本翻译。

凭借 128K token 的上下文长度,Phi-4 多模态模型在高效推理与受限内存环境中表现出色,非常适合实时的 AI 语言学习场景。

phi-4-multimodal features

步骤 1:先决条件

我们将要构建的多模态语言导师应用,是一款由 AI 驱动的交互式工具,结合文本、图像与音频交互,帮助用户学习新语言。

在开始之前,请确保已安装以下工具与库:

  • Python 3.8+
  • torch
  • Transformers
  • PIL
  • Soundfile
  • Gradio

运行以下命令安装必要依赖:

pip install gradio transformers torch soundfile pillow

我们还需要安装 FlashAttention2 以获得更佳性能:

pip install flash-attn --no-build-isolation

注意:本项目在 Google Colab 的 A100 GPU 上运行。若您使用较旧的 GPU(例如 NVIDIA V100),可能需要在模型初始化步骤中通过设置 _attn_implementation="eager" 来禁用 FlashAttention2。

安装完成后,运行以下导入命令:

import gradio as gr
import torch
import requests
import io
import os
import soundfile as sf
from PIL import Image
from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig

步骤 2:加载 Phi-4-Multimodal

要利用 Phi-4 的多模态能力,首先需要加载模型及其处理器。模型路径来自Hugging Face,而处理器负责对文本进行分词、对图像进行缩放与归一化,并将音频波形转换为与模型兼容的格式,以实现无缝的多模态处理。

# Load model and processor
model_path = "microsoft/Phi-4-multimodal-instruct"
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()
generation_config = GenerationConfig.from_pretrained(model_path)

模型初始化使用 AutoModelForCausalLM.from_pretrained() 函数来加载用于因果语言建模(CLM)的预训练 Phi-4 模型,并通过 device_map="cuda" 将模型加载到 GPU。

此步骤中的关键参数是 _attn_implementation='flash_attention_2'`,它启用 FlashAttention2,以更快且更省内存的注意力机制,尤其适合长上下文处理。

步骤 3:构建关键功能

模型加载完成后,我们来实现核心功能。

1. 清理回复

任何基于 LLM 或 VLM 的项目都需要确保模型生成准确且相关的回答。这也包括从输出中移除提示文本,避免初始指令出现在开头,从而让用户获得干净直接的回复。

def clean_response(response, instruction_keywords):
    """Removes the prompt text dynamically based on instruction keywords."""
    for keyword in instruction_keywords:
        if response.lower().startswith(keyword.lower()):
            response = response[len(keyword):].strip()
    return response

我们使用 strip() 函数,基于指令关键词去除提示文本。

2. 输入处理

现在来处理输入。根据用户的输入或场景,输入可以是文本、图像或音频。

def process_input(file, input_type, question):
    user_prompt = "<|user|>"
    assistant_prompt = "<|assistant|>"
    prompt_suffix = "<|end|>"
    
    if input_type == "Image":
	prompt= f'{user_prompt}<|image_1|>{question}{prompt_suffix}{assistant_prompt}'
        image = Image.open(file)
	inputs = processor(text=prompt, images=image, return_tensors='pt').to(model.device)
    elif input_type == "Audio":
 	prompt= f'{user_prompt}<|audio_1|>{question}{prompt_suffix}{assistant_prompt}'
        audio, samplerate = sf.read(file)
        inputs = processor(text=prompt, audios=[(audio, samplerate)], return_tensors='pt').to(model.device)
    elif input_type == "Text":
        prompt = f'{user_prompt}{question} "{file}"{prompt_suffix}{assistant_prompt}'
        inputs = processor(text=prompt, return_tensors='pt').to(model.device)
    else:
        return "Invalid input type"    
    
    generate_ids = model.generate(**inputs, max_new_tokens=1000, generation_config=generation_config)
    response = processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
    return clean_response(response, [question])

上述函数负责处理文本、图像与音频输入,并使用 Phi-4-multimodal 生成回复。技术流程如下:

  1. 图像输入处理: 若输入类型为 "Image",提示中会包含图像占位符(<|image_1|>)。随后加载图像,处理器对文本进行分词的同时提取视觉特征。处理后的输入被传至 GPU 以优化计算。
  2. 音频输入处理: 若输入类型为 "Audio",提示中会包含音频占位符(<|audio_1|>)。通过 sf.read() 读取音频文件,获取原始波形与采样率。处理器随后同时编码音频与文本,确保多模态理解的无缝衔接。
  3. 文本输入处理:若输入类型为 "Text",则直接将文本嵌入提示中。处理器会对输入进行分词与编码,供模型进一步处理。

3. 翻译与语法纠错

接下来,使用 Phi-4-multimodal 对文本进行翻译与语法纠错。

def process_text_translate(text, target_language):
    prompt = f'Translate the following text to {target_language}: "{text}"'
    return process_input(text, "Text", prompt)
def process_text_grammar(text):
    prompt = f'Check the grammar and provide corrections if needed for the following text: "{text}"'
    return process_input(text, "Text", prompt)

process_text_translate() 函数通过指定目标语言动态构建翻译提示,将输入文本与结构化提示传递给 process_input(),并返回译文。

同样地,process_text_grammar() 构建语法检查提示,调用 process_input() 处理并返回语法纠正后的文本。两者均借助模型的翻译与语法纠错能力以简化语言处理。

步骤 4:使用 Gradio 搭建多模态演示

至此,我们已具备关键逻辑函数。下面用 Gradio 构建交互式界面。

def gradio_interface():
    with gr.Blocks() as demo:
        gr.Markdown("# Phi 4 Powered - Multimodal Language Tutor")        
        with gr.Tab("Text-Based Learning"):
            text_input = gr.Textbox(label="Enter Text")
            language_input = gr.Textbox(label="Target Language", value="French")
            text_output = gr.Textbox(label="Response")
            text_translate_btn = gr.Button("Translate")
            text_grammar_btn = gr.Button("Check Grammar")
            text_clear_btn = gr.Button("Clear")
            text_translate_btn.click(process_text_translate, inputs=[text_input, language_input], outputs=text_output)
            text_grammar_btn.click(process_text_grammar, inputs=[text_input], outputs=text_output)
            text_clear_btn.click(lambda: ("", "", ""), outputs=[text_input, language_input, text_output])        
        with gr.Tab("Image-Based Learning"):
            image_input = gr.Image(type="filepath", label="Upload Image")
            language_input_image = gr.Textbox(label="Target Language for Translation", value="English")
            image_output = gr.Textbox(label="Response")
            image_clear_btn = gr.Button("Clear")
            image_translate_btn = gr.Button("Translate Text in Image")
            image_summarize_btn = gr.Button("Summarize Image")
            image_translate_btn.click(process_input, inputs=[image_input, gr.Textbox(value="Image", visible=False), gr.Textbox(value="Extract and translate text", visible=False)], outputs=image_output)
            image_summarize_btn.click(process_input, inputs=[image_input, gr.Textbox(value="Image", visible=False), gr.Textbox(value="Summarize this image", visible=False)], outputs=image_output)
            image_clear_btn.click(lambda: (None, "", ""), outputs=[image_input, language_input_image, image_output])
        with gr.Tab("Audio-Based Learning"):
            audio_input = gr.Audio(type="filepath", label="Upload Audio")
            language_input_audio = gr.Textbox(label="Target Language for Translation", value="English")
            transcript_output = gr.Textbox(label="Transcribed Text")
            translated_output = gr.Textbox(label="Translated Text")
            audio_clear_btn = gr.Button("Clear")
            audio_transcribe_btn = gr.Button("Transcribe & Translate")
            audio_transcribe_btn.click(process_input, inputs=[audio_input, gr.Textbox(value="Audio", visible=False), gr.Textbox(value="Transcribe this audio", visible=False)], outputs=transcript_output)
            audio_transcribe_btn.click(process_input, inputs=[audio_input, gr.Textbox(value="Audio", visible=False), language_input_audio], outputs=translated_output)
            audio_clear_btn.click(lambda: (None, "", "", ""), outputs=[audio_input, language_input_audio, transcript_output, translated_output])        
        demo.launch(debug=True)

if __name__ == "__main__":
    gradio_interface()

以上代码将 Gradio 界面组织为三个交互式选项卡:基于文本的学习、基于图像的学习与基于音频的学习,分别对应不同的语言学习功能。

用户可以输入文本进行翻译或语法检查,上传图像以提取与摘要文本,或提供音频进行语音转写与翻译。

每个功能均通过 Gradio 的 click() 方法触发,调用 process_text_translate()、process_text_grammar() 与 process_input() 等处理函数,传入所需输入并动态更新输出。

Clear 按钮在每个选项卡中用于重置输入与输出,保证流畅体验。最后通过 demo.launch(debug=True) 启动界面,方便开发者调试应用中的错误。

步骤 5:测试应用

以下是我对该应用的一些实验结果。

翻译与语法检查

在翻译与语法检查任务中,我输入了 "Hello world",并让模型将其翻译成法语并核查其语法(注意翻译与语法检查使用不同的按钮)。

Phi-4-multimodal for text translation

Phi-4-multimodal for grammar check and correction

翻译图像中的文本

在该示例中,我提供了一张西班牙语的禁止步行标志,提示行人不要走某条路径。模型准确理解了标志的含义,并生成了答案:“Do not walk on the track.”

Phi 4 for image text translation

音频转写与翻译

在音频转写中,我提供了一段英文音频,并让模型转写语音并将转写结果翻译成法语。

Phi 4 multimodal for audio transcription and translation

结语

在本教程中,我们使用 Phi-4 多模态模型构建了多模态语言导师,实现了基于文本、图像与音频的语言学习。我们利用 Phi-4 的先进视觉、语音与文本能力,提供实时翻译、语法纠错、语音转写与基于图像的学习洞见。本项目展示了多模态 AI 如何提升语言教育与可达性。

Aashi Dutt

作者

Aashi Dutt

我是一名 Google Developers 机器学习(生成式 AI)领域的专家、Kaggle 三项专家,以及 Women Techmakers 大使,拥有 3 年以上的技术从业经验。2020 年我共同创办了一家健康科技初创公司,目前在佐治亚理工学院攻读计算机科学硕士,专攻机器学习。

主题