OptiPFair-API

November 18, 2025 ยท View on GitHub

Tests Code Quality Python License HF Spaces

GitHub stars GitHub forks GitHub issues


A REST API built with FastAPI that exposes the bias visualization capabilities of the OptiPFair library.

โœจ Key Features

  • ๐Ÿ” Three Visualization Types - PCA, Mean Difference, and Heatmap analysis
  • ๐Ÿš€ FastAPI Backend - High-performance REST API with automatic documentation
  • ๐ŸŽจ Gradio Frontend - User-friendly web interface for interactive analysis
  • ๐Ÿณ Docker Ready - One-command deployment with Docker Compose
  • ๐ŸŒ Online Demo - Try it instantly on Hugging Face Spaces
  • ๐Ÿ”ง Production Ready - CI/CD, tests, and quality checks included

๐ŸŽฏ Quick Start

Option 1: Try Online (Zero Setup)

๐Ÿš€ Launch Demo on HF Spaces

git clone https://github.com/peremartra/optipfair-api.git
cd optipfair-api
docker-compose up -d

# Access at:
# Frontend: http://localhost:7860
# API Docs: http://localhost:8000/docs

Option 3: LLM-Assisted Development

Using ChatGPT, Claude, or other AI assistants? ๐Ÿ“‹ Give them the LLM Reference Manual to generate perfect integration code!

๐Ÿ“Š Bias Analysis Examples

Visualizations obtained with OptiPFair analyzing the LLaMA 3.2-1B model for racial bias:

Mean Image Differencesactivation_differences_layer.pngpca_analysis.png
Mean DifferencesLayer ActivationPCA Analysis

๐Ÿ“‹ Overview

This microservice provides endpoints to generate and download visualizations of activation patterns in transformer-based LLMs (e.g., LLaMA) using the OptiPFair toolkit.

๐ŸŽฏ Main Endpoints

  • POST /visualize/pca - PCA visualization of activations
  • POST /visualize/mean-diff - Mean activation difference across layers
  • POST /visualize/heatmap - Heatmap of activation differences
  • Response: Binary image (PNG, SVG, or PDF) showing the requested visualization

๐Ÿ”ง What's New in This Version

  • โœ… CI/CD Pipeline - Automated testing and code quality checks
  • โœ… Enhanced Validation - Better error handling and input validation
  • โœ… Docker Optimization - Faster builds and improved caching
  • โœ… Code Quality - Black, isort, and flake8 integration

โš™๏ธ Requirements

  • Python 3.11 or higher
  • Git
  • Docker & Docker Compose (recommended for easy deployment)
  • Optional: Mac (Apple Silicon) or NVIDIA GPU for hardware acceleration (MPS/CUDA)
  • Internet connection to download models from Hugging Face Hub

The easiest way to run OptiPFair-API is using Docker Compose, which automatically handles all dependencies and services.

Quick Start with Docker

# 1. Clone the repository
git clone https://github.com/peremartra/optipfair-api.git
cd optipfair-api

# 2. Start the entire stack
docker-compose up -d

# 3. Access the application
# Frontend (Gradio): http://localhost:7860
# Backend API docs: http://localhost:8000/docs

Docker Commands

# Start services (detached mode)
docker-compose up -d

# View logs in real-time
docker-compose logs -f

# Stop services
docker-compose down

# Rebuild after code changes
docker-compose up --build

# Check service status
docker-compose ps

Docker Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚           docker-compose            โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   Backend       โ”‚    Frontend       โ”‚
โ”‚   (FastAPI)     โ”‚    (Gradio)       โ”‚
โ”‚   Port: 8000    โ”‚    Port: 7860     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Features:

  • โœ… Automatic model caching - Downloads models once, reuses them
  • โœ… Health monitoring - Services restart automatically if they fail
  • โœ… Persistent storage - Model cache survives container restarts
  • โœ… Production ready - Secure, non-root containers
  • โœ… Cross-platform - Works on Mac, Linux, Windows

๐ŸŒ Try Online (HF Spaces)

๐Ÿš€ Zero Installation Required!

You can try OptiPFair-API directly in your browser without any setup:

๐Ÿ”— OptipFair Bias Analyzer on Hugging Face Spaces

Features:

  • โœ… Instant access - No installation required
  • โœ… GPU acceleration - Faster model loading and processing
  • โœ… Pre-loaded models - Ready to use immediately
  • โœ… Full functionality - All three visualization types (PCA, Mean Diff, Heatmap)
  • โœ… Public sharing - Share results with colleagues

Perfect for:

  • ๐Ÿงช Quick testing of bias analysis concepts
  • ๐Ÿ“š Learning and experimentation
  • ๐ŸŽฏ Demos and presentations
  • ๐Ÿ”„ Comparing with local deployment

๐Ÿ›  Manual Installation (Alternative)

If you prefer to run without Docker:

# 1. Clone the repository
git clone https://github.com/peremartra/optipfair-api.git
cd optipfair-api

# 2. Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate

# 3. Install dependencies
pip install -r requirements-docker.txt
pip install pytest httpx  # For testing

# 4. (Optional) Verify PyTorch MPS/CUDA support
python3 - <<'EOF'
import torch
print("MPS built?", torch.backends.mps.is_built(), "Available?", torch.backends.mps.is_available())
print("CUDA available?", torch.cuda.is_available())
EOF

Running Manually

# Terminal 1: Start FastAPI backend
uvicorn main:app --reload

# Terminal 2: Start Gradio frontend  
python gradio_app.py
  • Backend: http://127.0.0.1:8000
  • Frontend: http://127.0.0.1:7860

๐Ÿงช Testing & Development

Run Tests

# Run the test suite
pytest tests/test_api_endpoints.py tests/test_validation.py -v

# Run with coverage
pytest --cov=. tests/

Code Quality

# Format code
black .
isort .

# Check code quality
flake8 .

# Run all quality checks (same as CI/CD)
black . && isort . && flake8 . && pytest tests/test_api_endpoints.py tests/test_validation.py

๐Ÿ” API Documentation

Interactive API Docs

  • Swagger UI: http://localhost:8000/docs (when running locally)
  • ReDoc: http://localhost:8000/redoc (alternative documentation)

For LLM-Assisted Development

๐Ÿ“‹ OptipFair-API LLM Reference Manual - Perfect for ChatGPT, Claude, and other AI assistants to generate integration code.

Health Check

GET /ping

Response:

{ "message": "pong" }

1. PCA Visualization

POST /visualize/pca

Generates a PCA scatter plot comparing activations for two prompts.

Request JSON Schema:

FieldTypeDescription
model_namestringHugging Face model identifier (e.g. "meta-llama/Llama-3.2-1B").
prompt_pairstring[2]Array of exactly two prompts to compare.
layer_keystringExact layer name (e.g. "attention_output_layer_0").
highlight_diffboolean(Optional) Highlight differing tokens (default: true).
figure_formatstring(Optional) Output format: png, svg, or pdf (default: png).
pair_indexinteger(Optional) Index for naming output file (default: 0).
output_dirstring(Optional) Custom directory to save the image.

Example using curl:

curl -X POST http://localhost:8000/visualize/pca \
  -H "Content-Type: application/json" \
  -d '{
        "model_name": "meta-llama/Llama-3.2-1B",
        "prompt_pair": [
          "The white doctor examined the patient. The nurse thought",
          "The Black doctor examined the patient. The nurse thought"
        ],
        "layer_key": "attention_output_layer_0",
        "figure_format": "png"
      }' \
  --output pca.png

Example using Python (requests):

import requests

payload = {
    "model_name": "meta-llama/Llama-3.2-1B",
    "prompt_pair": [
        "The white doctor examined the patient. The nurse thought",
        "The Black doctor examined the patient. The nurse thought"
    ],
    "layer_key": "attention_output_layer_0",
    "figure_format": "png"
}

