Upload 25 files
Browse files- api/README.md +113 -0
- api/api/__init__.py +1 -0
- api/api/app.py +65 -0
- api/api/config.py +78 -0
- api/api/schemas.py +35 -0
- api/api/service.py +213 -0
- api/local_config.py +50 -0
- api/predict.py +140 -0
- api/run_api.py +105 -0
- api/setup_local_model.py +156 -0
- hf_space/README.md +13 -0
- hf_space/app.py +89 -0
- hf_space/requirements.txt +10 -0
- src/README.md +14 -0
- src/configs/config.yaml +6 -0
- src/configs/dataset/default.yaml +13 -0
- src/configs/model/default.yaml +7 -0
- src/configs/training/default.yaml +18 -0
- src/dataset.py +124 -0
- src/inference.py +138 -0
- src/main.py +388 -0
- src/models/__init__.py +9 -0
- src/models/fuse_md.py +223 -0
- src/models/local_store.py +62 -0
- src/train.py +100 -0
api/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Fuse-MD API
|
| 2 |
+
|
| 3 |
+
This folder contains the FastAPI-based inference service for Fuse-MD.
|
| 4 |
+
|
| 5 |
+
## What it does
|
| 6 |
+
|
| 7 |
+
The API loads a saved Fuse-MD checkpoint and exposes HTTP endpoints for:
|
| 8 |
+
|
| 9 |
+
- health checks
|
| 10 |
+
- model metadata
|
| 11 |
+
- multimodal prediction from text and an uploaded image
|
| 12 |
+
|
| 13 |
+
## Endpoints
|
| 14 |
+
|
| 15 |
+
- `GET /`
|
| 16 |
+
- `GET /health`
|
| 17 |
+
- `GET /model-info`
|
| 18 |
+
- `POST /predict`
|
| 19 |
+
|
| 20 |
+
## Easy local inference
|
| 21 |
+
|
| 22 |
+
1. Activate your virtual environment.
|
| 23 |
+
2. Download the text backbone once:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
python api/setup_local_model.py --model VishnuPJ/MalayaLLM_7B_Base
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
3. Open `api/local_config.py` and set `CHECKPOINT_PATH` to your trained `.pth` file.
|
| 30 |
+
4. Start the API from the repository root:
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
python api/run_api.py
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
5. In a second terminal, send a prediction request:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python api/predict.py --image data/malayalam/dev/sample/148.jpg --text "sample meme transcription"
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
The helper scripts use the values in `api/local_config.py` by default, so you
|
| 43 |
+
only need to set the checkpoint path once for the common local workflow.
|
| 44 |
+
|
| 45 |
+
The setup command requires internet only the first time. After that, runtime
|
| 46 |
+
loads the text backbone from `local_models/` in offline mode. If you use a
|
| 47 |
+
Tamil checkpoint, run
|
| 48 |
+
`python api/setup_local_model.py --model abhinand/tamil-llama-7b-base-v0.1`
|
| 49 |
+
once too.
|
| 50 |
+
|
| 51 |
+
## Local config defaults
|
| 52 |
+
|
| 53 |
+
`api/local_config.py` includes:
|
| 54 |
+
|
| 55 |
+
- `CHECKPOINT_PATH`
|
| 56 |
+
- `LOCAL_MODEL_ROOT`
|
| 57 |
+
- `HOST`
|
| 58 |
+
- `PORT`
|
| 59 |
+
- `DEVICE`
|
| 60 |
+
- `THRESHOLD`
|
| 61 |
+
- `MAX_LENGTH`
|
| 62 |
+
|
| 63 |
+
You can also override the startup settings directly from the terminal:
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
python api/run_api.py --checkpoint trained_model/tamil/fusion/your_checkpoint.pth --device cpu
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
The model setup command also supports checkpoint-based inference of the model id:
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
python api/setup_local_model.py --checkpoint trained_model/malayalam/fusion/your_checkpoint.pth
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
## Run the API manually
|
| 76 |
+
|
| 77 |
+
From the repository root:
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
uvicorn api.api.app:app --host 0.0.0.0 --port 8000 --reload
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
## Optional environment variables
|
| 84 |
+
|
| 85 |
+
- `FUSEMD_CHECKPOINT`
|
| 86 |
+
- `FUSEMD_HOST`
|
| 87 |
+
- `FUSEMD_PORT`
|
| 88 |
+
- `FUSEMD_THRESHOLD`
|
| 89 |
+
- `FUSEMD_MAX_LENGTH`
|
| 90 |
+
- `FUSEMD_USE_8BIT`
|
| 91 |
+
- `FUSEMD_DEVICE`
|
| 92 |
+
- `FUSEMD_LOCAL_MODEL_ROOT`
|
| 93 |
+
|
| 94 |
+
## Example request
|
| 95 |
+
|
| 96 |
+
```bash
|
| 97 |
+
python api/predict.py --image sample.jpg --text "sample meme transcription"
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
Manual `curl` usage still works:
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
curl -X POST "http://127.0.0.1:8000/predict" \
|
| 104 |
+
-F "text=sample meme transcription" \
|
| 105 |
+
-F "image=@sample.jpg"
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
## Notes
|
| 109 |
+
|
| 110 |
+
- The API uses the saved checkpoint metadata to rebuild the model.
|
| 111 |
+
- The repository does not include the dataset.
|
| 112 |
+
- The text backbone must be downloaded once into `local_models/` before offline runtime.
|
| 113 |
+
- For single-image API inference, uploaded images are normalized per image at runtime.
|
api/api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI app package for Fuse-MD inference."""
|
api/api/app.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import asynccontextmanager
|
| 2 |
+
|
| 3 |
+
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
|
| 4 |
+
|
| 5 |
+
from .config import settings
|
| 6 |
+
from .schemas import HealthResponse, ModelInfoResponse, PredictionResponse
|
| 7 |
+
from .service import FuseMDService
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
service = FuseMDService(settings)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@asynccontextmanager
|
| 14 |
+
async def lifespan(_: FastAPI):
|
| 15 |
+
service.load()
|
| 16 |
+
yield
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
app = FastAPI(
|
| 20 |
+
title="Fuse-MD API",
|
| 21 |
+
version="1.0.0",
|
| 22 |
+
description="FastAPI service for checkpoint-based Fuse-MD multimodal inference.",
|
| 23 |
+
lifespan=lifespan,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@app.get("/", tags=["meta"])
|
| 28 |
+
async def root() -> dict[str, str]:
|
| 29 |
+
return {
|
| 30 |
+
"message": "Fuse-MD FastAPI service is running.",
|
| 31 |
+
"docs": "/docs",
|
| 32 |
+
"health": "/health",
|
| 33 |
+
"model_info": "/model-info",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@app.get("/health", response_model=HealthResponse, tags=["meta"])
|
| 38 |
+
async def health() -> HealthResponse:
|
| 39 |
+
return HealthResponse(**service.health())
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@app.get("/model-info", response_model=ModelInfoResponse, tags=["meta"])
|
| 43 |
+
async def model_info() -> ModelInfoResponse:
|
| 44 |
+
return ModelInfoResponse(**service.info())
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@app.post("/predict", response_model=PredictionResponse, tags=["inference"])
|
| 48 |
+
async def predict(
|
| 49 |
+
text: str = Form(..., description="Meme transcription or OCR text."),
|
| 50 |
+
image: UploadFile = File(..., description="Uploaded meme image."),
|
| 51 |
+
threshold: float | None = Form(default=None, description="Optional decision threshold override."),
|
| 52 |
+
) -> PredictionResponse:
|
| 53 |
+
try:
|
| 54 |
+
image_bytes = await image.read()
|
| 55 |
+
result = service.predict(
|
| 56 |
+
text=text,
|
| 57 |
+
image_bytes=image_bytes,
|
| 58 |
+
image_filename=image.filename,
|
| 59 |
+
threshold=threshold,
|
| 60 |
+
)
|
| 61 |
+
return PredictionResponse(**result)
|
| 62 |
+
except ValueError as exc:
|
| 63 |
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
| 64 |
+
except RuntimeError as exc:
|
| 65 |
+
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
api/api/config.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def repo_root() -> Path:
|
| 8 |
+
return Path(__file__).resolve().parents[2]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def resolve_repo_path(raw_path: str) -> Path:
|
| 12 |
+
path = Path(raw_path)
|
| 13 |
+
if path.is_absolute():
|
| 14 |
+
return path
|
| 15 |
+
return (repo_root() / path).resolve()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def auto_checkpoint_path() -> Path:
|
| 19 |
+
explicit = os.getenv("FUSEMD_CHECKPOINT")
|
| 20 |
+
if explicit:
|
| 21 |
+
return resolve_repo_path(explicit)
|
| 22 |
+
|
| 23 |
+
preferred = resolve_repo_path("trained_model/malayalam/fusion/fusemd_best.pth")
|
| 24 |
+
if preferred.exists():
|
| 25 |
+
return preferred
|
| 26 |
+
|
| 27 |
+
candidates = sorted(
|
| 28 |
+
repo_root().glob("trained_model/*/fusion/*.pth"),
|
| 29 |
+
key=lambda path: path.stat().st_mtime,
|
| 30 |
+
reverse=True,
|
| 31 |
+
)
|
| 32 |
+
if candidates:
|
| 33 |
+
return candidates[0]
|
| 34 |
+
|
| 35 |
+
return preferred
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def env_optional_float(name: str) -> Optional[float]:
|
| 39 |
+
raw_value = os.getenv(name)
|
| 40 |
+
if raw_value is None or raw_value == "":
|
| 41 |
+
return None
|
| 42 |
+
return float(raw_value)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def env_optional_int(name: str) -> Optional[int]:
|
| 46 |
+
raw_value = os.getenv(name)
|
| 47 |
+
if raw_value is None or raw_value == "":
|
| 48 |
+
return None
|
| 49 |
+
return int(raw_value)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def env_bool(name: str, default: bool) -> bool:
|
| 53 |
+
raw_value = os.getenv(name)
|
| 54 |
+
if raw_value is None:
|
| 55 |
+
return default
|
| 56 |
+
return raw_value.strip().lower() in {"1", "true", "yes", "on"}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass(frozen=True)
|
| 60 |
+
class Settings:
|
| 61 |
+
checkpoint_path: Path
|
| 62 |
+
host: str
|
| 63 |
+
port: int
|
| 64 |
+
default_threshold: Optional[float]
|
| 65 |
+
max_length: Optional[int]
|
| 66 |
+
use_8bit: bool
|
| 67 |
+
device: str
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
settings = Settings(
|
| 71 |
+
checkpoint_path=auto_checkpoint_path(),
|
| 72 |
+
host=os.getenv("FUSEMD_HOST", "0.0.0.0"),
|
| 73 |
+
port=int(os.getenv("FUSEMD_PORT", "8000")),
|
| 74 |
+
default_threshold=env_optional_float("FUSEMD_THRESHOLD"),
|
| 75 |
+
max_length=env_optional_int("FUSEMD_MAX_LENGTH"),
|
| 76 |
+
use_8bit=env_bool("FUSEMD_USE_8BIT", False),
|
| 77 |
+
device=os.getenv("FUSEMD_DEVICE", "auto").strip().lower(),
|
| 78 |
+
)
|
api/api/schemas.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
from pydantic import BaseModel, Field
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class HealthResponse(BaseModel):
|
| 7 |
+
status: str
|
| 8 |
+
ready: bool
|
| 9 |
+
checkpoint: str
|
| 10 |
+
device: str
|
| 11 |
+
error: Optional[str] = None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ModelInfoResponse(BaseModel):
|
| 15 |
+
ready: bool
|
| 16 |
+
checkpoint: str
|
| 17 |
+
device: str
|
| 18 |
+
language: Optional[str] = None
|
| 19 |
+
text_model: Optional[str] = None
|
| 20 |
+
image_model: Optional[str] = None
|
| 21 |
+
fusion_method: Optional[str] = None
|
| 22 |
+
threshold: Optional[float] = None
|
| 23 |
+
max_length: Optional[int] = None
|
| 24 |
+
error: Optional[str] = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class PredictionResponse(BaseModel):
|
| 28 |
+
label: str = Field(description="Predicted class label.")
|
| 29 |
+
probability: float = Field(description="Predicted probability for the positive class.")
|
| 30 |
+
threshold: float = Field(description="Decision threshold used for classification.")
|
| 31 |
+
predicted_positive: bool = Field(description="Whether the prediction crosses the threshold.")
|
| 32 |
+
fusion_method: str
|
| 33 |
+
language: str
|
| 34 |
+
checkpoint: str
|
| 35 |
+
image_filename: Optional[str] = None
|
api/api/service.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import sys
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any, Dict, Optional
|
| 5 |
+
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from .config import Settings
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 14 |
+
if str(ROOT) not in sys.path:
|
| 15 |
+
sys.path.insert(0, str(ROOT))
|
| 16 |
+
|
| 17 |
+
from src.models import build_model, load_tokenizer_and_llama, load_trainable_checkpoint, resolve_dtype
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class FuseMDService:
|
| 24 |
+
def __init__(self, settings: Settings) -> None:
|
| 25 |
+
self.settings = settings
|
| 26 |
+
self.device = self.resolve_device(settings.device)
|
| 27 |
+
self.model = None
|
| 28 |
+
self.tokenizer = None
|
| 29 |
+
self.threshold: Optional[float] = settings.default_threshold
|
| 30 |
+
self.max_length: Optional[int] = settings.max_length
|
| 31 |
+
self.metadata: Dict[str, Any] = {}
|
| 32 |
+
self.load_error: Optional[str] = None
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def resolve_device(requested_device: str) -> torch.device:
|
| 36 |
+
if requested_device == "cpu":
|
| 37 |
+
return torch.device("cpu")
|
| 38 |
+
if requested_device == "cuda":
|
| 39 |
+
if not torch.cuda.is_available():
|
| 40 |
+
raise RuntimeError("CUDA was requested for the API, but no CUDA device is available.")
|
| 41 |
+
return torch.device("cuda")
|
| 42 |
+
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def ready(self) -> bool:
|
| 46 |
+
return self.model is not None and self.tokenizer is not None and self.load_error is None
|
| 47 |
+
|
| 48 |
+
def load(self) -> None:
|
| 49 |
+
if self.ready:
|
| 50 |
+
return
|
| 51 |
+
|
| 52 |
+
checkpoint_path = self.settings.checkpoint_path
|
| 53 |
+
try:
|
| 54 |
+
if not checkpoint_path.exists():
|
| 55 |
+
raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")
|
| 56 |
+
|
| 57 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
| 58 |
+
checkpoint_cfg = checkpoint.get("config", {})
|
| 59 |
+
checkpoint_dataset_cfg = self.extract_dataset_config(checkpoint_cfg)
|
| 60 |
+
checkpoint_model_cfg = self.extract_model_config(checkpoint_cfg)
|
| 61 |
+
checkpoint_training_cfg = self.extract_training_config(checkpoint_cfg)
|
| 62 |
+
|
| 63 |
+
text_model_name = str(
|
| 64 |
+
checkpoint_model_cfg.get("text_model", "VishnuPJ/MalayaLLM_7B_Base")
|
| 65 |
+
)
|
| 66 |
+
image_model_name = str(checkpoint_model_cfg.get("image_model", "vit_base_patch16_224"))
|
| 67 |
+
embedding_dim = int(checkpoint_model_cfg.get("embedding_dim", 128))
|
| 68 |
+
fusion_method = str(checkpoint.get("fusion_method", checkpoint_model_cfg.get("fusion_methods", ["gated"])[0]))
|
| 69 |
+
language = str(checkpoint_dataset_cfg.get("language", "unknown"))
|
| 70 |
+
dtype_name = str(checkpoint_model_cfg.get("dtype", "float16"))
|
| 71 |
+
use_8bit = bool(checkpoint_model_cfg.get("use_8bit", False) or self.settings.use_8bit)
|
| 72 |
+
max_length = int(checkpoint_training_cfg.get("max_length", self.max_length or 75))
|
| 73 |
+
|
| 74 |
+
threshold = self.settings.default_threshold
|
| 75 |
+
if threshold is None:
|
| 76 |
+
threshold = float(checkpoint.get("best_threshold", 0.5))
|
| 77 |
+
|
| 78 |
+
dtype = resolve_dtype(dtype_name)
|
| 79 |
+
tokenizer, llama = load_tokenizer_and_llama(
|
| 80 |
+
text_model_name,
|
| 81 |
+
use_8bit=bool(use_8bit and self.device.type == "cuda"),
|
| 82 |
+
dtype=dtype,
|
| 83 |
+
device=self.device,
|
| 84 |
+
)
|
| 85 |
+
model = build_model(
|
| 86 |
+
llama=llama,
|
| 87 |
+
image_model_name=image_model_name,
|
| 88 |
+
fusion_method=fusion_method,
|
| 89 |
+
embedding_dim=embedding_dim,
|
| 90 |
+
).to(self.device)
|
| 91 |
+
load_trainable_checkpoint(model, checkpoint)
|
| 92 |
+
model.eval()
|
| 93 |
+
|
| 94 |
+
self.tokenizer = tokenizer
|
| 95 |
+
self.model = model
|
| 96 |
+
self.threshold = threshold
|
| 97 |
+
self.max_length = max_length
|
| 98 |
+
self.metadata = {
|
| 99 |
+
"checkpoint": str(checkpoint_path),
|
| 100 |
+
"device": str(self.device),
|
| 101 |
+
"language": language,
|
| 102 |
+
"text_model": text_model_name,
|
| 103 |
+
"image_model": image_model_name,
|
| 104 |
+
"fusion_method": fusion_method,
|
| 105 |
+
"threshold": threshold,
|
| 106 |
+
"max_length": max_length,
|
| 107 |
+
}
|
| 108 |
+
self.load_error = None
|
| 109 |
+
logger.info("Loaded Fuse-MD checkpoint from %s", checkpoint_path)
|
| 110 |
+
except Exception as exc: # pragma: no cover - defensive path for runtime startup failures
|
| 111 |
+
self.model = None
|
| 112 |
+
self.tokenizer = None
|
| 113 |
+
self.metadata = {
|
| 114 |
+
"checkpoint": str(checkpoint_path),
|
| 115 |
+
"device": str(self.device),
|
| 116 |
+
}
|
| 117 |
+
self.load_error = str(exc)
|
| 118 |
+
logger.exception("Failed to load Fuse-MD API model")
|
| 119 |
+
|
| 120 |
+
@staticmethod
|
| 121 |
+
def extract_dataset_config(checkpoint_cfg: Dict[str, Any]) -> Dict[str, Any]:
|
| 122 |
+
if isinstance(checkpoint_cfg.get("dataset"), dict):
|
| 123 |
+
return checkpoint_cfg["dataset"]
|
| 124 |
+
return checkpoint_cfg
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def extract_model_config(checkpoint_cfg: Dict[str, Any]) -> Dict[str, Any]:
|
| 128 |
+
if isinstance(checkpoint_cfg.get("model"), dict):
|
| 129 |
+
return checkpoint_cfg["model"]
|
| 130 |
+
return checkpoint_cfg
|
| 131 |
+
|
| 132 |
+
@staticmethod
|
| 133 |
+
def extract_training_config(checkpoint_cfg: Dict[str, Any]) -> Dict[str, Any]:
|
| 134 |
+
if isinstance(checkpoint_cfg.get("training"), dict):
|
| 135 |
+
return checkpoint_cfg["training"]
|
| 136 |
+
return checkpoint_cfg
|
| 137 |
+
|
| 138 |
+
def health(self) -> Dict[str, Any]:
|
| 139 |
+
return {
|
| 140 |
+
"status": "ready" if self.ready else "error",
|
| 141 |
+
"ready": self.ready,
|
| 142 |
+
"checkpoint": str(self.settings.checkpoint_path),
|
| 143 |
+
"device": str(self.device),
|
| 144 |
+
"error": self.load_error,
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
def info(self) -> Dict[str, Any]:
|
| 148 |
+
return {
|
| 149 |
+
"ready": self.ready,
|
| 150 |
+
"checkpoint": str(self.settings.checkpoint_path),
|
| 151 |
+
"device": str(self.device),
|
| 152 |
+
"language": self.metadata.get("language"),
|
| 153 |
+
"text_model": self.metadata.get("text_model"),
|
| 154 |
+
"image_model": self.metadata.get("image_model"),
|
| 155 |
+
"fusion_method": self.metadata.get("fusion_method"),
|
| 156 |
+
"threshold": self.metadata.get("threshold"),
|
| 157 |
+
"max_length": self.metadata.get("max_length"),
|
| 158 |
+
"error": self.load_error,
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
def predict(self, text: str, image_bytes: bytes, image_filename: Optional[str], threshold: Optional[float]) -> Dict[str, Any]:
|
| 162 |
+
if not self.ready:
|
| 163 |
+
self.load()
|
| 164 |
+
if not self.ready:
|
| 165 |
+
raise RuntimeError(self.load_error or "Model is not available.")
|
| 166 |
+
|
| 167 |
+
resolved_threshold = float(self.threshold if threshold is None else threshold)
|
| 168 |
+
|
| 169 |
+
tokens = self.tokenizer(
|
| 170 |
+
[text],
|
| 171 |
+
truncation=True,
|
| 172 |
+
max_length=int(self.max_length or 75),
|
| 173 |
+
padding="max_length",
|
| 174 |
+
return_tensors="pt",
|
| 175 |
+
)
|
| 176 |
+
input_ids = tokens.input_ids.to(device=self.device, dtype=torch.long)
|
| 177 |
+
attention_mask = tokens.attention_mask.to(device=self.device, dtype=torch.long)
|
| 178 |
+
image_tensor = self.preprocess_image(image_bytes).to(device=self.device, dtype=torch.float32)
|
| 179 |
+
|
| 180 |
+
with torch.no_grad():
|
| 181 |
+
logits = self.model(input_ids, attention_mask, image_tensor)
|
| 182 |
+
probability = float(torch.sigmoid(logits).reshape(-1)[0].item())
|
| 183 |
+
|
| 184 |
+
predicted_positive = probability >= resolved_threshold
|
| 185 |
+
return {
|
| 186 |
+
"label": "misogyny" if predicted_positive else "not-misogyny",
|
| 187 |
+
"probability": probability,
|
| 188 |
+
"threshold": resolved_threshold,
|
| 189 |
+
"predicted_positive": predicted_positive,
|
| 190 |
+
"fusion_method": str(self.metadata["fusion_method"]),
|
| 191 |
+
"language": str(self.metadata["language"]),
|
| 192 |
+
"checkpoint": str(self.settings.checkpoint_path),
|
| 193 |
+
"image_filename": image_filename,
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
@staticmethod
|
| 197 |
+
def preprocess_image(image_bytes: bytes) -> torch.Tensor:
|
| 198 |
+
image_array = np.frombuffer(image_bytes, dtype=np.uint8)
|
| 199 |
+
image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
|
| 200 |
+
if image is None:
|
| 201 |
+
raise ValueError("Could not decode the uploaded image.")
|
| 202 |
+
|
| 203 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 204 |
+
image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_CUBIC)
|
| 205 |
+
image_tensor = torch.tensor(image, dtype=torch.float32).permute(2, 0, 1) / 255.0
|
| 206 |
+
|
| 207 |
+
# The training pipeline normalizes each split using observed image statistics.
|
| 208 |
+
# For single-sample API inference, use per-image channel normalization.
|
| 209 |
+
mean = image_tensor.mean(dim=(1, 2), keepdim=True)
|
| 210 |
+
std = image_tensor.std(dim=(1, 2), keepdim=True).clamp_min(1e-6)
|
| 211 |
+
image_tensor = (image_tensor - mean) / std
|
| 212 |
+
|
| 213 |
+
return image_tensor.unsqueeze(0)
|
api/local_config.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Update this once to point at the checkpoint you want the easy-mode API to use.
|
| 7 |
+
CHECKPOINT_PATH = (
|
| 8 |
+
"trained_model/tamil/fusion/"
|
| 9 |
+
"custom_tamil_llamavit_fusion_element_lr1e-05_epoch4_bs16_20260425_231136.pth"
|
| 10 |
+
)
|
| 11 |
+
LOCAL_MODEL_ROOT = "local_models"
|
| 12 |
+
HOST = "127.0.0.1"
|
| 13 |
+
PORT = 8000
|
| 14 |
+
DEVICE = "auto"
|
| 15 |
+
THRESHOLD = None
|
| 16 |
+
MAX_LENGTH = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(frozen=True)
|
| 20 |
+
class LocalAPIConfig:
|
| 21 |
+
checkpoint_path: Path
|
| 22 |
+
local_model_root: Path
|
| 23 |
+
host: str
|
| 24 |
+
port: int
|
| 25 |
+
device: str
|
| 26 |
+
threshold: Optional[float]
|
| 27 |
+
max_length: Optional[int]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def repo_root() -> Path:
|
| 31 |
+
return Path(__file__).resolve().parents[1]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def resolve_repo_path(raw_path: str) -> Path:
|
| 35 |
+
path = Path(raw_path)
|
| 36 |
+
if path.is_absolute():
|
| 37 |
+
return path
|
| 38 |
+
return (repo_root() / path).resolve()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def load_local_api_config() -> LocalAPIConfig:
|
| 42 |
+
return LocalAPIConfig(
|
| 43 |
+
checkpoint_path=resolve_repo_path(CHECKPOINT_PATH),
|
| 44 |
+
local_model_root=resolve_repo_path(LOCAL_MODEL_ROOT),
|
| 45 |
+
host=str(HOST),
|
| 46 |
+
port=int(PORT),
|
| 47 |
+
device=str(DEVICE).strip().lower(),
|
| 48 |
+
threshold=None if THRESHOLD is None else float(THRESHOLD),
|
| 49 |
+
max_length=None if MAX_LENGTH is None else int(MAX_LENGTH),
|
| 50 |
+
)
|
api/predict.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
import urllib.error
|
| 5 |
+
import urllib.parse
|
| 6 |
+
import urllib.request
|
| 7 |
+
import uuid
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
from local_config import load_local_api_config
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def parse_args() -> argparse.Namespace:
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description="Send a local prediction request to the Fuse-MD FastAPI server."
|
| 17 |
+
)
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
"--image",
|
| 20 |
+
required=True,
|
| 21 |
+
help="Path to the image file to upload.",
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"--text",
|
| 25 |
+
required=True,
|
| 26 |
+
help="Text or OCR transcription for the meme.",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"--threshold",
|
| 30 |
+
type=float,
|
| 31 |
+
help="Optional threshold override for this request.",
|
| 32 |
+
)
|
| 33 |
+
parser.add_argument(
|
| 34 |
+
"--url",
|
| 35 |
+
help="Prediction endpoint URL. Defaults to the local API URL from api/local_config.py.",
|
| 36 |
+
)
|
| 37 |
+
return parser.parse_args()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def default_predict_url() -> str:
|
| 41 |
+
config = load_local_api_config()
|
| 42 |
+
return f"http://{config.host}:{config.port}/predict"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def encode_multipart_form(
|
| 46 |
+
*,
|
| 47 |
+
text: str,
|
| 48 |
+
image_path: Path,
|
| 49 |
+
image_bytes: bytes,
|
| 50 |
+
threshold: Optional[float],
|
| 51 |
+
) -> tuple[bytes, str]:
|
| 52 |
+
boundary = f"fusemd-{uuid.uuid4().hex}"
|
| 53 |
+
lines: list[bytes] = []
|
| 54 |
+
|
| 55 |
+
def add_field(name: str, value: str) -> None:
|
| 56 |
+
lines.extend(
|
| 57 |
+
[
|
| 58 |
+
f"--{boundary}".encode("utf-8"),
|
| 59 |
+
f'Content-Disposition: form-data; name="{name}"'.encode("utf-8"),
|
| 60 |
+
b"",
|
| 61 |
+
value.encode("utf-8"),
|
| 62 |
+
]
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
add_field("text", text)
|
| 66 |
+
if threshold is not None:
|
| 67 |
+
add_field("threshold", str(threshold))
|
| 68 |
+
|
| 69 |
+
lines.extend(
|
| 70 |
+
[
|
| 71 |
+
f"--{boundary}".encode("utf-8"),
|
| 72 |
+
(
|
| 73 |
+
f'Content-Disposition: form-data; name="image"; filename="{image_path.name}"'
|
| 74 |
+
).encode("utf-8"),
|
| 75 |
+
b"Content-Type: application/octet-stream",
|
| 76 |
+
b"",
|
| 77 |
+
image_bytes,
|
| 78 |
+
f"--{boundary}--".encode("utf-8"),
|
| 79 |
+
b"",
|
| 80 |
+
]
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
body = b"\r\n".join(lines)
|
| 84 |
+
return body, boundary
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main() -> int:
|
| 88 |
+
args = parse_args()
|
| 89 |
+
image_path = Path(args.image)
|
| 90 |
+
if not image_path.is_absolute():
|
| 91 |
+
image_path = (Path.cwd() / image_path).resolve()
|
| 92 |
+
|
| 93 |
+
if not image_path.exists():
|
| 94 |
+
print(f"Image not found: {image_path}")
|
| 95 |
+
return 1
|
| 96 |
+
|
| 97 |
+
if not image_path.is_file():
|
| 98 |
+
print(f"Image path is not a file: {image_path}")
|
| 99 |
+
return 1
|
| 100 |
+
|
| 101 |
+
image_bytes = image_path.read_bytes()
|
| 102 |
+
url = args.url or default_predict_url()
|
| 103 |
+
body, boundary = encode_multipart_form(
|
| 104 |
+
text=args.text,
|
| 105 |
+
image_path=image_path,
|
| 106 |
+
image_bytes=image_bytes,
|
| 107 |
+
threshold=args.threshold,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
request = urllib.request.Request(
|
| 111 |
+
url=url,
|
| 112 |
+
data=body,
|
| 113 |
+
method="POST",
|
| 114 |
+
headers={
|
| 115 |
+
"Content-Type": f"multipart/form-data; boundary={boundary}",
|
| 116 |
+
"Content-Length": str(len(body)),
|
| 117 |
+
},
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
with urllib.request.urlopen(request) as response:
|
| 122 |
+
payload = json.loads(response.read().decode("utf-8"))
|
| 123 |
+
print(json.dumps(payload, indent=2))
|
| 124 |
+
return 0
|
| 125 |
+
except urllib.error.HTTPError as exc:
|
| 126 |
+
detail = exc.read().decode("utf-8", errors="replace")
|
| 127 |
+
print(f"API request failed with status {exc.code}.")
|
| 128 |
+
print(detail)
|
| 129 |
+
return 1
|
| 130 |
+
except urllib.error.URLError as exc:
|
| 131 |
+
parsed = urllib.parse.urlparse(url)
|
| 132 |
+
base_url = f"{parsed.scheme}://{parsed.netloc}" if parsed.scheme and parsed.netloc else url
|
| 133 |
+
print(f"Could not connect to Fuse-MD API at {base_url}.")
|
| 134 |
+
print("Start it first with: python api/run_api.py")
|
| 135 |
+
print(f"Connection error: {exc.reason}")
|
| 136 |
+
return 1
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
sys.exit(main())
|
api/run_api.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import uvicorn
|
| 8 |
+
|
| 9 |
+
from local_config import load_local_api_config, resolve_repo_path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parse_args() -> argparse.Namespace:
|
| 13 |
+
parser = argparse.ArgumentParser(
|
| 14 |
+
description="Start the Fuse-MD FastAPI server using local easy-mode defaults."
|
| 15 |
+
)
|
| 16 |
+
parser.add_argument(
|
| 17 |
+
"--checkpoint",
|
| 18 |
+
help="Checkpoint path to use instead of api/local_config.py.",
|
| 19 |
+
)
|
| 20 |
+
parser.add_argument(
|
| 21 |
+
"--device",
|
| 22 |
+
choices=["auto", "cpu", "cuda"],
|
| 23 |
+
help="Device override for the API server.",
|
| 24 |
+
)
|
| 25 |
+
parser.add_argument(
|
| 26 |
+
"--host",
|
| 27 |
+
help="Host override for the API server.",
|
| 28 |
+
)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--port",
|
| 31 |
+
type=int,
|
| 32 |
+
help="Port override for the API server.",
|
| 33 |
+
)
|
| 34 |
+
return parser.parse_args()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_effective_config(
|
| 38 |
+
args: argparse.Namespace,
|
| 39 |
+
) -> tuple[Path, Path, str, int, str, Optional[str], Optional[str]]:
|
| 40 |
+
config = load_local_api_config()
|
| 41 |
+
checkpoint_path = (
|
| 42 |
+
resolve_repo_path(args.checkpoint) if args.checkpoint else config.checkpoint_path
|
| 43 |
+
)
|
| 44 |
+
local_model_root = config.local_model_root
|
| 45 |
+
host = args.host or config.host
|
| 46 |
+
port = args.port or config.port
|
| 47 |
+
device = (args.device or config.device).strip().lower()
|
| 48 |
+
threshold = None if config.threshold is None else str(config.threshold)
|
| 49 |
+
max_length = None if config.max_length is None else str(config.max_length)
|
| 50 |
+
return checkpoint_path, local_model_root, host, port, device, threshold, max_length
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def configure_environment(
|
| 54 |
+
checkpoint_path: Path,
|
| 55 |
+
local_model_root: Path,
|
| 56 |
+
host: str,
|
| 57 |
+
port: int,
|
| 58 |
+
device: str,
|
| 59 |
+
threshold: Optional[str],
|
| 60 |
+
max_length: Optional[str],
|
| 61 |
+
) -> None:
|
| 62 |
+
os.environ["FUSEMD_CHECKPOINT"] = str(checkpoint_path)
|
| 63 |
+
os.environ["FUSEMD_LOCAL_MODEL_ROOT"] = str(local_model_root)
|
| 64 |
+
os.environ["FUSEMD_HOST"] = host
|
| 65 |
+
os.environ["FUSEMD_PORT"] = str(port)
|
| 66 |
+
os.environ["FUSEMD_DEVICE"] = device
|
| 67 |
+
|
| 68 |
+
if threshold is None:
|
| 69 |
+
os.environ.pop("FUSEMD_THRESHOLD", None)
|
| 70 |
+
else:
|
| 71 |
+
os.environ["FUSEMD_THRESHOLD"] = threshold
|
| 72 |
+
|
| 73 |
+
if max_length is None:
|
| 74 |
+
os.environ.pop("FUSEMD_MAX_LENGTH", None)
|
| 75 |
+
else:
|
| 76 |
+
os.environ["FUSEMD_MAX_LENGTH"] = max_length
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def main() -> int:
|
| 80 |
+
args = parse_args()
|
| 81 |
+
checkpoint_path, local_model_root, host, port, device, threshold, max_length = build_effective_config(args)
|
| 82 |
+
|
| 83 |
+
if not checkpoint_path.exists():
|
| 84 |
+
print("Fuse-MD API could not start.")
|
| 85 |
+
print(f"Checkpoint not found: {checkpoint_path}")
|
| 86 |
+
print("Update CHECKPOINT_PATH in api/local_config.py or pass --checkpoint.")
|
| 87 |
+
return 1
|
| 88 |
+
|
| 89 |
+
configure_environment(checkpoint_path, local_model_root, host, port, device, threshold, max_length)
|
| 90 |
+
base_url = f"http://{host}:{port}"
|
| 91 |
+
print("Starting Fuse-MD API")
|
| 92 |
+
print(f"Checkpoint: {checkpoint_path}")
|
| 93 |
+
print(f"Local model root: {local_model_root}")
|
| 94 |
+
print(f"Device: {device}")
|
| 95 |
+
print(f"URL: {base_url}")
|
| 96 |
+
print(f"Docs: {base_url}/docs")
|
| 97 |
+
|
| 98 |
+
from api.app import app
|
| 99 |
+
|
| 100 |
+
uvicorn.run(app, host=host, port=port)
|
| 101 |
+
return 0
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
sys.exit(main())
|
api/setup_local_model.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import shutil
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from huggingface_hub import snapshot_download
|
| 9 |
+
|
| 10 |
+
from local_config import load_local_api_config, repo_root, resolve_repo_path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ROOT = repo_root()
|
| 14 |
+
if str(ROOT) not in sys.path:
|
| 15 |
+
sys.path.insert(0, str(ROOT))
|
| 16 |
+
|
| 17 |
+
from src.models.local_store import expected_local_model_path
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def parse_args() -> argparse.Namespace:
|
| 21 |
+
parser = argparse.ArgumentParser(
|
| 22 |
+
description="Download a Hugging Face text model once into Fuse-MD's local_models store."
|
| 23 |
+
)
|
| 24 |
+
parser.add_argument(
|
| 25 |
+
"--model",
|
| 26 |
+
help="Hugging Face model id to download, for example VishnuPJ/MalayaLLM_7B_Base.",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"--checkpoint",
|
| 30 |
+
help="Checkpoint path to inspect and infer the required text model.",
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument(
|
| 33 |
+
"--root",
|
| 34 |
+
help="Override the local model root. Defaults to api/local_config.py.",
|
| 35 |
+
)
|
| 36 |
+
parser.add_argument(
|
| 37 |
+
"--force",
|
| 38 |
+
action="store_true",
|
| 39 |
+
help="Re-download into the target folder even if it already exists.",
|
| 40 |
+
)
|
| 41 |
+
return parser.parse_args()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def infer_text_model_from_checkpoint(checkpoint_path: Path) -> str:
|
| 45 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
| 46 |
+
checkpoint_cfg = checkpoint.get("config", {})
|
| 47 |
+
if isinstance(checkpoint_cfg.get("model"), dict):
|
| 48 |
+
checkpoint_cfg = checkpoint_cfg["model"]
|
| 49 |
+
|
| 50 |
+
text_model = checkpoint_cfg.get("text_model")
|
| 51 |
+
if not text_model:
|
| 52 |
+
raise KeyError(f"Checkpoint does not define a text model: {checkpoint_path}")
|
| 53 |
+
return str(text_model)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def choose_model_id(args: argparse.Namespace) -> str:
|
| 57 |
+
if args.model:
|
| 58 |
+
return str(args.model)
|
| 59 |
+
|
| 60 |
+
if args.checkpoint:
|
| 61 |
+
checkpoint_path = resolve_repo_path(args.checkpoint)
|
| 62 |
+
if not checkpoint_path.exists():
|
| 63 |
+
raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")
|
| 64 |
+
return infer_text_model_from_checkpoint(checkpoint_path)
|
| 65 |
+
|
| 66 |
+
config = load_local_api_config()
|
| 67 |
+
if not config.checkpoint_path.exists():
|
| 68 |
+
raise FileNotFoundError(
|
| 69 |
+
"No model id was provided and the default checkpoint is missing. "
|
| 70 |
+
"Pass --model or --checkpoint."
|
| 71 |
+
)
|
| 72 |
+
return infer_text_model_from_checkpoint(config.checkpoint_path)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def resolved_root_arg(args: argparse.Namespace) -> str:
|
| 76 |
+
if args.root:
|
| 77 |
+
return str(resolve_repo_path(args.root))
|
| 78 |
+
return str(load_local_api_config().local_model_root)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def verify_model_files(target_path: Path) -> None:
|
| 82 |
+
required_files = [target_path / "config.json", target_path / "tokenizer_config.json"]
|
| 83 |
+
missing_files = [path.name for path in required_files if not path.exists()]
|
| 84 |
+
if missing_files:
|
| 85 |
+
raise FileNotFoundError(
|
| 86 |
+
f"Downloaded model is incomplete at {target_path}. Missing: {', '.join(missing_files)}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
has_weights = any(
|
| 90 |
+
(target_path / file_name).exists()
|
| 91 |
+
for file_name in (
|
| 92 |
+
"model.safetensors",
|
| 93 |
+
"model.safetensors.index.json",
|
| 94 |
+
"pytorch_model.bin",
|
| 95 |
+
"pytorch_model.bin.index.json",
|
| 96 |
+
)
|
| 97 |
+
)
|
| 98 |
+
if not has_weights:
|
| 99 |
+
raise FileNotFoundError(
|
| 100 |
+
f"Downloaded model is incomplete at {target_path}. Missing model weights."
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
for index_name in ("pytorch_model.bin.index.json", "model.safetensors.index.json"):
|
| 104 |
+
index_path = target_path / index_name
|
| 105 |
+
if not index_path.exists():
|
| 106 |
+
continue
|
| 107 |
+
|
| 108 |
+
with open(index_path, "r", encoding="utf-8") as file:
|
| 109 |
+
index_payload = json.load(file)
|
| 110 |
+
|
| 111 |
+
weight_map = index_payload.get("weight_map", {})
|
| 112 |
+
shard_names = sorted(set(str(name) for name in weight_map.values()))
|
| 113 |
+
missing_shards = [name for name in shard_names if not (target_path / name).exists()]
|
| 114 |
+
if missing_shards:
|
| 115 |
+
raise FileNotFoundError(
|
| 116 |
+
f"Downloaded model is incomplete at {target_path}. Missing shard files: "
|
| 117 |
+
f"{', '.join(missing_shards)}"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def safe_remove_tree(target_path: Path, root_path: Path) -> None:
|
| 122 |
+
resolved_target = target_path.resolve()
|
| 123 |
+
resolved_root = root_path.resolve()
|
| 124 |
+
if resolved_target == resolved_root or resolved_root not in resolved_target.parents:
|
| 125 |
+
raise ValueError(f"Refusing to remove path outside local model root: {resolved_target}")
|
| 126 |
+
shutil.rmtree(resolved_target)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def main() -> int:
|
| 130 |
+
args = parse_args()
|
| 131 |
+
model_id = choose_model_id(args)
|
| 132 |
+
root_arg = resolved_root_arg(args)
|
| 133 |
+
root_path = Path(root_arg)
|
| 134 |
+
target_path = expected_local_model_path(model_id, root_arg)
|
| 135 |
+
root_path.mkdir(parents=True, exist_ok=True)
|
| 136 |
+
|
| 137 |
+
if target_path.exists() and args.force:
|
| 138 |
+
safe_remove_tree(target_path, root_path)
|
| 139 |
+
|
| 140 |
+
if target_path.exists():
|
| 141 |
+
verify_model_files(target_path)
|
| 142 |
+
print(f"Local model already exists: {target_path}")
|
| 143 |
+
print("Use --force to re-download it.")
|
| 144 |
+
return 0
|
| 145 |
+
|
| 146 |
+
print(f"Downloading model: {model_id}")
|
| 147 |
+
print(f"Target folder: {target_path}")
|
| 148 |
+
snapshot_download(repo_id=model_id, local_dir=str(target_path))
|
| 149 |
+
verify_model_files(target_path)
|
| 150 |
+
print("Local model download complete.")
|
| 151 |
+
print(f"Saved to: {target_path}")
|
| 152 |
+
return 0
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
sys.exit(main())
|
hf_space/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Fuse-MD
|
| 3 |
+
emoji: 🔎
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
app_file: app.py
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Fuse-MD
|
| 12 |
+
|
| 13 |
+
Research demo for multimodal misogyny-meme detection in Malayalam.
|
hf_space/app.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fuse-MD Hugging Face ZeroGPU demo.
|
| 2 |
+
|
| 3 |
+
The Space must also contain the ``src`` and ``api`` folders and the selected
|
| 4 |
+
checkpoint at the repository root. The large text backbone is downloaded from
|
| 5 |
+
the Hugging Face Hub during startup.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
import spaces
|
| 15 |
+
GPU = spaces.GPU
|
| 16 |
+
except ImportError: # pragma: no cover - local-only fallback
|
| 17 |
+
def GPU(*args, **kwargs):
|
| 18 |
+
def decorate(function):
|
| 19 |
+
return function
|
| 20 |
+
return decorate
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
from huggingface_hub import snapshot_download
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
ROOT = Path(__file__).resolve().parent
|
| 27 |
+
sys.path.insert(0, str(ROOT))
|
| 28 |
+
|
| 29 |
+
TEXT_MODEL = "VishnuPJ/MalayaLLM_7B_Base"
|
| 30 |
+
CHECKPOINT = ROOT / "custom_malayalam_llamavit_fusion_element.pth"
|
| 31 |
+
MODEL_DIR = ROOT / ".hf_model_cache" / "VishnuPJ__MalayaLLM_7B_Base"
|
| 32 |
+
|
| 33 |
+
# Download one text backbone only. Keeping a single language model reduces
|
| 34 |
+
# startup time and storage usage for the free demo.
|
| 35 |
+
if not MODEL_DIR.exists():
|
| 36 |
+
snapshot_download(repo_id=TEXT_MODEL, local_dir=MODEL_DIR)
|
| 37 |
+
|
| 38 |
+
os.environ.setdefault("FUSEMD_CHECKPOINT", str(CHECKPOINT))
|
| 39 |
+
os.environ.setdefault("FUSEMD_LOCAL_MODEL_ROOT", str(ROOT / ".hf_model_cache"))
|
| 40 |
+
os.environ.setdefault("FUSEMD_DEVICE", "cuda")
|
| 41 |
+
|
| 42 |
+
from api.api.config import settings # noqa: E402
|
| 43 |
+
from api.api.service import FuseMDService # noqa: E402
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
service = FuseMDService(settings)
|
| 47 |
+
service.load()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@GPU(duration=120)
|
| 51 |
+
def predict(image_path, text, threshold):
|
| 52 |
+
if image_path is None:
|
| 53 |
+
return "Please upload a meme image."
|
| 54 |
+
|
| 55 |
+
started = time.perf_counter()
|
| 56 |
+
with open(image_path, "rb") as image_file:
|
| 57 |
+
response = service.predict(
|
| 58 |
+
text=text or "",
|
| 59 |
+
image_bytes=image_file.read(),
|
| 60 |
+
image_filename=Path(image_path).name,
|
| 61 |
+
threshold=threshold,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
elapsed = time.perf_counter() - started
|
| 65 |
+
return (
|
| 66 |
+
f"### Prediction: **{response['label']}**\n\n"
|
| 67 |
+
f"Positive probability: **{response['probability']:.1%}**\n\n"
|
| 68 |
+
f"Threshold: {response['threshold']:.2f} | "
|
| 69 |
+
f"Language: {response['language']} | Fusion: {response['fusion_method']}\n\n"
|
| 70 |
+
f"Runtime: **{elapsed:.1f} seconds**"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
with gr.Blocks(title="Fuse-MD Demo") as demo:
|
| 75 |
+
gr.Markdown(
|
| 76 |
+
"# Fuse-MD\n"
|
| 77 |
+
"Upload a Malayalam meme and enter its transcription. The model predicts "
|
| 78 |
+
"whether it contains misogynistic content."
|
| 79 |
+
)
|
| 80 |
+
with gr.Row():
|
| 81 |
+
image = gr.Image(type="filepath", label="Meme image", width=420, height=420)
|
| 82 |
+
text = gr.Textbox(label="Meme transcription", lines=5)
|
| 83 |
+
threshold = gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Decision threshold")
|
| 84 |
+
button = gr.Button("Predict", variant="primary")
|
| 85 |
+
result = gr.Markdown()
|
| 86 |
+
button.click(predict, inputs=[image, text, threshold], outputs=result)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
demo.queue().launch()
|
hf_space/requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
spaces
|
| 2 |
+
gradio
|
| 3 |
+
huggingface_hub
|
| 4 |
+
transformers
|
| 5 |
+
accelerate
|
| 6 |
+
bitsandbytes
|
| 7 |
+
timm
|
| 8 |
+
opencv-python-headless
|
| 9 |
+
fastapi
|
| 10 |
+
python-multipart
|
src/README.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project structure
|
| 2 |
+
|
| 3 |
+
The `src` folder hosts the Fuse-MD implementation.
|
| 4 |
+
|
| 5 |
+
```
|
| 6 |
+
configs/ Hydra configuration for dataset, model, and training
|
| 7 |
+
models/ Fuse-MD model components
|
| 8 |
+
dataset.py Multimodal meme dataset loader
|
| 9 |
+
train.py Training and evaluation helpers
|
| 10 |
+
main.py Training entrypoint
|
| 11 |
+
inference.py Checkpoint inference entrypoint
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
The default data location is `../data` relative to `src/`, configured as `data` from the project root in `configs/dataset/default.yaml`.
|
src/configs/config.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
defaults:
|
| 2 |
+
- model: default
|
| 3 |
+
- dataset: default
|
| 4 |
+
- training: default
|
| 5 |
+
- override hydra/job_logging: colorlog
|
| 6 |
+
- override hydra/hydra_logging: colorlog
|
src/configs/dataset/default.yaml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
data_root: data
|
| 2 |
+
output_root: .
|
| 3 |
+
language: malayalam
|
| 4 |
+
train_split: train
|
| 5 |
+
dev_split: dev
|
| 6 |
+
test_split: test
|
| 7 |
+
inference_split: test
|
| 8 |
+
image_id_col: image_id
|
| 9 |
+
text_col: transcriptions
|
| 10 |
+
label_col: original_labels
|
| 11 |
+
finetuned_model_path: trained_model/malayalam/fusion/fusemd_best.pth
|
| 12 |
+
save_metrics_path: predictions/malayalam/inference/metrics.json
|
| 13 |
+
save_preds_path: predictions/malayalam/inference/preds.csv
|
src/configs/model/default.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
text_model: VishnuPJ/MalayaLLM_7B_Base
|
| 2 |
+
image_model: vit_base_patch16_224
|
| 3 |
+
embedding_dim: 128
|
| 4 |
+
fusion_methods:
|
| 5 |
+
- gated
|
| 6 |
+
use_8bit: false
|
| 7 |
+
dtype: float16
|
src/configs/training/default.yaml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
max_epochs: 10
|
| 2 |
+
learning_rates:
|
| 3 |
+
- 1e-5
|
| 4 |
+
batch_size: 16
|
| 5 |
+
max_length: 75
|
| 6 |
+
num_workers: 0
|
| 7 |
+
optimizer_eps: 1e-4
|
| 8 |
+
scheduler_factor: 0.5
|
| 9 |
+
scheduler_patience: 2
|
| 10 |
+
scheduler_threshold: 1e-3
|
| 11 |
+
early_stopping_patience: 5
|
| 12 |
+
oversample_positive_train: 3
|
| 13 |
+
threshold_start: 0.1
|
| 14 |
+
threshold_stop: 0.9
|
| 15 |
+
threshold_step: 0.1
|
| 16 |
+
threshold: null
|
| 17 |
+
seed: 42
|
| 18 |
+
save_confusion_matrix_png: true
|
src/dataset.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Dict, List, Tuple
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import Dataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def normalize_label(value: object) -> float:
|
| 11 |
+
if isinstance(value, str):
|
| 12 |
+
normalized = value.strip().lower()
|
| 13 |
+
if normalized in {"misogyny", "misogynous", "1", "true"}:
|
| 14 |
+
return 1.0
|
| 15 |
+
if normalized in {"not-misogyny", "not misogyny", "non-misogyny", "0", "false"}:
|
| 16 |
+
return 0.0
|
| 17 |
+
raise ValueError(f"Unsupported label value: {value!r}")
|
| 18 |
+
return float(value)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class MemeDataset(Dataset):
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
split: str,
|
| 25 |
+
data_root: Path,
|
| 26 |
+
language: str,
|
| 27 |
+
tokenizer,
|
| 28 |
+
image_id_col: str,
|
| 29 |
+
text_col: str,
|
| 30 |
+
label_col: str,
|
| 31 |
+
max_length: int,
|
| 32 |
+
oversample_positive_train: int = 0,
|
| 33 |
+
) -> None:
|
| 34 |
+
self.split = split
|
| 35 |
+
self.split_path = data_root / language / split
|
| 36 |
+
self.tokenizer = tokenizer
|
| 37 |
+
|
| 38 |
+
csv_path = self.split_path / f"{split}.csv"
|
| 39 |
+
if not csv_path.exists():
|
| 40 |
+
raise FileNotFoundError(f"Missing CSV file: {csv_path}")
|
| 41 |
+
|
| 42 |
+
df = pd.read_csv(csv_path).dropna(axis=0).copy()
|
| 43 |
+
required_cols = {image_id_col, text_col, label_col}
|
| 44 |
+
missing_cols = required_cols.difference(df.columns)
|
| 45 |
+
if missing_cols:
|
| 46 |
+
raise ValueError(f"{csv_path} is missing columns: {sorted(missing_cols)}")
|
| 47 |
+
|
| 48 |
+
df[image_id_col] = df[image_id_col].astype(int)
|
| 49 |
+
df[label_col] = df[label_col].map(normalize_label)
|
| 50 |
+
id_to_row = {int(row[image_id_col]): row for _, row in df.iterrows()}
|
| 51 |
+
|
| 52 |
+
raw_images: List[torch.Tensor] = []
|
| 53 |
+
raw_records: List[Tuple[int, str, float]] = []
|
| 54 |
+
for image_file in sorted(self.split_path.iterdir()):
|
| 55 |
+
if image_file.suffix.lower() == ".csv":
|
| 56 |
+
continue
|
| 57 |
+
if image_file.suffix.lower() not in {".jpg", ".jpeg", ".png", ".bmp", ".webp"}:
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
image_id = int(image_file.stem)
|
| 62 |
+
except ValueError:
|
| 63 |
+
continue
|
| 64 |
+
|
| 65 |
+
if image_id not in id_to_row:
|
| 66 |
+
continue
|
| 67 |
+
|
| 68 |
+
image = cv2.imread(str(image_file))
|
| 69 |
+
if image is None:
|
| 70 |
+
raise ValueError(f"Could not read image: {image_file}")
|
| 71 |
+
|
| 72 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 73 |
+
image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_CUBIC)
|
| 74 |
+
image_tensor = torch.tensor(image, dtype=torch.float32).permute(2, 0, 1) / 255.0
|
| 75 |
+
raw_images.append(image_tensor)
|
| 76 |
+
|
| 77 |
+
row = id_to_row[image_id]
|
| 78 |
+
raw_records.append((image_id, str(row[text_col]), float(row[label_col])))
|
| 79 |
+
|
| 80 |
+
if not raw_records:
|
| 81 |
+
raise ValueError(f"No valid examples found in {self.split_path}")
|
| 82 |
+
|
| 83 |
+
image_stack = torch.stack(raw_images, dim=0)
|
| 84 |
+
mean = image_stack.mean(dim=(0, 2, 3), keepdim=True)
|
| 85 |
+
std = image_stack.std(dim=(0, 2, 3), keepdim=True).clamp_min(1e-6)
|
| 86 |
+
image_stack = (image_stack - mean) / std
|
| 87 |
+
|
| 88 |
+
self.images: List[torch.Tensor] = []
|
| 89 |
+
self.labels: List[float] = []
|
| 90 |
+
self.image_ids: List[int] = []
|
| 91 |
+
texts: List[str] = []
|
| 92 |
+
|
| 93 |
+
for idx, (image_id, text, label) in enumerate(raw_records):
|
| 94 |
+
repeat = 1
|
| 95 |
+
if split == "train" and int(label) == 1 and oversample_positive_train > 0:
|
| 96 |
+
repeat += oversample_positive_train
|
| 97 |
+
|
| 98 |
+
for _ in range(repeat):
|
| 99 |
+
self.images.append(image_stack[idx])
|
| 100 |
+
self.labels.append(label)
|
| 101 |
+
self.image_ids.append(image_id)
|
| 102 |
+
texts.append(text)
|
| 103 |
+
|
| 104 |
+
tokens = tokenizer(
|
| 105 |
+
texts,
|
| 106 |
+
truncation=True,
|
| 107 |
+
max_length=max_length,
|
| 108 |
+
padding="max_length",
|
| 109 |
+
return_tensors="pt",
|
| 110 |
+
)
|
| 111 |
+
self.input_ids = tokens.input_ids
|
| 112 |
+
self.attention_mask = tokens.attention_mask
|
| 113 |
+
|
| 114 |
+
def __len__(self) -> int:
|
| 115 |
+
return len(self.labels)
|
| 116 |
+
|
| 117 |
+
def __getitem__(self, index: int) -> Dict[str, torch.Tensor]:
|
| 118 |
+
return {
|
| 119 |
+
"image": self.images[index],
|
| 120 |
+
"label": torch.tensor(self.labels[index], dtype=torch.float32),
|
| 121 |
+
"input_ids": self.input_ids[index],
|
| 122 |
+
"attention_mask": self.attention_mask[index],
|
| 123 |
+
"image_id": torch.tensor(self.image_ids[index], dtype=torch.long),
|
| 124 |
+
}
|
src/inference.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import random
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import hydra
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from omegaconf import OmegaConf
|
| 10 |
+
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, f1_score, precision_score, recall_score
|
| 11 |
+
from torch.utils.data import DataLoader
|
| 12 |
+
|
| 13 |
+
from dataset import MemeDataset
|
| 14 |
+
from models import build_model, load_tokenizer_and_llama, load_trainable_checkpoint, resolve_dtype
|
| 15 |
+
from train import collect_probabilities
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def template_root() -> Path:
|
| 22 |
+
return Path(__file__).resolve().parents[1]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def resolve_template_path(raw_path: str) -> Path:
|
| 26 |
+
path = Path(str(raw_path))
|
| 27 |
+
if path.is_absolute():
|
| 28 |
+
return path
|
| 29 |
+
return (template_root() / path).resolve()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def set_seed(seed: int) -> None:
|
| 33 |
+
random.seed(seed)
|
| 34 |
+
np.random.seed(seed)
|
| 35 |
+
torch.manual_seed(seed)
|
| 36 |
+
if torch.cuda.is_available():
|
| 37 |
+
torch.cuda.manual_seed_all(seed)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def flatten_probs(probs: np.ndarray) -> np.ndarray:
|
| 41 |
+
return probs.reshape(-1)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@hydra.main(version_base=None, config_path="./configs", config_name="config")
|
| 45 |
+
def main(cfg) -> None:
|
| 46 |
+
logger.info(OmegaConf.to_yaml(cfg, resolve=True))
|
| 47 |
+
set_seed(cfg.training.seed)
|
| 48 |
+
|
| 49 |
+
checkpoint_path = resolve_template_path(cfg.dataset.finetuned_model_path)
|
| 50 |
+
if not checkpoint_path.exists():
|
| 51 |
+
raise FileNotFoundError(f"Missing checkpoint: {checkpoint_path}")
|
| 52 |
+
|
| 53 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 54 |
+
dtype = resolve_dtype(cfg.model.dtype)
|
| 55 |
+
use_8bit = bool(cfg.model.use_8bit and device.type == "cuda")
|
| 56 |
+
checkpoint = torch.load(checkpoint_path, map_location="cpu")
|
| 57 |
+
checkpoint_cfg = checkpoint.get("config", {})
|
| 58 |
+
checkpoint_dataset_cfg = checkpoint_cfg.get("dataset", {})
|
| 59 |
+
checkpoint_model_cfg = checkpoint_cfg.get("model", {})
|
| 60 |
+
|
| 61 |
+
fusion_method = str(checkpoint.get("fusion_method", cfg.model.fusion_methods[0]))
|
| 62 |
+
threshold = cfg.training.threshold
|
| 63 |
+
if threshold is None:
|
| 64 |
+
threshold = float(checkpoint.get("best_threshold", 0.5))
|
| 65 |
+
|
| 66 |
+
text_model_name = str(checkpoint_model_cfg.get("text_model", cfg.model.text_model))
|
| 67 |
+
image_model_name = str(checkpoint_model_cfg.get("image_model", cfg.model.image_model))
|
| 68 |
+
embedding_dim = int(checkpoint_model_cfg.get("embedding_dim", cfg.model.embedding_dim))
|
| 69 |
+
language = str(checkpoint_dataset_cfg.get("language", cfg.dataset.language))
|
| 70 |
+
image_id_col = str(checkpoint_dataset_cfg.get("image_id_col", cfg.dataset.image_id_col))
|
| 71 |
+
text_col = str(checkpoint_dataset_cfg.get("text_col", cfg.dataset.text_col))
|
| 72 |
+
label_col = str(checkpoint_dataset_cfg.get("label_col", cfg.dataset.label_col))
|
| 73 |
+
|
| 74 |
+
tokenizer, llama = load_tokenizer_and_llama(text_model_name, use_8bit, dtype, device)
|
| 75 |
+
dataset = MemeDataset(
|
| 76 |
+
split=cfg.dataset.inference_split,
|
| 77 |
+
data_root=resolve_template_path(cfg.dataset.data_root),
|
| 78 |
+
language=language,
|
| 79 |
+
tokenizer=tokenizer,
|
| 80 |
+
image_id_col=image_id_col,
|
| 81 |
+
text_col=text_col,
|
| 82 |
+
label_col=label_col,
|
| 83 |
+
max_length=cfg.training.max_length,
|
| 84 |
+
oversample_positive_train=0,
|
| 85 |
+
)
|
| 86 |
+
loader = DataLoader(
|
| 87 |
+
dataset,
|
| 88 |
+
batch_size=cfg.training.batch_size,
|
| 89 |
+
shuffle=False,
|
| 90 |
+
drop_last=False,
|
| 91 |
+
num_workers=cfg.training.num_workers,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
model = build_model(llama, image_model_name, fusion_method, embedding_dim).to(device)
|
| 95 |
+
load_trainable_checkpoint(model, checkpoint)
|
| 96 |
+
model.eval()
|
| 97 |
+
|
| 98 |
+
probs, labels, image_ids = collect_probabilities(model, loader, device)
|
| 99 |
+
probs = flatten_probs(probs)
|
| 100 |
+
predictions = (probs >= threshold).astype(int)
|
| 101 |
+
labels = labels.astype(int)
|
| 102 |
+
image_ids = image_ids.astype(int)
|
| 103 |
+
|
| 104 |
+
preds_path = resolve_template_path(cfg.dataset.save_preds_path)
|
| 105 |
+
metrics_path = resolve_template_path(cfg.dataset.save_metrics_path)
|
| 106 |
+
preds_path.parent.mkdir(parents=True, exist_ok=True)
|
| 107 |
+
metrics_path.parent.mkdir(parents=True, exist_ok=True)
|
| 108 |
+
|
| 109 |
+
np.savetxt(
|
| 110 |
+
preds_path,
|
| 111 |
+
np.column_stack([image_ids, probs, predictions, labels]),
|
| 112 |
+
delimiter=",",
|
| 113 |
+
header="image_id,probability,prediction,true_label",
|
| 114 |
+
comments="",
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
metrics = {
|
| 118 |
+
"checkpoint": str(checkpoint_path),
|
| 119 |
+
"split": cfg.dataset.inference_split,
|
| 120 |
+
"fusion_method": fusion_method,
|
| 121 |
+
"threshold": float(threshold),
|
| 122 |
+
"accuracy": accuracy_score(labels, predictions),
|
| 123 |
+
"macro_f1": f1_score(labels, predictions, average="macro", zero_division=0),
|
| 124 |
+
"macro_precision": precision_score(labels, predictions, average="macro", zero_division=0),
|
| 125 |
+
"macro_recall": recall_score(labels, predictions, average="macro", zero_division=0),
|
| 126 |
+
"confusion_matrix": confusion_matrix(labels, predictions).tolist(),
|
| 127 |
+
"classification_report": classification_report(labels, predictions, zero_division=0),
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
with open(metrics_path, "w", encoding="utf-8") as file:
|
| 131 |
+
json.dump(metrics, file, ensure_ascii=False, indent=2)
|
| 132 |
+
|
| 133 |
+
logger.info("Saved predictions: %s", preds_path)
|
| 134 |
+
logger.info("Saved metrics: %s", metrics_path)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
main()
|
src/main.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import random
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Dict, Optional
|
| 7 |
+
|
| 8 |
+
import hydra
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
from omegaconf import OmegaConf
|
| 13 |
+
from sklearn.metrics import ConfusionMatrixDisplay, classification_report, confusion_matrix, f1_score
|
| 14 |
+
from torch import nn
|
| 15 |
+
from torch.optim.lr_scheduler import ReduceLROnPlateau
|
| 16 |
+
from torch.utils.data import DataLoader
|
| 17 |
+
|
| 18 |
+
from dataset import MemeDataset
|
| 19 |
+
from models import (
|
| 20 |
+
build_model,
|
| 21 |
+
get_trainable_checkpoint,
|
| 22 |
+
load_tokenizer_and_llama,
|
| 23 |
+
load_trainable_checkpoint,
|
| 24 |
+
resolve_dtype,
|
| 25 |
+
trainable_parameters,
|
| 26 |
+
)
|
| 27 |
+
from train import collect_probabilities, optimize_threshold, run_epoch
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def template_root() -> Path:
|
| 34 |
+
return Path(__file__).resolve().parents[1]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def resolve_template_path(raw_path: str) -> Path:
|
| 38 |
+
path = Path(str(raw_path))
|
| 39 |
+
if path.is_absolute():
|
| 40 |
+
return path
|
| 41 |
+
return (template_root() / path).resolve()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def set_seed(seed: int) -> None:
|
| 45 |
+
random.seed(seed)
|
| 46 |
+
np.random.seed(seed)
|
| 47 |
+
torch.manual_seed(seed)
|
| 48 |
+
if torch.cuda.is_available():
|
| 49 |
+
torch.cuda.manual_seed_all(seed)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def make_loaders(cfg, tokenizer) -> tuple[DataLoader, DataLoader, DataLoader]:
|
| 53 |
+
data_root = resolve_template_path(cfg.dataset.data_root)
|
| 54 |
+
common_kwargs = {
|
| 55 |
+
"data_root": data_root,
|
| 56 |
+
"language": cfg.dataset.language,
|
| 57 |
+
"tokenizer": tokenizer,
|
| 58 |
+
"image_id_col": cfg.dataset.image_id_col,
|
| 59 |
+
"text_col": cfg.dataset.text_col,
|
| 60 |
+
"label_col": cfg.dataset.label_col,
|
| 61 |
+
"max_length": cfg.training.max_length,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
train_dataset = MemeDataset(
|
| 65 |
+
split=cfg.dataset.train_split,
|
| 66 |
+
oversample_positive_train=cfg.training.oversample_positive_train,
|
| 67 |
+
**common_kwargs,
|
| 68 |
+
)
|
| 69 |
+
dev_dataset = MemeDataset(
|
| 70 |
+
split=cfg.dataset.dev_split,
|
| 71 |
+
oversample_positive_train=0,
|
| 72 |
+
**common_kwargs,
|
| 73 |
+
)
|
| 74 |
+
test_dataset = MemeDataset(
|
| 75 |
+
split=cfg.dataset.test_split,
|
| 76 |
+
oversample_positive_train=0,
|
| 77 |
+
**common_kwargs,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
train_loader = DataLoader(
|
| 81 |
+
train_dataset,
|
| 82 |
+
batch_size=cfg.training.batch_size,
|
| 83 |
+
shuffle=True,
|
| 84 |
+
drop_last=True,
|
| 85 |
+
num_workers=cfg.training.num_workers,
|
| 86 |
+
)
|
| 87 |
+
dev_loader = DataLoader(
|
| 88 |
+
dev_dataset,
|
| 89 |
+
batch_size=cfg.training.batch_size,
|
| 90 |
+
shuffle=False,
|
| 91 |
+
drop_last=False,
|
| 92 |
+
num_workers=cfg.training.num_workers,
|
| 93 |
+
)
|
| 94 |
+
test_loader = DataLoader(
|
| 95 |
+
test_dataset,
|
| 96 |
+
batch_size=cfg.training.batch_size,
|
| 97 |
+
shuffle=False,
|
| 98 |
+
drop_last=False,
|
| 99 |
+
num_workers=cfg.training.num_workers,
|
| 100 |
+
)
|
| 101 |
+
return train_loader, dev_loader, test_loader
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def make_output_dirs(cfg) -> Dict[str, Path]:
|
| 105 |
+
output_root = resolve_template_path(cfg.dataset.output_root)
|
| 106 |
+
paths = {
|
| 107 |
+
"predictions": output_root / "predictions" / cfg.dataset.language / "fusion",
|
| 108 |
+
"metrics": output_root / "predictions" / cfg.dataset.language / "fusion",
|
| 109 |
+
"models": output_root / "trained_model" / cfg.dataset.language / "fusion",
|
| 110 |
+
}
|
| 111 |
+
for path in paths.values():
|
| 112 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
return paths
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def save_run_artifacts(
|
| 117 |
+
cfg,
|
| 118 |
+
paths: Dict[str, Path],
|
| 119 |
+
model,
|
| 120 |
+
fusion: str,
|
| 121 |
+
initial_lr: float,
|
| 122 |
+
final_lr: float,
|
| 123 |
+
best_epoch: int,
|
| 124 |
+
best_threshold: float,
|
| 125 |
+
best_dev_f1: float,
|
| 126 |
+
threshold_scores: Dict[float, float],
|
| 127 |
+
test_probs: np.ndarray,
|
| 128 |
+
test_labels: np.ndarray,
|
| 129 |
+
test_ids: np.ndarray,
|
| 130 |
+
test_loss: float,
|
| 131 |
+
test_macro_f1: float,
|
| 132 |
+
test_accuracy: float,
|
| 133 |
+
) -> None:
|
| 134 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 135 |
+
run_name = (
|
| 136 |
+
f"fusemd_{cfg.dataset.language}_{fusion}"
|
| 137 |
+
f"_lr{initial_lr}_epoch{best_epoch}_bs{cfg.training.batch_size}_{timestamp}"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
predictions = (test_probs >= best_threshold).astype(float)
|
| 141 |
+
predictions_path = paths["predictions"] / f"{run_name}.csv"
|
| 142 |
+
metrics_json_path = paths["metrics"] / f"{run_name}.json"
|
| 143 |
+
metrics_txt_path = paths["metrics"] / f"{run_name}.txt"
|
| 144 |
+
checkpoint_path = paths["models"] / f"{run_name}.pth"
|
| 145 |
+
|
| 146 |
+
np.savetxt(
|
| 147 |
+
predictions_path,
|
| 148 |
+
np.column_stack(
|
| 149 |
+
[
|
| 150 |
+
test_ids.astype(int),
|
| 151 |
+
test_probs,
|
| 152 |
+
predictions.astype(int),
|
| 153 |
+
test_labels.astype(int),
|
| 154 |
+
]
|
| 155 |
+
),
|
| 156 |
+
delimiter=",",
|
| 157 |
+
header="image_id,probability,prediction,true_label",
|
| 158 |
+
comments="",
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
checkpoint = {
|
| 162 |
+
**get_trainable_checkpoint(model),
|
| 163 |
+
"fusion_method": fusion,
|
| 164 |
+
"learning_rate": initial_lr,
|
| 165 |
+
"final_learning_rate": final_lr,
|
| 166 |
+
"best_epoch": best_epoch,
|
| 167 |
+
"best_threshold": best_threshold,
|
| 168 |
+
"best_dev_macro_f1": best_dev_f1,
|
| 169 |
+
"threshold_scores": threshold_scores,
|
| 170 |
+
"test_macro_f1": test_macro_f1,
|
| 171 |
+
"test_accuracy": test_accuracy,
|
| 172 |
+
"test_loss": test_loss,
|
| 173 |
+
"config": OmegaConf.to_container(cfg, resolve=True),
|
| 174 |
+
}
|
| 175 |
+
torch.save(checkpoint, checkpoint_path)
|
| 176 |
+
stable_checkpoint_path = resolve_template_path(cfg.dataset.finetuned_model_path)
|
| 177 |
+
stable_checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
|
| 178 |
+
torch.save(checkpoint, stable_checkpoint_path)
|
| 179 |
+
|
| 180 |
+
report = classification_report(test_labels, predictions, digits=5, zero_division=0)
|
| 181 |
+
matrix = confusion_matrix(test_labels, predictions)
|
| 182 |
+
metrics = {
|
| 183 |
+
"run_name": run_name,
|
| 184 |
+
"date_time": datetime.now().isoformat(),
|
| 185 |
+
"fusion_method": fusion,
|
| 186 |
+
"initial_learning_rate": initial_lr,
|
| 187 |
+
"final_learning_rate": final_lr,
|
| 188 |
+
"best_epoch": best_epoch,
|
| 189 |
+
"best_threshold": best_threshold,
|
| 190 |
+
"best_dev_macro_f1": best_dev_f1,
|
| 191 |
+
"threshold_scores": threshold_scores,
|
| 192 |
+
"test_macro_f1": test_macro_f1,
|
| 193 |
+
"test_accuracy": test_accuracy,
|
| 194 |
+
"test_loss": test_loss,
|
| 195 |
+
"confusion_matrix": matrix.tolist(),
|
| 196 |
+
"classification_report": report,
|
| 197 |
+
"config": OmegaConf.to_container(cfg, resolve=True),
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
with open(metrics_json_path, "w", encoding="utf-8") as file:
|
| 201 |
+
json.dump(metrics, file, ensure_ascii=False, indent=2)
|
| 202 |
+
|
| 203 |
+
with open(metrics_txt_path, "w", encoding="utf-8") as file:
|
| 204 |
+
file.write(f"Run: {run_name}\n")
|
| 205 |
+
file.write(f"Date and time: {metrics['date_time']}\n")
|
| 206 |
+
file.write(f"Fusion: {fusion}\n")
|
| 207 |
+
file.write(f"Initial LR: {initial_lr}\n")
|
| 208 |
+
file.write(f"Final LR: {final_lr}\n")
|
| 209 |
+
file.write(f"Best epoch: {best_epoch}\n")
|
| 210 |
+
file.write(f"Best threshold: {best_threshold}\n")
|
| 211 |
+
file.write(f"Dev macro-F1: {best_dev_f1:.5f}\n")
|
| 212 |
+
file.write(f"Test macro-F1: {test_macro_f1:.5f}\n")
|
| 213 |
+
file.write(f"Test accuracy: {test_accuracy:.5f}\n")
|
| 214 |
+
file.write(f"Test loss: {test_loss:.5f}\n\n")
|
| 215 |
+
file.write(str(matrix))
|
| 216 |
+
file.write("\n\n")
|
| 217 |
+
file.write(report)
|
| 218 |
+
|
| 219 |
+
if cfg.training.save_confusion_matrix_png:
|
| 220 |
+
display = ConfusionMatrixDisplay(matrix)
|
| 221 |
+
display.plot()
|
| 222 |
+
plt.title(f"{cfg.dataset.language} {fusion} confusion matrix")
|
| 223 |
+
plt.savefig(paths["metrics"] / f"{run_name}_confusion_matrix.png", bbox_inches="tight", dpi=200)
|
| 224 |
+
plt.close()
|
| 225 |
+
|
| 226 |
+
logger.info("Saved checkpoint: %s", checkpoint_path)
|
| 227 |
+
logger.info("Updated default inference checkpoint: %s", stable_checkpoint_path)
|
| 228 |
+
logger.info("Saved predictions: %s", predictions_path)
|
| 229 |
+
logger.info("Saved metrics: %s", metrics_json_path)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def train_one_run(
|
| 233 |
+
cfg,
|
| 234 |
+
tokenizer,
|
| 235 |
+
llama,
|
| 236 |
+
train_loader: DataLoader,
|
| 237 |
+
dev_loader: DataLoader,
|
| 238 |
+
test_loader: DataLoader,
|
| 239 |
+
device: torch.device,
|
| 240 |
+
fusion: str,
|
| 241 |
+
learning_rate: float,
|
| 242 |
+
paths: Dict[str, Path],
|
| 243 |
+
) -> None:
|
| 244 |
+
logger.info("Starting run with fusion=%s learning_rate=%s", fusion, learning_rate)
|
| 245 |
+
model = build_model(llama, cfg.model.image_model, fusion, cfg.model.embedding_dim).to(device)
|
| 246 |
+
|
| 247 |
+
optimizer = torch.optim.Adam(trainable_parameters(model), lr=learning_rate, eps=cfg.training.optimizer_eps)
|
| 248 |
+
scheduler = ReduceLROnPlateau(
|
| 249 |
+
optimizer,
|
| 250 |
+
factor=cfg.training.scheduler_factor,
|
| 251 |
+
patience=cfg.training.scheduler_patience,
|
| 252 |
+
threshold=cfg.training.scheduler_threshold,
|
| 253 |
+
)
|
| 254 |
+
criterion = nn.BCEWithLogitsLoss()
|
| 255 |
+
|
| 256 |
+
best_dev_loss = float("inf")
|
| 257 |
+
best_epoch = 0
|
| 258 |
+
final_lr = learning_rate
|
| 259 |
+
epochs_without_improvement = 0
|
| 260 |
+
best_state: Optional[Dict[str, object]] = None
|
| 261 |
+
|
| 262 |
+
for epoch in range(1, cfg.training.max_epochs + 1):
|
| 263 |
+
train_loss = run_epoch(
|
| 264 |
+
model,
|
| 265 |
+
train_loader,
|
| 266 |
+
criterion,
|
| 267 |
+
device,
|
| 268 |
+
optimizer=optimizer,
|
| 269 |
+
description=f"Train epoch {epoch}",
|
| 270 |
+
)
|
| 271 |
+
with torch.no_grad():
|
| 272 |
+
dev_loss = run_epoch(
|
| 273 |
+
model,
|
| 274 |
+
dev_loader,
|
| 275 |
+
criterion,
|
| 276 |
+
device,
|
| 277 |
+
optimizer=None,
|
| 278 |
+
description=f"Dev epoch {epoch}",
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
scheduler.step(dev_loss)
|
| 282 |
+
current_lr = optimizer.param_groups[0]["lr"]
|
| 283 |
+
logger.info(
|
| 284 |
+
"Epoch %s train_loss=%.5f dev_loss=%.5f lr=%.8f",
|
| 285 |
+
epoch,
|
| 286 |
+
train_loss,
|
| 287 |
+
dev_loss,
|
| 288 |
+
current_lr,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if dev_loss < best_dev_loss:
|
| 292 |
+
best_dev_loss = dev_loss
|
| 293 |
+
best_epoch = epoch
|
| 294 |
+
final_lr = current_lr
|
| 295 |
+
epochs_without_improvement = 0
|
| 296 |
+
best_state = get_trainable_checkpoint(model)
|
| 297 |
+
else:
|
| 298 |
+
epochs_without_improvement += 1
|
| 299 |
+
|
| 300 |
+
if epochs_without_improvement >= cfg.training.early_stopping_patience:
|
| 301 |
+
logger.info("Early stopping at epoch %s", epoch)
|
| 302 |
+
break
|
| 303 |
+
|
| 304 |
+
if best_state is not None:
|
| 305 |
+
load_trainable_checkpoint(model, best_state)
|
| 306 |
+
model.to(device)
|
| 307 |
+
|
| 308 |
+
dev_probs, dev_labels, _ = collect_probabilities(model, dev_loader, device)
|
| 309 |
+
best_threshold, best_dev_f1, threshold_scores = optimize_threshold(
|
| 310 |
+
dev_probs,
|
| 311 |
+
dev_labels,
|
| 312 |
+
cfg.training.threshold_start,
|
| 313 |
+
cfg.training.threshold_stop,
|
| 314 |
+
cfg.training.threshold_step,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
test_probs, test_labels, test_ids = collect_probabilities(model, test_loader, device)
|
| 318 |
+
test_preds = (test_probs >= best_threshold).astype(float)
|
| 319 |
+
test_macro_f1 = f1_score(test_labels, test_preds, average="macro", zero_division=0)
|
| 320 |
+
test_accuracy = float((test_preds == test_labels).mean())
|
| 321 |
+
|
| 322 |
+
with torch.no_grad():
|
| 323 |
+
test_loss = run_epoch(
|
| 324 |
+
model,
|
| 325 |
+
test_loader,
|
| 326 |
+
criterion,
|
| 327 |
+
device,
|
| 328 |
+
optimizer=None,
|
| 329 |
+
description="Test loss",
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
save_run_artifacts(
|
| 333 |
+
cfg=cfg,
|
| 334 |
+
paths=paths,
|
| 335 |
+
model=model,
|
| 336 |
+
fusion=fusion,
|
| 337 |
+
initial_lr=learning_rate,
|
| 338 |
+
final_lr=final_lr,
|
| 339 |
+
best_epoch=best_epoch,
|
| 340 |
+
best_threshold=best_threshold,
|
| 341 |
+
best_dev_f1=best_dev_f1,
|
| 342 |
+
threshold_scores=threshold_scores,
|
| 343 |
+
test_probs=test_probs,
|
| 344 |
+
test_labels=test_labels,
|
| 345 |
+
test_ids=test_ids,
|
| 346 |
+
test_loss=test_loss,
|
| 347 |
+
test_macro_f1=test_macro_f1,
|
| 348 |
+
test_accuracy=test_accuracy,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
del model
|
| 352 |
+
if torch.cuda.is_available():
|
| 353 |
+
torch.cuda.empty_cache()
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
@hydra.main(version_base=None, config_path="./configs", config_name="config")
|
| 357 |
+
def main(cfg) -> None:
|
| 358 |
+
logger.info(OmegaConf.to_yaml(cfg, resolve=True))
|
| 359 |
+
set_seed(cfg.training.seed)
|
| 360 |
+
|
| 361 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 362 |
+
dtype = resolve_dtype(cfg.model.dtype)
|
| 363 |
+
use_8bit = bool(cfg.model.use_8bit and device.type == "cuda")
|
| 364 |
+
if cfg.model.use_8bit and device.type != "cuda":
|
| 365 |
+
logger.warning("8-bit quantization requested, but CUDA is unavailable. Continuing without 8-bit.")
|
| 366 |
+
|
| 367 |
+
tokenizer, llama = load_tokenizer_and_llama(cfg.model.text_model, use_8bit, dtype, device)
|
| 368 |
+
train_loader, dev_loader, test_loader = make_loaders(cfg, tokenizer)
|
| 369 |
+
paths = make_output_dirs(cfg)
|
| 370 |
+
|
| 371 |
+
for fusion in cfg.model.fusion_methods:
|
| 372 |
+
for learning_rate in cfg.training.learning_rates:
|
| 373 |
+
train_one_run(
|
| 374 |
+
cfg=cfg,
|
| 375 |
+
tokenizer=tokenizer,
|
| 376 |
+
llama=llama,
|
| 377 |
+
train_loader=train_loader,
|
| 378 |
+
dev_loader=dev_loader,
|
| 379 |
+
test_loader=test_loader,
|
| 380 |
+
device=device,
|
| 381 |
+
fusion=fusion,
|
| 382 |
+
learning_rate=float(learning_rate),
|
| 383 |
+
paths=paths,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
if __name__ == "__main__":
|
| 388 |
+
main()
|
src/models/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .fuse_md import (
|
| 2 |
+
FuseMD,
|
| 3 |
+
build_model,
|
| 4 |
+
get_trainable_checkpoint,
|
| 5 |
+
load_tokenizer_and_llama,
|
| 6 |
+
load_trainable_checkpoint,
|
| 7 |
+
resolve_dtype,
|
| 8 |
+
trainable_parameters,
|
| 9 |
+
)
|
src/models/fuse_md.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Tuple
|
| 2 |
+
|
| 3 |
+
import timm
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 7 |
+
|
| 8 |
+
from .local_store import runtime_text_model_path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def resolve_dtype(dtype_name: str) -> torch.dtype:
|
| 12 |
+
if dtype_name == "float16":
|
| 13 |
+
return torch.float16
|
| 14 |
+
if dtype_name == "float32":
|
| 15 |
+
return torch.float32
|
| 16 |
+
raise ValueError(f"Unsupported dtype: {dtype_name}")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def infer_hidden_size(llama: AutoModelForCausalLM) -> int:
|
| 20 |
+
if hasattr(llama.config, "hidden_size"):
|
| 21 |
+
return int(llama.config.hidden_size)
|
| 22 |
+
if hasattr(llama.config, "n_embd"):
|
| 23 |
+
return int(llama.config.n_embd)
|
| 24 |
+
raise ValueError("Could not infer hidden size from the language model config")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ImageEmbeddingModel(nn.Module):
|
| 28 |
+
def __init__(self, model_name: str, embedding_dim: int) -> None:
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.embedding = timm.create_model(model_name, pretrained=True, num_classes=embedding_dim)
|
| 31 |
+
|
| 32 |
+
def forward(self, images: torch.Tensor) -> torch.Tensor:
|
| 33 |
+
return self.embedding(images)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class LlamaTextProjector(nn.Module):
|
| 37 |
+
def __init__(self, llama: AutoModelForCausalLM, embedding_dim: int) -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.text_base = getattr(llama, "model", llama)
|
| 40 |
+
hidden_size = infer_hidden_size(llama)
|
| 41 |
+
self.projection = nn.Sequential(
|
| 42 |
+
nn.Linear(hidden_size, 512, bias=False),
|
| 43 |
+
nn.Dropout(0.5),
|
| 44 |
+
nn.GELU(),
|
| 45 |
+
nn.LayerNorm(512),
|
| 46 |
+
nn.Linear(512, embedding_dim, bias=False),
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
|
| 50 |
+
outputs = self.text_base(input_ids=input_ids, attention_mask=attention_mask)
|
| 51 |
+
hidden = outputs.last_hidden_state
|
| 52 |
+
mask = attention_mask.unsqueeze(-1).to(hidden.dtype)
|
| 53 |
+
pooled = (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)
|
| 54 |
+
pooled = pooled.to(self.projection[0].weight.dtype)
|
| 55 |
+
return self.projection(pooled)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class FusionHead(nn.Module):
|
| 59 |
+
def __init__(self, fusion: str, embedding_dim: int) -> None:
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.fusion = fusion
|
| 62 |
+
|
| 63 |
+
if fusion == "concat":
|
| 64 |
+
fused_dim = embedding_dim * 2
|
| 65 |
+
elif fusion == "element":
|
| 66 |
+
fused_dim = embedding_dim
|
| 67 |
+
elif fusion == "avgpool":
|
| 68 |
+
self.w_image = nn.Linear(embedding_dim, 64, bias=False)
|
| 69 |
+
self.w_text = nn.Linear(embedding_dim, 64, bias=False)
|
| 70 |
+
self.pool = nn.AvgPool1d(kernel_size=4)
|
| 71 |
+
fused_dim = 16
|
| 72 |
+
elif fusion == "gated":
|
| 73 |
+
self.u_text = nn.Linear(embedding_dim, 64, bias=False)
|
| 74 |
+
self.v_image = nn.Linear(embedding_dim, 64, bias=False)
|
| 75 |
+
self.w_fused = nn.Linear(64, 8, bias=False)
|
| 76 |
+
self.sigmoid = nn.Sigmoid()
|
| 77 |
+
fused_dim = 8
|
| 78 |
+
else:
|
| 79 |
+
raise ValueError(f"Unsupported fusion method: {fusion}")
|
| 80 |
+
|
| 81 |
+
hidden_dim = max(fused_dim // 2, 1)
|
| 82 |
+
self.initial = nn.Linear(fused_dim, hidden_dim, bias=True)
|
| 83 |
+
self.final = nn.Linear(hidden_dim, 1, bias=True)
|
| 84 |
+
|
| 85 |
+
def forward(self, text_features: torch.Tensor, image_features: torch.Tensor) -> torch.Tensor:
|
| 86 |
+
target_dtype = self.initial.weight.dtype
|
| 87 |
+
text_features = text_features.to(target_dtype)
|
| 88 |
+
image_features = image_features.to(target_dtype)
|
| 89 |
+
|
| 90 |
+
if self.fusion == "concat":
|
| 91 |
+
fused = torch.cat([text_features, image_features], dim=-1)
|
| 92 |
+
elif self.fusion == "element":
|
| 93 |
+
fused = text_features * image_features
|
| 94 |
+
elif self.fusion == "avgpool":
|
| 95 |
+
text_encoded = self.w_text(text_features)
|
| 96 |
+
image_encoded = self.w_image(image_features)
|
| 97 |
+
fused = self.pool((text_encoded * image_encoded).unsqueeze(1)).squeeze(1)
|
| 98 |
+
else:
|
| 99 |
+
gate = self.sigmoid(self.u_text(text_features))
|
| 100 |
+
image_encoded = self.v_image(image_features)
|
| 101 |
+
fused = self.w_fused(gate * image_encoded)
|
| 102 |
+
|
| 103 |
+
hidden = self.initial(fused)
|
| 104 |
+
return self.final(hidden).squeeze(-1)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class FuseMD(nn.Module):
|
| 108 |
+
def __init__(
|
| 109 |
+
self,
|
| 110 |
+
text_encoder: LlamaTextProjector,
|
| 111 |
+
image_encoder: ImageEmbeddingModel,
|
| 112 |
+
fusion_head: FusionHead,
|
| 113 |
+
) -> None:
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.text_encoder = text_encoder
|
| 116 |
+
self.image_encoder = image_encoder
|
| 117 |
+
self.fusion_head = fusion_head
|
| 118 |
+
|
| 119 |
+
def forward(
|
| 120 |
+
self,
|
| 121 |
+
input_ids: torch.Tensor,
|
| 122 |
+
attention_mask: torch.Tensor,
|
| 123 |
+
images: torch.Tensor,
|
| 124 |
+
) -> torch.Tensor:
|
| 125 |
+
text_features = self.text_encoder(input_ids, attention_mask)
|
| 126 |
+
image_features = self.image_encoder(images)
|
| 127 |
+
return self.fusion_head(text_features, image_features)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def load_tokenizer_and_llama(
|
| 131 |
+
text_model_name: str,
|
| 132 |
+
use_8bit: bool,
|
| 133 |
+
dtype: torch.dtype,
|
| 134 |
+
device: torch.device,
|
| 135 |
+
) -> Tuple[AutoTokenizer, AutoModelForCausalLM]:
|
| 136 |
+
resolved_model_path = runtime_text_model_path(text_model_name)
|
| 137 |
+
tokenizer = AutoTokenizer.from_pretrained(resolved_model_path, local_files_only=True)
|
| 138 |
+
if tokenizer.pad_token is None:
|
| 139 |
+
if tokenizer.eos_token is not None:
|
| 140 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 141 |
+
else:
|
| 142 |
+
tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
| 143 |
+
|
| 144 |
+
quantization_config = None
|
| 145 |
+
if use_8bit and device.type == "cuda":
|
| 146 |
+
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
|
| 147 |
+
|
| 148 |
+
model_dtype = dtype if device.type == "cuda" else torch.float32
|
| 149 |
+
llama = AutoModelForCausalLM.from_pretrained(
|
| 150 |
+
resolved_model_path,
|
| 151 |
+
low_cpu_mem_usage=True,
|
| 152 |
+
local_files_only=True,
|
| 153 |
+
quantization_config=quantization_config,
|
| 154 |
+
torch_dtype=model_dtype,
|
| 155 |
+
)
|
| 156 |
+
if len(tokenizer) != llama.get_input_embeddings().num_embeddings:
|
| 157 |
+
llama.resize_token_embeddings(len(tokenizer), mean_resizing=False)
|
| 158 |
+
return tokenizer, llama
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def freeze_base_models(model: FuseMD) -> None:
|
| 162 |
+
for param in model.text_encoder.text_base.parameters():
|
| 163 |
+
param.requires_grad = False
|
| 164 |
+
for param in model.text_encoder.projection.parameters():
|
| 165 |
+
param.requires_grad = True
|
| 166 |
+
|
| 167 |
+
for param in model.image_encoder.embedding.parameters():
|
| 168 |
+
param.requires_grad = False
|
| 169 |
+
if hasattr(model.image_encoder.embedding, "head"):
|
| 170 |
+
for param in model.image_encoder.embedding.head.parameters():
|
| 171 |
+
param.requires_grad = True
|
| 172 |
+
|
| 173 |
+
for param in model.fusion_head.parameters():
|
| 174 |
+
param.requires_grad = True
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def trainable_parameters(model: FuseMD) -> List[nn.Parameter]:
|
| 178 |
+
return [param for param in model.parameters() if param.requires_grad]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def get_trainable_checkpoint(model: FuseMD) -> Dict[str, object]:
|
| 182 |
+
vit_state = model.image_encoder.state_dict()
|
| 183 |
+
vit_head_state = {key: value.cpu() for key, value in vit_state.items() if key.startswith("embedding.head")}
|
| 184 |
+
|
| 185 |
+
return {
|
| 186 |
+
"text_projection_state_dict": {
|
| 187 |
+
key: value.cpu() for key, value in model.text_encoder.projection.state_dict().items()
|
| 188 |
+
},
|
| 189 |
+
"vit_head_state_dict": vit_head_state,
|
| 190 |
+
"fusion_head_state_dict": {
|
| 191 |
+
key: value.cpu() for key, value in model.fusion_head.state_dict().items()
|
| 192 |
+
},
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def load_trainable_checkpoint(model: FuseMD, checkpoint: Dict[str, object]) -> None:
|
| 197 |
+
text_projection_state = checkpoint.get("text_projection_state_dict")
|
| 198 |
+
if text_projection_state is None:
|
| 199 |
+
text_projection_state = checkpoint.get("text_clf_head_state_dict")
|
| 200 |
+
if text_projection_state is None:
|
| 201 |
+
raise KeyError("Checkpoint is missing both 'text_projection_state_dict' and 'text_clf_head_state_dict'.")
|
| 202 |
+
|
| 203 |
+
model.text_encoder.projection.load_state_dict(text_projection_state)
|
| 204 |
+
|
| 205 |
+
vit_current = model.image_encoder.state_dict()
|
| 206 |
+
vit_current.update(checkpoint["vit_head_state_dict"])
|
| 207 |
+
model.image_encoder.load_state_dict(vit_current, strict=False)
|
| 208 |
+
|
| 209 |
+
model.fusion_head.load_state_dict(checkpoint["fusion_head_state_dict"])
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def build_model(
|
| 213 |
+
llama: AutoModelForCausalLM,
|
| 214 |
+
image_model_name: str,
|
| 215 |
+
fusion_method: str,
|
| 216 |
+
embedding_dim: int,
|
| 217 |
+
) -> FuseMD:
|
| 218 |
+
text_encoder = LlamaTextProjector(llama=llama, embedding_dim=embedding_dim)
|
| 219 |
+
image_encoder = ImageEmbeddingModel(image_model_name, embedding_dim=embedding_dim)
|
| 220 |
+
fusion_head = FusionHead(fusion=fusion_method, embedding_dim=embedding_dim)
|
| 221 |
+
model = FuseMD(text_encoder=text_encoder, image_encoder=image_encoder, fusion_head=fusion_head)
|
| 222 |
+
freeze_base_models(model)
|
| 223 |
+
return model
|
src/models/local_store.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
LOCAL_MODEL_ROOT_ENV = "FUSEMD_LOCAL_MODEL_ROOT"
|
| 6 |
+
DEFAULT_LOCAL_MODEL_ROOT = "local_models"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def repo_root() -> Path:
|
| 10 |
+
return Path(__file__).resolve().parents[2]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def resolve_repo_path(raw_path: str) -> Path:
|
| 14 |
+
path = Path(str(raw_path))
|
| 15 |
+
if path.is_absolute():
|
| 16 |
+
return path
|
| 17 |
+
return (repo_root() / path).resolve()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def configured_local_model_root(raw_root: str | None = None) -> Path:
|
| 21 |
+
configured = raw_root or os.getenv(LOCAL_MODEL_ROOT_ENV, DEFAULT_LOCAL_MODEL_ROOT)
|
| 22 |
+
return resolve_repo_path(configured)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def local_model_folder_name(model_id: str) -> str:
|
| 26 |
+
return model_id.replace("\\", "__").replace("/", "__")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def expected_local_model_path(model_id: str, raw_root: str | None = None) -> Path:
|
| 30 |
+
return configured_local_model_root(raw_root) / local_model_folder_name(model_id)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def looks_like_explicit_local_path(text_model_name: str) -> bool:
|
| 34 |
+
normalized = text_model_name.replace("/", "\\")
|
| 35 |
+
return (
|
| 36 |
+
normalized.startswith(".\\")
|
| 37 |
+
or normalized.startswith("..\\")
|
| 38 |
+
or normalized.startswith("local_models\\")
|
| 39 |
+
or "\\" in text_model_name
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def runtime_text_model_path(text_model_name: str, raw_root: str | None = None) -> Path:
|
| 44 |
+
direct_candidate = resolve_repo_path(text_model_name)
|
| 45 |
+
if direct_candidate.exists():
|
| 46 |
+
return direct_candidate
|
| 47 |
+
|
| 48 |
+
absolute_candidate = Path(text_model_name)
|
| 49 |
+
if absolute_candidate.is_absolute():
|
| 50 |
+
raise FileNotFoundError(f"Local text model path not found: {absolute_candidate}")
|
| 51 |
+
if looks_like_explicit_local_path(text_model_name):
|
| 52 |
+
raise FileNotFoundError(f"Local text model path not found: {direct_candidate}")
|
| 53 |
+
|
| 54 |
+
expected_path = expected_local_model_path(text_model_name, raw_root)
|
| 55 |
+
if expected_path.exists():
|
| 56 |
+
return expected_path
|
| 57 |
+
|
| 58 |
+
raise FileNotFoundError(
|
| 59 |
+
"Local text model is missing for "
|
| 60 |
+
f"'{text_model_name}'. Expected folder: {expected_path}. "
|
| 61 |
+
f"Run: python api/setup_local_model.py --model {text_model_name}"
|
| 62 |
+
)
|
src/train.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from sklearn.metrics import f1_score
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.utils.data import DataLoader
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def move_batch(batch: Dict[str, torch.Tensor], device: torch.device) -> Dict[str, torch.Tensor]:
|
| 12 |
+
return {
|
| 13 |
+
"image": batch["image"].to(device=device, dtype=torch.float32),
|
| 14 |
+
"label": batch["label"].to(device=device, dtype=torch.float32),
|
| 15 |
+
"input_ids": batch["input_ids"].to(device=device, dtype=torch.long),
|
| 16 |
+
"attention_mask": batch["attention_mask"].to(device=device, dtype=torch.long),
|
| 17 |
+
"image_id": batch["image_id"].to(device=device),
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def run_epoch(
|
| 22 |
+
model: nn.Module,
|
| 23 |
+
loader: DataLoader,
|
| 24 |
+
criterion: nn.Module,
|
| 25 |
+
device: torch.device,
|
| 26 |
+
optimizer: Optional[torch.optim.Optimizer] = None,
|
| 27 |
+
description: str = "Training",
|
| 28 |
+
) -> float:
|
| 29 |
+
is_training = optimizer is not None
|
| 30 |
+
model.train(is_training)
|
| 31 |
+
|
| 32 |
+
total_loss = 0.0
|
| 33 |
+
steps = 0
|
| 34 |
+
|
| 35 |
+
iterator = tqdm(loader, unit="batch", desc=description)
|
| 36 |
+
for batch in iterator:
|
| 37 |
+
batch = move_batch(batch, device)
|
| 38 |
+
|
| 39 |
+
if is_training:
|
| 40 |
+
optimizer.zero_grad(set_to_none=True)
|
| 41 |
+
|
| 42 |
+
logits = model(batch["input_ids"], batch["attention_mask"], batch["image"])
|
| 43 |
+
loss = criterion(logits, batch["label"])
|
| 44 |
+
|
| 45 |
+
if is_training:
|
| 46 |
+
loss.backward()
|
| 47 |
+
optimizer.step()
|
| 48 |
+
|
| 49 |
+
total_loss += float(loss.item())
|
| 50 |
+
steps += 1
|
| 51 |
+
iterator.set_postfix(loss=total_loss / max(steps, 1))
|
| 52 |
+
|
| 53 |
+
return total_loss / max(steps, 1)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@torch.no_grad()
|
| 57 |
+
def collect_probabilities(
|
| 58 |
+
model: nn.Module,
|
| 59 |
+
loader: DataLoader,
|
| 60 |
+
device: torch.device,
|
| 61 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 62 |
+
model.eval()
|
| 63 |
+
probs: List[float] = []
|
| 64 |
+
labels: List[float] = []
|
| 65 |
+
image_ids: List[int] = []
|
| 66 |
+
|
| 67 |
+
for batch in loader:
|
| 68 |
+
batch = move_batch(batch, device)
|
| 69 |
+
logits = model(batch["input_ids"], batch["attention_mask"], batch["image"])
|
| 70 |
+
batch_probs = torch.sigmoid(logits)
|
| 71 |
+
probs.extend(batch_probs.detach().cpu().numpy().tolist())
|
| 72 |
+
labels.extend(batch["label"].detach().cpu().numpy().tolist())
|
| 73 |
+
image_ids.extend(batch["image_id"].detach().cpu().numpy().tolist())
|
| 74 |
+
|
| 75 |
+
return np.asarray(probs), np.asarray(labels), np.asarray(image_ids)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def threshold_grid(start: float, stop: float, step: float) -> List[float]:
|
| 79 |
+
values = []
|
| 80 |
+
current = start
|
| 81 |
+
while current <= stop + 1e-9:
|
| 82 |
+
values.append(round(current, 10))
|
| 83 |
+
current += step
|
| 84 |
+
return values
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def optimize_threshold(
|
| 88 |
+
probs: np.ndarray,
|
| 89 |
+
labels: np.ndarray,
|
| 90 |
+
threshold_start: float,
|
| 91 |
+
threshold_stop: float,
|
| 92 |
+
threshold_step: float,
|
| 93 |
+
) -> Tuple[float, float, Dict[float, float]]:
|
| 94 |
+
scores: Dict[float, float] = {}
|
| 95 |
+
for threshold in threshold_grid(threshold_start, threshold_stop, threshold_step):
|
| 96 |
+
preds = (probs >= threshold).astype(float)
|
| 97 |
+
scores[threshold] = f1_score(labels, preds, average="macro", zero_division=0)
|
| 98 |
+
|
| 99 |
+
best_threshold = max(scores, key=scores.get)
|
| 100 |
+
return best_threshold, scores[best_threshold], scores
|