> ## Documentation Index
> Fetch the complete documentation index at: https://docs.inferless.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy the Phi-4-Multimodal-Instruct using Inferless

> Phi-4-Multimodal-Instruct is a 5.6-billion-parameter multimodal language model from Microsoft that integrates text, vision, and audio processing. This model excels in instruction-based tasks, offering advanced reasoning and cross-modal capabilities.

## Introduction

[Phi-4-Multimodal-Instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct) is a state‑of‑the‑art multimodal foundation model developed by Microsoft Research. Built for instruction‑tuned applications, it seamlessly fuses robust language understanding with advanced visual and audio analysis. Whether it’s interpreting complex images, transcribing and translating speech, or parsing detailed documents, this model is engineered to act as a versatile AI agent. With capabilities that include generating structured outputs and supporting multilingual inputs across text, vision, and audio, Phi-4-Multimodal-Instruct opens up new possibilities for interactive chatbots, multimedia content analysis, and beyond.

## Defining Dependencies

We are using the [transformers](https://github.com/huggingface/transformers) to serve the model on a single A100.

## Our Observations

We have deployed the model on an A100 GPU(80GB). Here are our observations:

| Library      | Inference Time (Image Q\&A) | Inference Time (Audio Transcribe) | Cold Start Time |
| ------------ | --------------------------- | --------------------------------- | --------------- |
| transformers | 7.54 sec                    | 6.28 sec                          | 16.23 sec       |

Note: The inference time(image and video) and cold start time are average values.

## Defining Dependencies

We are using the [transformers](https://github.com/huggingface/transformers) to serve the model on a single A100 (80GB).

## Constructing the GitHub/GitLab Template

Now quickly construct the GitHub/GitLab template, this process is mandatory and make sure you don't add any file named `model.py`.

```
phi-4-multimodal-instruct/
├── app.py
├── inferless-runtime-config.yaml
└── inferless.yaml
```

You can also add other files to this directory.

## Create the Input Schema with Pydantic

Using the `inferless` Python client and Pydantic, you can define structured schemas directly in your code for input and output, eliminating the need for external file.

### Input Schema

When defining an input schema with Pydantic, you need to annotate your class attributes with the appropriate types, such as `str`, `float`, `int`, etc.
These type annotations specifys what type of data each field should contain.
The `default` value serves as the example input for testing with the `infer` function.

```python theme={null}
@inferless.request
class RequestObjects(BaseModel):
    task_type: str = Field(default="image")
    prompt: Optional[str] ="What is shown in this image?"
    content_url: Optional[str] ="https://www.ilankelman.org/stopsigns/australia.jpg"
    max_new_tokens: Optional[int] = 128
```

### Output Schema

The `@inferless.response` decorator helps you define structured output schemas.

```python theme={null}
@inferless.response
class ResponseObjects(BaseModel):
    generated_result: str = Field(default="Test output")
```

### Usage in the `infer` Function

Once you have annotated the objects you can expect the infer function to receive `RequestObjects` as input,
and returns a `ResponseObjects` instance as output, ensuring the results adhere to a defined structure.

```python theme={null}
class InferlessPythonModel:
    def infer(self, request: RequestObjects) -> ResponseObjects:
        
        return ResponseObjects(generated_result = response)
```

## Create the class for inference

In the [app.py](https://github.com/inferless/phi-4-multimodal-instruct/blob/main/app.py) we will define the class and import all the required functions

1. `def initialize`: In this function, you will initialize your model and define any `variable` that you want to use during inference.

2. `def infer`: This function gets called for every request that you send. Here you can define all the steps that are required for the inference.

3. `def finalize`: This function cleans up all the allocated memory.

```python theme={null}
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import snapshot_download
import requests
import torch
import io
from PIL import Image
import soundfile as sf
from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
from urllib.request import urlopen
import inferless
from pydantic import BaseModel, Field
from typing import Optional


@inferless.request
class RequestObjects(BaseModel):
    task_type: str = Field(default="image")
    prompt: Optional[str] ="What is shown in this image?"
    content_url: Optional[str] ="https://www.ilankelman.org/stopsigns/australia.jpg"
    max_new_tokens: Optional[int] = 128

@inferless.response
class ResponseObjects(BaseModel):
    generated_result: str = Field(default="Test output")

class InferlessPythonModel:
    def initialize(self):
        model_path = "microsoft/Phi-4-multimodal-instruct"
        snapshot_download(repo_id=model_path, allow_patterns=["*.safetensors"])
        
        self.processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
        self.model = AutoModelForCausalLM.from_pretrained(model_path,device_map="cuda",torch_dtype="auto",
                                                          trust_remote_code=True,_attn_implementation="flash_attention_2"
                                                         ).cuda()
        self.generation_config = GenerationConfig.from_pretrained(model_path)

        self.user_prompt = "<|user|>"
        self.assistant_prompt = "<|assistant|>"
        self.prompt_suffix = "<|end|>"

    def infer(self, request: RequestObjects) -> ResponseObjects:
        if request.task_type == "image":
            prompt = f"{self.user_prompt}<|image_1|>{request.prompt}{self.prompt_suffix}{self.assistant_prompt}"
            image = Image.open(requests.get(request.content_url, stream=True).raw)
            inputs = self.processor(text=prompt, images=image, return_tensors="pt").to("cuda:0")
        else:
            prompt = f"{self.user_prompt}<|audio_1|>{request.prompt}{self.prompt_suffix}{self.assistant_prompt}"
            audio, samplerate = sf.read(io.BytesIO(urlopen(request.content_url).read()))
            inputs = self.processor(text=prompt, audios=[(audio, samplerate)], return_tensors='pt').to('cuda:0')

        generate_ids = self.model.generate(**inputs,max_new_tokens=request.max_new_tokens,
                                           generation_config=self.generation_config,)
        generate_ids = generate_ids[:, inputs["input_ids"].shape[1] :]
        response = self.processor.batch_decode(generate_ids, skip_special_tokens=True,
                                               clean_up_tokenization_spaces=False)[0]        
        
        generateObject = ResponseObjects(generated_result=response)
        return generateObject

    def finalize(self):
        self.model = None
```

## Creating the Custom Runtime

This is a mandatory step where we allow the users to upload their custom runtime through [inferless-runtime-config.yaml](https://github.com/inferless/phi-4-multimodal-instruct/blob/main/inferless-runtime-config.yaml).

```python theme={null}
build:
  cuda_version: "12.1.1"
  python_packages:
    - packaging==24.2
    - 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
    - hf-transfer==0.1.9
    - inferless==0.2.13
    - pydantic==2.10.2
  run:
    - "pip install flash_attn==2.7.4.post1"
```

## Test your model with Remote Run

You can use the `inferless remote-run`([installation guide here](https://docs.inferless.com/model-import/cli-import#cli-import)) command to test your model or any custom Python script in a remote GPU environment directly from your local machine. Make sure that you use `Python3.10` for seamless experience.

### Step 1: Add the Decorators and local entry point

To enable **Remote Run**, simply do the following:

1. Import the `inferless` library and initialize `Cls(gpu="A100")`. The available GPU options are `T4`, `A10` and `A100`.
2. Decorated the `initialize` and `infer` functions with `@app.load` and `@app.infer` respectively.
3. Create the Local Entry Point by decorating a function (for example, `my_local_entry`) with `@inferless.local_entry_point`.
   Within this function, instantiate your model class, convert any incoming parameters into a `RequestObjects` object, and invoke the model's `infer` method.

```python theme={null}
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import snapshot_download
import requests
import torch
import io
from PIL import Image
import soundfile as sf
from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
from urllib.request import urlopen
import inferless
from pydantic import BaseModel, Field
from typing import Optional


@inferless.request
class RequestObjects(BaseModel):
    task_type: str = Field(default="image")
    prompt: Optional[str] ="What is shown in this image?"
    content_url: Optional[str] ="https://www.ilankelman.org/stopsigns/australia.jpg"
    max_new_tokens: Optional[int] = 128

@inferless.response
class ResponseObjects(BaseModel):
    generated_result: str = Field(default="Test output")

app = inferless.Cls(gpu="A100")

class InferlessPythonModel:
    @app.load
    def initialize(self):
        model_path = "microsoft/Phi-4-multimodal-instruct"
        snapshot_download(repo_id=model_path, allow_patterns=["*.safetensors"])
        
        self.processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
        self.model = AutoModelForCausalLM.from_pretrained(model_path,device_map="cuda",torch_dtype="auto",
                                                          trust_remote_code=True,_attn_implementation="flash_attention_2"
                                                         ).cuda()
        self.generation_config = GenerationConfig.from_pretrained(model_path)

        self.user_prompt = "<|user|>"
        self.assistant_prompt = "<|assistant|>"
        self.prompt_suffix = "<|end|>"

    @app.infer
    def infer(self, request: RequestObjects) -> ResponseObjects:
        if request.task_type == "image":
            prompt = f"{self.user_prompt}<|image_1|>{request.prompt}{self.prompt_suffix}{self.assistant_prompt}"
            image = Image.open(requests.get(request.content_url, stream=True).raw)
            inputs = self.processor(text=prompt, images=image, return_tensors="pt").to("cuda:0")
        else:
            prompt = f"{self.user_prompt}<|audio_1|>{request.prompt}{self.prompt_suffix}{self.assistant_prompt}"
            audio, samplerate = sf.read(io.BytesIO(urlopen(request.content_url).read()))
            inputs = self.processor(text=prompt, audios=[(audio, samplerate)], return_tensors='pt').to('cuda:0')

        generate_ids = self.model.generate(**inputs,max_new_tokens=request.max_new_tokens,
                                           generation_config=self.generation_config,)
        generate_ids = generate_ids[:, inputs["input_ids"].shape[1] :]
        response = self.processor.batch_decode(generate_ids, skip_special_tokens=True,
                                               clean_up_tokenization_spaces=False)[0]        
        
        generateObject = ResponseObjects(generated_result=response)
        return generateObject

    def finalize(self):
        self.model = None

@inferless.local_entry_point
def my_local_entry(dynamic_params):
    request_objects = RequestObjects(**dynamic_params)
    model_instance = InferlessPythonModel()

    return model_instance.infer(request_objects)
```

### Step 2: Run with Remote GPU

From your local terminal, navigate to the folder containing your `app.py` and your `inferless-runtime-config.yaml` and run:

```bash theme={null}
inferless remote-run app.py -c inferless-runtime-config.yaml --task_type "image" --prompt "What does this diagram illustrate?" --content_url "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
```

You can pass the other input parameters in the same way (e.g., `--content_url`, `--max_new_tokens`, etc.) as long as your code expects them in the `inputs` dictionary.

If you want to exclude certain files or directories from being uploaded, use the `--exclude` or `-e` flag.

## Method A: Deploying the model on Inferless Platform

Inferless supports multiple ways of [importing your model](https://docs.inferless.com/model-import/file-structure-req/file-structure-requirements). For this tutorial, we will use GitHub.

### Step 1: Login to the inferless dashboard can click on Import model button

Navigate to your desired workspace in Inferless and Click on `Add a custom model` button that you see on the top right. An import wizard will open up.

### Step 2: Follow the UI to complete the model  Import

* Select the GitHub/GitLab Integration option to connect your source code repository with the deployment environment.
* Navigate to the specific GitHub repository that contains your model's code. Here, you will need to identify and enter the name of the model you wish to import.
* Choose the appropriate type of machine that suits your model's requirements. Additionally, specify the minimum and maximum number of replicas to define the scalability range for deploying your model.
* Optionally, you have the option to enable automatic build and deployment. This feature triggers a new deployment automatically whenever there is a new code push to your repository.
* If your model requires additional software packages, configure the Custom Runtime settings by including necessary pip or apt packages. Also, set up environment variables such as  Inference Timeout, Container Concurrency, and Scale Down Timeout to tailor the runtime environment according to your needs.
* Wait for the validation process to complete, ensuring that all settings are correct and functional. Once validation is successful, click on the "Import" button to finalize the import of your model.
  <img src="https://mintcdn.com/inferless-68/g8bkqnienvwe_7dP/images/inferless_model_import.png?fit=max&auto=format&n=g8bkqnienvwe_7dP&q=85&s=4cd9d6888f4fbd75d9d4e6eb90771bd3" alt="" width="2484" height="1478" data-path="images/inferless_model_import.png" />

### Step 3: Wait for the model build to complete usually takes \~5-10 minutes

### Step 4: Use the APIs to call the model

Once the model is in 'Active' status you can click on the 'API' page to call the model

### Here is the Demo:

<img src="https://mintcdn.com/inferless-68/txuhsMKn8Dl42Mmp/gif/qwen2.5-vl-7b.gif?s=17a0284da6b7fb6e4ee00a52de845425" alt="" width="1000" height="511" data-path="gif/qwen2.5-vl-7b.gif" />

## Method B: Deploying the model on Inferless CLI

Inferless allows you to deploy your model using Inferless-CLI. Follow the steps to deploy using Inferless CLI.

### Clone the repository of the model

Let's begin by cloning the model repository:

```bash theme={null}
git clone https://github.com/inferless/phi-4-multimodal-instruct.git
```

### Deploy the Model

To deploy the model using Inferless CLI, execute the following command:

```bash theme={null}
inferless deploy --gpu A100 --runtime inferless-runtime-config.yaml
```

**Explanation of the Command:**

* `--gpu A100`: Specifies the GPU type for deployment. Available options include `A10`, `A100`, and `T4`.
* `--runtime inferless-runtime-config.yaml`: Defines the runtime configuration file. If not specified, the default Inferless runtime is used.
  <img src="https://mintcdn.com/inferless-68/ICUjU4GLsdW9H74k/images/phi-4-multimodal-cli.png?fit=max&auto=format&n=ICUjU4GLsdW9H74k&q=85&s=4b602b7bbfbe6b1ab28ea2351ba815cd" alt="" width="2614" height="688" data-path="images/phi-4-multimodal-cli.png" />