resp = requests.post("http://localhost:8000/visualize/pca", json=payload)
resp.raise_for_status()

with open("pca_result.png", "wb") as f:
    f.write(resp.content)

print("Saved PCA visualization to pca_result.png")

2. Mean Difference Visualization

POST /visualize/mean-diff

Generates a bar chart showing mean activation differences across layers for a specific component type.

Request JSON Schema:

FieldTypeDescription
model_namestringHugging Face model identifier (e.g. "meta-llama/Llama-3.2-1B").
prompt_pairstring[2]Array of exactly two prompts to compare.
layer_typestringComponent type to analyze (e.g. "attention_output").
figure_formatstring(Optional) Output format (default: png).
output_dirstring(Optional) Custom directory to save the image.
pair_indexinteger(Optional) Index for naming output file (default: 0).

Valid layer types for layer_type:

  • mlp_output - Output of the MLP block
  • attention_output - Output of the attention mechanism
  • gate_proj - Output of the gate projection in GLU
  • up_proj - Output of the up projection in GLU
  • down_proj - Output of the down projection in GLU
  • input_norm - Output of the input normalization

Example using Python (requests):

import requests

payload = {
    "model_name": "meta-llama/Llama-3.2-1B",
    "prompt_pair": [
        "The white doctor examined the patient. The nurse thought",
        "The Black doctor examined the patient. The nurse thought"
    ],
    "layer_type": "attention_output",
    "figure_format": "png"
}

resp = requests.post("http://localhost:8000/visualize/mean-diff", json=payload)
resp.raise_for_status()

with open("mean_diff_result.png", "wb") as f:
    f.write(resp.content)

print("Saved mean difference visualization to mean_diff_result.png")

3. Heatmap Visualization

POST /visualize/heatmap

Generates a heatmap showing activation differences for a specific layer.

Request JSON Schema:

FieldTypeDescription
model_namestringHugging Face model identifier (e.g. "meta-llama/Llama-3.2-1B").
prompt_pairstring[2]Array of exactly two prompts to compare.
layer_keystringExact layer name (e.g. "attention_output_layer_0").
figure_formatstring(Optional) Output format (default: png).
output_dirstring(Optional) Custom directory to save the image.
pair_indexinteger(Optional) Index for naming output file (default: 0).

Example using Python (requests):

import requests

payload = {
    "model_name": "meta-llama/Llama-3.2-1B",
    "prompt_pair": [
        "The white doctor examined the patient. The nurse thought",
        "The Black doctor examined the patient. The nurse thought"
    ],
    "layer_key": "attention_output_layer_2",
    "figure_format": "png"
}

resp = requests.post("http://localhost:8000/visualize/heatmap", json=payload)
resp.raise_for_status()

with open("heatmap_result.png", "wb") as f:
    f.write(resp.content)

print("Saved heatmap visualization to heatmap_result.png")

๐Ÿ“ Project Structure

optipfair-api/           # Repository root
โ”œโ”€โ”€ main.py              # FastAPI application entrypoint
โ”œโ”€โ”€ gradio_app.py        # Gradio frontend application
โ”œโ”€โ”€ docker-compose.yml   # Docker orchestration configuration
โ”œโ”€โ”€ Dockerfile.backend   # Backend container definition
โ”œโ”€โ”€ Dockerfile.frontend  # Frontend container definition
โ”œโ”€โ”€ requirements-docker.txt # Optimized dependencies for containers
โ”œโ”€โ”€ .github/             # CI/CD workflows
โ”‚   โ””โ”€โ”€ workflows/
โ”‚       โ”œโ”€โ”€ test.yml     # Automated testing
โ”‚       โ””โ”€โ”€ code-quality.yml # Code quality checks
โ”œโ”€โ”€ routers/             # API route modules
โ”‚   โ””โ”€โ”€ visualize.py     # Routes for /visualize/*
โ”œโ”€โ”€ schemas/             # Pydantic request/response models
โ”‚   โ””โ”€โ”€ visualize.py     # Request schemas for visualizations
โ”œโ”€โ”€ utils/               # Internal utility functions
โ”‚   โ””โ”€โ”€ visualize_pca.py # Wrappers for optipfair visualization functions
โ”œโ”€โ”€ tests/               # Test suite
โ”‚   โ”œโ”€โ”€ test_api_endpoints.py # API endpoint tests
โ”‚   โ””โ”€โ”€ test_validation.py    # Input validation tests
โ”œโ”€โ”€ hf-spaces/           # Hugging Face Spaces deployment
โ””โ”€โ”€ README.md            # Project documentation

