Memory-efficient attention forward operator error in Docker container with FastAPI and DINOv2

I’m currently working on an API using FastAPI to serve DINOv2 models from the official DINOv2 repository. The API works well locally, but when I run it in a Docker container, I encounter an error related to the memory-efficient attention forward operator.

API.py

from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.responses import JSONResponse
import torch
from PIL import Image, UnidentifiedImageError
from torchvision import transforms
import io
import requests  # Import the requests library
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

# Dictionary to map model names to their respective identifiers
MODEL_MAP = {
    'dinov2_vitl14': 'dinov2_vitl14',
    'dinov2_vits14': 'dinov2_vits14',
    'dinov2_vitb14': 'dinov2_vitb14',
    'dinov2_vitg14': 'dinov2_vitg14',
}

# Load the model based on the provided model name
def load_model(model_name: str):
    if model_name not in MODEL_MAP:
        raise ValueError(f"Model {model_name} is not supported.")
    model = torch.hub.load('facebookresearch/dinov2', MODEL_MAP[model_name])
    model.eval()
    return model

# Preprocess the image
def preprocess_image(image):
    input_image = Image.open(io.BytesIO(image)).convert('RGB')
    preprocess = transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])
    input_tensor = preprocess(input_image)
    input_batch = input_tensor.unsqueeze(0)  # Create a mini-batch as expected by the model
    return input_batch

# Perform inference
def infer(model, input_batch):
    with torch.no_grad():
        output = model(input_batch)
    return output

@app.post("/infer/")
async def infer_image(file: UploadFile = File(...), model_name: str = Form(...)):
    try:
        if model_name not in MODEL_MAP:
            raise HTTPException(status_code=400, detail="Invalid model name provided.")

        image_bytes = await file.read()
        input_batch = preprocess_image(image_bytes)
        model = load_model(model_name)
        output = infer(model, input_batch)

        return JSONResponse(content={"inference_output": output.tolist()})
    except Exception as e:
        logger.error(f"Error processing image: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/infer-url/")
async def infer_image_url(url: str = Form(...), model_name: str = Form(...)):
    try:
        if model_name not in MODEL_MAP:
            raise HTTPException(status_code=400, detail="Invalid model name provided.")

        response = requests.get(url)
        if response.status_code != 200:
            logger.error(f"Failed to download image from URL: {url}, Status code: {response.status_code}")
            raise HTTPException(status_code=400, detail="Failed to download image from the provided URL.")

        image_bytes = response.content

        try:
            input_batch = preprocess_image(image_bytes)
        except UnidentifiedImageError:
            logger.error(f"The provided URL does not contain a valid image: {url}")
            raise HTTPException(status_code=400, detail="The provided URL does not contain a valid image.")

        model = load_model(model_name)
        output = infer(model, input_batch)

        return JSONResponse(content={"inference_output": output.tolist()})
    except Exception as e:
        logger.error(f"Error processing image from URL: {url}, Error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Dockerfile

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "API:app", "--host", "0.0.0.0", "--port", 8000"]

requirements.txt:

--extra-index-url https://download.pytorch.org/whl/cu117
torch==2.0.0
torchvision==0.15.0
omegaconf
torchmetrics==0.10.3
fvcore
iopath
xformers==0.0.16rc425
submitit
--extra-index-url https://pypi.nvidia.com
cuml-cu11
fastapi
Pillow
requests
uvicorn

Problem:
When I run the API locally, both endpoints work fine. However, when running the API in the Docker container, I get the following error:

{ "detail": "No operator found for memory_efficient_attention_forward with inputs:n query : shape=(1, 257, 6, 64) (torch.float32)n key : shape=(1, 257, 6, 64) (torch.float32)n value : shape=(1, 257, 6, 64) (torch.float32)n attn_bias : <class 'NoneType'>n p : 0.0ncutlassF is not supported because:n device=cpu (supported: {'cuda'})nflshattF is not supported because:n device=cpu (supported: {'cuda'})n dtype=torch.float32 (supported: {torch.bfloat16, torch.float16})ntritonflashattFis not supported because:n device=cpu (supported: {'cuda'})n dtype=torch.float32 (supported: {torch.bfloat16, torch.float16})n Operator wasn't built - seepython -m xformers.info for more infon triton is not availablensmallkFis not supported because:n max(query.shape[-1] != value.shape[-1]) > 32n unsupported embed per head: 64" }

Additional Information:
The error seems to indicate that the CPU is not supported for the memory-efficient attention forward operator.
Locally, the API runs on a system with CUDA support.
In the Docker container, the application seems to be running on the CPU.
Question:
How can I resolve this error and make the API work correctly in the Docker container?

Any insights or suggestions would be greatly appreciated. Thank you!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật