How santanuhxx/inferx works
Purpose and Entry Point
InferX is a FastAPI service for extracting pooled embeddings from selected hidden layers of Hugging Face transformer models. The runtime entry point is app/main.py, which creates the HTTP app, manages startup/shutdown, installs middleware, and exposes API and Prometheus routes. Configuration is environment-driven through app/config.py.
HTTP Boundary and Request Policy
REST endpoints are split between authentication and inference/status APIs:
• app/api/auth.py handles token issuance, refresh, and identity.
• app/api/routes.py serves encoding, health, layer discovery, and usage statistics.
• app/api/dependencies.py composes authenticated-user and rate-limit checks before protected inference routes.
• app/schemas/request.py and app/schemas/response.py define the Pydantic API contract, including text/batch/layer validation and embedding metadata.
The API boundary validates requests before model work and returns embeddings, selected layer, shape, and timing rather than model-native tensors.
Security and Traffic Controls
JWT/OAuth2 credential handling, password verification, and token verification are centralized in app/security/auth_backend.py. Per-user sliding-window request limits are enforced by app/security/rate_limiter.py, invoked through API dependencies. Application-level request IDs and response compression are provided by app/middleware/request_id.py and app/middleware/compression.py; CORS is configured at application assembly time in app/main.py.
Model Lifecycle and Extraction
app/models/model_loader.py owns loading and unloading the configured Hugging Face model and tokenizer, choosing CUDA when available/configured and falling back to CPU. The core extraction stage in app/inference/layer_extractor.py tokenizes text, runs the model with hidden states enabled, selects the requested/default final layer, mean-pools token representations, and optionally normalizes vectors. app/inference/batch_processor.py splits larger valid requests into configured inference batches.
Model identity and supported-model/VRAM metadata are represented by app/models/model_registry.py. This boundary isolates framework-specific PyTorch/Transformers operations from HTTP routing.
Cache-First Inference Flow
app/inference/inference_engine.py coordinates the primary encode path: derive/cache lookup per request input, return a hit when available, otherwise invoke layer extraction and persist the result. app/cache/embedding_cache.py implements embedding-key generation and TTL-backed storage; app/cache/redis_client.py owns Redis connectivity. Redis is both the embedding-cache service and Celery broker, making its availability material to low-latency cached inference and async work.
Persistence, Metrics, and Background Work
SQLite/SQLAlchemy persistence is initialized through app/db/database.py; request/user/model entities and analytics queries live in app/db/models.py and app/db/crud.py. The request path records latency and cache outcomes for aggregate and per-user stats.
Prometheus instruments requests, inference latency, cache counters, and GPU memory in app/monitoring/metrics.py; structured application logging is configured by app/monitoring/logging_config.py. Optional asynchronous batch encoding and cleanup tasks are defined in app/tasks/background_jobs.py and registered against Celery/Redis in app/tasks/celery_app.py.
Deployment Topology
The service runs on Python 3.10+ with FastAPI/Uvicorn, PyTorch, and Hugging Face Transformers. It needs a locally loaded/downloaded Hugging Face-compatible model, optionally an NVIDIA CUDA environment. Docker deployment is defined in docker/Dockerfile; the multi-service stack in docker/docker-compose.yaml includes InferX, Redis, Prometheus (scrape settings: configs/prometheus.yml), and Grafana. Startup initializes the database, connects Redis, then loads the model; shutdown unloads it and releases GPU resources.
Main entry points: main.py FastAPI app lifecycle · inference_engine.py Cache-first inference engine · routes.py Inference & status API · redis_client.py Redis
Components 19
HTTP API
- FastAPI app lifecycle · Starts dependencies, installs middleware, and exposes routes.
app/main.py - Environment config
app/config.py - Auth API
app/api/auth.py - Inference & status API
app/api/routes.py - Auth and rate-limit policy
app/api/dependencies.py - Embedding API contract · Validates text, batches, layers, and response metadata.
app/schemas/request.py - JWT credential backend
app/security/auth_backend.py - Per-user rate limiter
app/security/rate_limiter.py
Inference Runtime
- Cache-first inference engine
app/inference/inference_engine.py - Inference batch processor
app/inference/batch_processor.py - Hidden-layer extractor · Tokenizes, selects a hidden layer, mean-pools, and normalizes vectors.
app/inference/layer_extractor.py - Model and tokenizer lifecycle · Loads on CUDA when available and unloads on shutdown.
app/models/model_loader.py - Supported model registry
app/models/model_registry.py
State & Observability
- Embedding cache · Generates keys and persists cached embedding results.
app/cache/embedding_cache.py - Redis · Shared embedding cache and Celery broker.
app/cache/redis_client.py - SQLite analytics store · Stores request, user, model, and usage data.
app/db/database.py - Prometheus metrics · Tracks requests, latency, cache outcomes, and GPU memory.
app/monitoring/metrics.py
Background Work
- Celery background jobs · Runs optional batch encoding and cleanup tasks.
app/tasks/celery_app.py
Deployment
- Docker service stack · Runs InferX with Redis, Prometheus, and Grafana.
docker/docker-compose.yaml
Connections 24
- FastAPI app lifecycle → Environment config: reads
- FastAPI app lifecycle → Auth API: mounts
- FastAPI app lifecycle → Inference & status API: mounts
- FastAPI app lifecycle → Model and tokenizer lifecycle: startup / shutdown
- FastAPI app lifecycle → Redis: connects
- FastAPI app lifecycle → SQLite analytics store: initializes
- Auth API → JWT credential backend: issues and verifies tokens
- Inference & status API → Auth and rate-limit policy: protects encode routes
- Inference & status API → Embedding API contract: validates request / response
- Auth and rate-limit policy → JWT credential backend: authenticates user
- Auth and rate-limit policy → Per-user rate limiter: enforces limits
- Inference & status API → Cache-first inference engine: encodes validated input
- Cache-first inference engine → Embedding cache: lookup then store
- Embedding cache → Redis: uses TTL storage
- Cache-first inference engine → Inference batch processor: miss path
- Inference batch processor → Hidden-layer extractor: submits batches
- Hidden-layer extractor → Model and tokenizer lifecycle: uses loaded model
- Model and tokenizer lifecycle → Supported model registry: selects model metadata
- Cache-first inference engine → SQLite analytics store: records request outcomes
- Cache-first inference engine → Prometheus metrics: emits latency and cache metrics
- Celery background jobs → Redis: broker
- Docker service stack → FastAPI app lifecycle: runs service
- Docker service stack → Redis: runs dependency
- Docker service stack → Prometheus metrics: Prometheus scrapes