๐Ÿš€ Deployment Options

1. ๐ŸŒ Hugging Face Spaces (Try Now!)

๐Ÿ”— OptipFair Bias Analyzer

Pros: Zero setup, GPU acceleration, instant access, public sharing
Cons: Limited to HF Spaces platform, shared resources

docker-compose up -d

Pros: Easy setup, automatic dependencies, production-ready, full control
Cons: Requires Docker installation

3. ๐Ÿ“ฑ Manual Installation

Traditional Python virtual environment setup.

Pros: Full control, native performance (MPS on Mac), development flexibility
Cons: Manual dependency management, longer setup time


๐Ÿค– LLM Integration Guide

For developers using AI assistants (ChatGPT, Claude, etc.) to generate code:

๐Ÿ“‹ OptipFair-API LLM Reference Manual

This comprehensive guide helps Large Language Models understand and generate correct code for OptipFair-API integration:

# Give this file to your favorite LLM assistant:
# "Please use the OptipFair-API LLM Reference Manual to help me integrate with this API"

What the manual includes:

  • โœ… Complete API schemas - All endpoints with examples
  • โœ… Request/response formats - Exact JSON structures
  • โœ… Code generation templates - Python, JavaScript, curl examples
  • โœ… Common patterns - Best practices for integration
  • โœ… Error handling - How to handle validation and server errors

Perfect for:

  • ๐Ÿค– AI-assisted development - ChatGPT, Claude, GitHub Copilot
  • ๐Ÿ“š Quick integration - Generate client code in minutes
  • ๐Ÿ› ๏ธ Prototyping - Rapid API testing and exploration
  • ๐Ÿ“– Learning - Understand API patterns and usage

๐Ÿค Contributing

We welcome contributions! Please see our contributing guidelines:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes and add tests
  4. Ensure code quality: black . && isort . && flake8 .
  5. Run tests: pytest tests/
  6. Commit your changes: git commit -m 'Add amazing feature'
  7. Push to the branch: git push origin feature/amazing-feature
  8. Open a Pull Request

Development Setup

git clone https://github.com/peremartra/optipfair-api.git
cd optipfair-api
python -m venv .venv
source .venv/bin/activate
pip install -r requirements-docker.txt
pip install black isort flake8 pytest httpx

๐Ÿ“– Citation

If you use OptipFair-API in your research or projects, please cite both the API and the underlying library:

OptipFair Library (Core Implementation)

@software{optipfair,
  author = {Pere Martra},
  title = {OptipFair: Structured Pruning and Bias Visualization for Large Language Models},
  url = {https://github.com/peremartra/optipfair},
  version = {0.1.3},
  year = {2024}
}

OptipFair-API (REST Interface)

@software{optipfair_api,
  author = {Pere Martra},
  title = {OptipFair-API: REST API for LLM Bias Analysis and Visualization},
  url = {https://github.com/peremartra/optipfair-api},
  year = {2025}
}

๐Ÿ“„ License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.


๐Ÿ™ Acknowledgments


โญ Star this repo | ๐Ÿ› Report Bug | ๐Ÿ’ก Request Feature

Made with โค๏ธ by Pere Martra