🚀 Mac M4 Local AI Background Removal Service Deployment Guide (BiRefNet)
Goal: Deploy the BiRefNet SOTA background-removal model on macOS Hardware requirements: Apple Silicon Mac (M1/M2/M3/M4) Final result: a Web UI (port 8860) + API endpoint, using the NPU/GPU for lightning-fast matting.
/50266ff9-67b1-4e58-bae0-a59af5ee925b.webp)
Step 1: Install the Package Manager (Homebrew)
If Homebrew is already installed on your Mac, skip this step.
Open Terminal, copy and run the following command:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Important: configure environment variables After installation finishes, the terminal will prompt you at the bottom to run two commands (those starting with echo). You must run them, otherwise the brew command will not work. If you missed them, you can run this manually:
(echo; echo 'eval "$(/opt/homebrew/bin/brew shellenv)"') >> /Users/$USER/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
Step 2: Install Python Environment Management (Miniforge)
We need a clean Python environment. For Apple Silicon chips, Miniforge is the best choice (lighter than Anaconda, with native support for M-series chips).
-
Install Miniforge:
brew install miniforge -
Initialize the shell:
conda init zsh -
Apply the configuration: close the current terminal window and open a new terminal.
Step 3: Create the Project and Environment
We will put all files under the Documents/BiRefNet-Mac directory.
-
Create the directory:
mkdir -p ~/Documents/BiRefNet-Mac cd ~/Documents/BiRefNet-Mac -
Create an isolated Python environment (Python 3.10):
conda create -n birefnet python=3.10 -y -
Activate the environment:
conda activate birefnet
(After activation, your command-line prefix should change to (birefnet))
Step 4: Install Dependencies (Key Step)
We will install PyTorch (with Mac GPU acceleration support) and the libraries BiRefNet needs.
Copy the following commands and run them in the terminal:
# 1. Install PyTorch and image-processing libraries
pip install torch torchvision torchaudio
# 2. Install HuggingFace ecosystem libraries and the WebUI library
pip install transformers timm pillow gradio accelerate
# 3. Install the model-specific math libraries (fixes the earlier error)
pip install einops kornia
Step 5: Write the Code (app.py)
Copy the entire block of code below and run it in the terminal. It will automatically generate a configured app.py file in the current directory.
Configuration note: Mac GPU (MPS) acceleration is enabled, and the port is set to 8860.
cat > app.py << 'EOF'
import gradio as gr
import torch
from transformers import AutoModelForImageSegmentation
from torchvision import transforms
from PIL import Image
# --- 1. Device detection (Mac M4 core) ---
def get_device():
if torch.backends.mps.is_available():
print("✅ Mac M4 GPU activated (MPS mode) - full performance")
return "mps"
return "cpu"
device = get_device()
# --- 2. Load the model ---
# The general-purpose BiRefNet is used here; it gives the most balanced results
MODEL_ID = "ZhengPeng7/BiRefNet"
print(f"Loading model: {MODEL_ID} ...")
# trust_remote_code=True is required because this model contains custom code
model = AutoModelForImageSegmentation.from_pretrained(MODEL_ID, trust_remote_code=True)
model.to(device)
model.eval()
# --- 3. Preprocessing ---
transform = transforms.Compose([
transforms.Resize((1024, 1024)), # change to 2048 for more detail, but it will be slower
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# --- 4. Core inference logic ---
def remove_background(image):
if image is None: return None
original_size = image.size
# Convert the image to a Tensor and move it to the GPU
input_tensor = transform(image).unsqueeze(0).to(device)
# Inference (no gradient computation, saves VRAM)
with torch.no_grad():
preds = model(input_tensor)[-1].sigmoid().cpu()
# Generate the Mask and restore the original size
pred = preds[0].squeeze()
pred_pil = transforms.ToPILImage()(pred)
mask = pred_pil.resize(original_size)
# Composite the Alpha channel
image.putalpha(mask)
return image
# --- 5. Start the Web service ---
with gr.Blocks(title="BiRefNet Local") as demo:
gr.Markdown("## ⚡️ BiRefNet Local (Powered by Mac M4)")
with gr.Row():
input_img = gr.Image(type="pil", label="Upload image")
output_img = gr.Image(type="pil", label="Background-removed result", format="png")
btn = gr.Button("Start", variant="primary")
btn.click(fn=remove_background, inputs=input_img, outputs=output_img)
if __name__ == "__main__":
# Allow LAN access, port 8860
demo.launch(server_name="0.0.0.0", server_port=8860)
EOF
Step 6: First Run and Model Download
Since connecting to HuggingFace from China can be unstable, we first set up a mirror for acceleration, then run in the foreground once to make sure the model downloads successfully.
# Set the HF mirror (takes effect temporarily)
export HF_ENDPOINT=https://hf-mirror.com
# Start!
python app.py
- Watch the terminal: wait for the progress bar to finish (about 580MB).
- Success sign: you see
Running on local URL: http://0.0.0.0:8860. - Test: open a browser at
http://localhost:8860and try uploading an image. - Exit: once it works, press
Ctrl + Cto stop the program.
Step 7: Configure Silent Background Running (Production Mode)
So the service stays available after you close the terminal, we need to run it in the background.
- Startup script (with logs):
nohup python -u app.py > app.log 2>&1 &
- Verify the service: visit
http://localhost:8860 - View the logs (optional):
tail -f app.log
Operations Management Commands (Worth Bookmarking)
For when you restart the machine or need to start the service again later:
1. Start the service:
cd ~/Documents/BiRefNet-Mac
conda activate birefnet
nohup python -u app.py > app.log 2>&1 &
2. Stop the service:
# Find the process occupying port 8860 and force-kill it
lsof -t -i:8860 | xargs kill -9
3. Check the running status:
ps -ef | grep app.py
Now your Mac mini M4 has become a high-performance local background-removal server, with no dependency on Docker at all and zero performance overhead.
Comments