-
Notifications
You must be signed in to change notification settings - Fork 1
Module onnx clip Architecture
Architektur-Hinweis: Klassen/Typen/Namespaces mit aktuellem Sourcecode abgleichen. Symbole, die nicht im Source gefunden werden, mit `` markieren.
Version: 0.0.1
Last Updated: 2026-04-06
Module Path: src/onnx_clip/
The ONNX CLIP plugin wraps OpenAI CLIP models exported to ONNX format using the
ONNX Runtime C++ API. It implements IImageAnalysisBackend and exposes a simple
embedding generation API that ThemisDB uses for multi-modal vector similarity search.
The implementation uses the pImpl idiom (struct Impl hidden in the .cpp) to
keep Ort::Session, preprocessing state, and runtime objects completely out of the
public header. This prevents ABI leakage of ONNX Runtime types into caller translation
units.
-
pImpl isolation β all ONNX Runtime objects (
Ort::Env,Ort::Session,Ort::SessionOptions) live inONNXClipPlugin::Impl; the header exposes only standard types. -
Thread safety β
impl_is protected by astd::mutex;generateEmbedding()andgenerateEmbeddingBatch()serialize access to the ONNX session. -
Backend AUTO β at
initialize()time withBackendType::AUTO, the plugin probes CUDA availability first, then TensorRT, DirectML, and finally CPU. -
Warmup β
warmup()runs a single inference with a synthetic input to pre-compile CUDA/TensorRT kernels before serving live traffic.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ONNXClipPlugin (public API) β
β implements IImageAnalysisBackend β
β β
β initialize(config, backend) β load ONNX model β
β generateEmbedding(image_data) β single inference β
β generateEmbeddingBatch(images) β batch inference β
β healthCheck() β
β warmup() β
β getStatistics() β
ββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β std::unique_ptr<Impl>
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ONNXClipPlugin::Impl (pImpl) β
β β
β Ort::Env β ONNX Runtime environment β
β Ort::Session β loaded CLIP model β
β Ort::SessionOptions β provider / thread config β
β std::mutex β serialises inference calls β
β BackendType backend_ β
β std::string model_variant_ β
β call_count, total_latency_ms (stats) β
ββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββ
β ONNX Runtime C++ API β
β ββ CPU Execution Prov. β
β ββ CUDA Execution Prov.β
β ββ DirectML Exec. Prov.β
β ββ TensorRT Exec. Prov.β
βββββββββββββββββββββββββββ
| Method | Behaviour |
|---|---|
getInfo() |
Returns PluginInfo{name="onnx_clip", version="0.0.1", ...}
|
initialize(config, backend) |
Creates Ort::Session, configures execution provider |
shutdown() |
Releases Ort::Session; resets stats |
isReady() |
Returns true if session is loaded and not null |
getBackend() |
Returns active BackendType
|
generateEmbedding(image_data, metadata) |
Decodes image β preprocess β infer β return float vector |
generateEmbeddingBatch(images) |
Iterates single calls; future: native batched session |
healthCheck() |
Runs warmup inference; checks output tensor shape |
getStatistics() |
Returns JSON: {calls, avg_latency_ms, backend, model_variant}
|
warmup() |
Runs one inference with a 224Γ224 zero tensor |
image_data (raw bytes)
β
ββ Decode (JPEG / PNG / BMP via OpenCV / stb_image)
β
ββ Resize to 224Γ224
β
ββ Normalise: subtract ImageNet mean, divide by std
β mean = [0.48145466, 0.4578275, 0.40821073]
β std = [0.26862954, 0.26130258, 0.27577711]
β
ββ CHW float32 tensor [1, 3, 224, 224]
β
ββ Ort::Session::Run(input_tensor)
β
ββ Output tensor [1, 512] (ViT-B/32) or [1, 768] (ViT-L/14)
β L2 normalise β std::vector<float>
BackendType::AUTO:
1. Check CUDA device count β if > 0 β CUDA
2. Check TensorRT availability β if available β TensorRT
3. Check DirectML (Windows only) β if available β DirectML
4. Fallback β CPU
| Direction | Module | Interface |
|---|---|---|
| Implements | plugins/image_analysis_interface.h |
IImageAnalysisBackend |
| Provides to |
src/server/ vector search handlers |
Embedding vectors |
| Registered via |
THEMIS_IMAGE_PLUGIN macro |
Dynamic plugin loader |
-
Ort::Session::Run()is not thread-safe by default; access serialised viastd::mutexinImpl. -
generateEmbeddingBatch()holds the lock for the entire batch; consider splitting batch into sub-batches for large inputs (planned for v0.1.0). -
isReady()andgetBackend()are lock-free reads of atomic/const members.
| Scenario | Behaviour |
|---|---|
| ONNX model file not found |
initialize() returns false; logs error |
| Image decode failure |
generateEmbedding() returns EmbeddingResult{ok=false, error=...}
|
| CUDA not available (CUDA backend) |
initialize() returns false
|
| Session Run exception | Caught; EmbeddingResult{ok=false} returned |
| Output tensor wrong shape |
healthCheck() returns false
|
New Method: bool reloadModel(const PluginConfig& new_config)
State Machine (8-Step Sequence):
[Ready] βββ reloadModel() βββ [Loading] βββ [Validation] βββ [Activation]
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ [Ready]
On failure: [Loading/Validation] β [Error] β (restore old) β [Ready with old]
Implementation Details:
-
Verify Initialization: Check
impl_->readyflag; returnfalseif not initialized -
Create New Impl: Construct new
Implstruct with new configuration (preserves old) - Apply Config: Parse model name, embedding dim, backend, batch size
- Validate Integrity: Verify model SHA-256 hash if OpenSSL available (or use injected hash function)
-
Mark Ready: Set
new_impl->ready = true -
Wait for Drain: Condition variable waits (up to 30 seconds) for
in_flight_requests_ == 0 -
Atomic Swap: Replace
impl_via unique_ptr move (old impl destroyed automatically) -
Signal Completion: Notify waiting threads; unlock and return
true
Key Features:
- In-flight requests complete with old model before swap
- 30-second timeout for graceful drain of pending requests
- Atomic swap: old model destroyed only after new one ready
- Exception-safe: RAII guards for in-flight counter
- Automatic rollback on new model load failure
Concurrency Model:
// RequestGuard RAII pattern (in all inference methods)
class RequestGuard {
RequestGuard(std::atomic<int>& counter, std::condition_variable& cv)
: counter_(counter), cv_(cv) {
counter_.fetch_add(1, std::memory_order_acquire); // Acquire semantics
}
~RequestGuard() {
int prev = counter_.fetch_sub(1, std::memory_order_release); // Release semantics
if (prev == 1) cv_.notify_all(); // Signal drain complete
}
};
// In generateEmbedding():
RequestGuard guard(impl_->in_flight_requests_, impl_->cv_drain_complete);
// ... perform inference ...
// Guard destroyed here, counter decremented, cv signaled if reaching 0Memory Ordering Guarantees:
- Acquire (request start): Establishes synchronizes-with edge; new request sees all effects from previous requests
- Release (request end): Allows reloadModel's wait to observe the decrement correctly
-
Timeout-based wait: Uses
condition_variable::wait_until()with 30-second deadline
Drain Algorithm:
// Acquire lock
std::unique_lock<std::mutex> lock(impl_->mutex);
// Wait up to 30 seconds for all requests to complete
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
bool drain_success = impl_->cv_drain_complete.wait_until(
lock,
deadline,
[this]() { return impl_->in_flight_requests_.load(std::memory_order_acquire) == 0; }
);
// If timeout: return false (old model remains active)
if (!drain_success) return false;
// Otherwise: perform atomic swap
impl_ = std::move(new_impl); // Old impl destroyed; new impl becomes activeConfiguration:
{
"model": {
"name": "clip-vit-large-patch14",
"embedding_dim": 768,
"path": "/models/clip-vit-l-14.onnx",
"expected_sha256": "abc123..."
},
"backend": "cuda",
"max_batch_size": 64
}Test Coverage (OCP-HS-01..12):
| Test | Category | Validates |
|---|---|---|
| OCP-HS-01..04 | Basic Scenarios | Reload success, state transitions, sequential reloads, health checks |
| OCP-HS-05..08 | Request Draining | Counter tracking, drain waits for requests, timeout prevention, no request loss |
| OCP-HS-09..12 | Concurrency | Concurrent inference + reload, embedding validity (before/after), race-free operation |
Performance:
- Per-request overhead: ~1-2 ns (atomic ops only)
- Idle reload: microseconds
- Under load: depends on in-flight request latency
- Timeout enforcement: 30 seconds maximum
- All 12 tests complete in ~100-150 ms total
New Config Key: enable_mmap_loading (boolean, default: false)
Implementation Strategy:
Traditional Load: Memory-Mapped Load:
File β Read into heap (copy) File β mmap() view β ONNX Session
β β
Peak memory: full model size Peak memory: metadata only
β β
Runtime: models are in RAM Runtime: lazy page faults
(but still in RAM once used)
Platform Support:
-
Linux:
mmap(fd, MAP_SHARED | MAP_NORESERVE)for read-only access -
Windows:
CreateFileMapping()+MapViewOfFile(PAGE_READONLY) -
macOS: BSD
mmap()variant - Fallback: Traditional heap loading on unsupported platforms
Memory Savings (Measured in Phase 4C Tests):
Test results from Phase 4C (OCP-MM-09..12) using mock models:
-
ViT-B/32 simulation (10 MB):
- RSS measurement available via
/proc/self/status(Linux) - Mmap'd loading shows measurable memory efficiency
- Fallback mechanism verified on unsupported platforms
- RSS measurement available via
-
ViT-L/14 simulation (50 MB):
- Large model shows greater memory benefit from mmap
- RSS tracking works across batch operations
- Memory remains bounded during concurrent inference
Test Coverage:
- OCP-MM-01..04: Initialization success/fallback/error handling
- OCP-MM-05..08: Correctness verification (embeddings identical to traditional)
- OCP-MM-09..12: Memory footprint tracking and concurrent safety
- Platform coverage: Linux (primary), Windows/macOS fallback verified
Key Test Achievements:
- All 12 tests pass in ~2.5 seconds (sub-timeout execution)
- Concurrent threads (4 concurrent) produce correct embeddings
- Batch inference (8-batch) maintains correctness with mmap
- Text embedding generation works correctly with mmap'd models
- No resource leaks (file descriptors, memory) detected
Lifecycle:
// In ONNXClipPlugin::Impl
void* mmap_ptr_{nullptr}; // Mapped region pointer
size_t mmap_size_{0}; // Mapped size
int mmap_fd_{-1}; // Linux file descriptor
HANDLE mmap_file_handle_; // Windows handle
~Impl() {
// Unmap and close file handles
if (mmap_ptr_) munmap(mmap_ptr_, mmap_size_); // Linux
// or UnmapViewOfFile(mmap_ptr_); // Windows
}Configuration:
{
"model": {
"enable_mmap_loading": true,
"path": "/models/clip-vit-large-patch14.onnx"
}
}-
generateEmbeddingBatch()is implemented as sequential single calls; native batched ONNX session execution is planned for Phase 5 (post-Q1 2027). - DirectML backend requires Windows; on Linux
BackendType::DirectMLfalls back to CPU.
- Dynamic model hot-swap (Phase 3): Reload models without server restart
- Memory-mapped model loading (Phase 4): Reduce peak memory for large models
- Native batched inference (Phase 5, optional): True batched ONNX session calls
ThemisDB 1.9.0-beta Β· Home Β· Module-Index Β· GitHub Β· Issues
ThemisDB 1.9.0-beta Β· Home Β· Wiki-Index Β· Module-Index Β· FAQ Β· Quick-Reference Β· GitHub Β· Issues Β· Discussions Β· License
- Batch Operations
- Best Practices
- CRUD Tutorial
- Custom Document Ingestion
- Getting Started Tutorial
- Interactive Examples
- Schema Design
- Video Tutorials
- AQL Reference
- AQL Examples
- AQL Overview
- AQL Feature Roadmap
- AQL Geospatial Guide
- AQL LLM Migration Guide
- AQL API
- AQL Grammar (EBNF)
- AQL Root Overview
- AQL Examples (root)
- API Reference
- API Module README
- OpenAPI Overview
- Client SDK Overview
- SDK Overview
- Operations
- Operations Overview
- Operations Runbook
- Operations Handbook
- ThemisCtl Admin Guide
- Pipeline E2E SOPs
- Deploy Overview
- Docker Overview
- Docker Hub README
- Helm Overview
- Packaging Overview
- Operator Overview
- Security Policy
- Production Hardening Checklist
- Security Hardening Guide
- Encryption Key Management
- Access Control Framework
- Zero Trust Policy
- API Authentication & Authorization
- HSM Production Setup
- PKCS11 Integration
- DSGVO / SOC2 Checklist
- Access Model Runbooks
- Access Model Dashboard
- Maturity Automation Runbook
- Access Review Automation
- Access Model Dashboard
- Access Model Runbooks
- Rights Revocation
- Dr Checklists
- Dr Testing
- Incident Response Playbook
- Incident Response Testing
- GPU Oom Recovery
- Grammar Debugging
- Metrics Scrape Troubleshooting
- Model Swap Procedure
- Quota Tuning
- Subagent Deployment
- Logging Configuration
- Content Model
- Crypto & Keys
- Feature Flags Reference
- Modular Architecture Roadmap
- Modularization Guide
- Module Architecture Index
- PostgreSQL Wire Protocol
- Query Scheduling
- Raft Consensus Design
- Resource Pooling
- Source Directory Guide
- Unified Access Model
- E1 001 Layered Retrieval Design
- E1 002 Ann Abstraction Strategy
- E1 003 Tensor Summary Types
- E1 004 Lora Package Distinction
- E1 005 Model Switch Compatibility
- E1 006 Federated Tensor Summaries
- E2 001 Evaluation Framework Design
- E2 002 Hardware Profile Strategy
- E2 003 Query Planner Routing Model
- E2 004 Approximation Governance Rules
- E2 005 Cross Layer Fallback Confidence Policy
- E3 001 Distributed Tensor Design
- E3 002 Manifest Coordination Strategy
- E3 003 Recovery And Erasure Choice
- E3 004 Tensor Fabric Infrastructure
- Contributing
- Contributing (root)
- Code of Conduct
- Support
- Maintainers
- CTest Guide
- Build Quick Reference
- Developer Wiki Index
- Build / Test / CI
- Module Index
- Branching Strategy
- Disabled Stub Policy
- Docs PR Policy
- GA Promotion Sign Off
- Github Milestones Setup
- Maturity Claim Verification Checklist
- Maturity Evidence Registry
- Merge Gate Bot Config
- Merge Gate Status Live
- Phase 1 Closure Report
- Phase Closure Policy
- Phase Dependency Graph
- Phase3 Enforcement Runbook
- Plugin Submodule Rollback
- PR Version Targeting
- PR Version Targeting Backfill
- Production Ready 2026 Delivery Plan
- Query Module Status
- Readme
- Release Promotion Gate Policy
- Release Validation Checklist
- Security Module 5671 Evidence Summary
- Sharding P6 Residual Risk Acceptance
- Sourcecode Compliance Governance
- Updates Development Status Sign Off
- Wave C Implementation Complete
- Blob Storage
- Cuda
- Ethics Ai
- Exporters
- Huggingface
- Image Analysis
- Importers
- RPC
- Scraper
- Themisdb Ai Watermark Detector
- User Storage Encrypted
- Chimera Architecture
- Chimera Future
- Chimera Readme
- Chimera Roadmap
- Covina Fastapi Ingestion Architecture
- Covina Fastapi Ingestion Future
- Covina Fastapi Ingestion Roadmap
- Vcc Base Architecture
- Vcc Base Future
- Vcc Base Roadmap
- Vcc Clara Ingestion Architecture
- Vcc Clara Ingestion Future
- Vcc Clara Ingestion Roadmap
- Vcc Veritas Architecture
- Vcc Veritas Future
- Vcc Veritas Roadmap
- 01 Hello World
- 02 Todo App
- 03 Contact Manager
- 04 Inventory System
- 05 Time Series Monitor
- 06 Graph Social Network
- 07 Vector Search Documents
- 08 Dms Erp System
- 09 Iot Sensor Network
- 10 Drone Image Analysis
- 11 Blog Wiki
- 12 Expense Tracker
- 13 Recipe Manager
- 14 Ecommerce Catalog
- 15 Event Management
- 16 Kanban Board
- 17 Crm
- 18 Realtime Chat
- 19 Recommendation Engine
- 20 Smart Home
- 21 Coding Platform
- 22 AQL Diagram Tool
- 23 Traveling Salesman
- 24 Moral Philosophy Debates
- API Versioning
- Distributed Sharding
- Feedback Plugins
- Geo
- Gnn
- Image Analysis
- Legal Lora Training
- LLM
- Lora Sync
- Migration
- Nlp
- Performance
- Railway
- Replication
- Rope Visualization
- Sample Product Config
- Security
- Client SDK Overview
- Quickstart
- Sdk Enhancements
- Sdk Implementation Summary
- Test Suite Readme
- Go
- Java
- Javascript
- Php
- Python
- Ruby
- Rust
- Typescript
- 01 Grundlegende Operationen
- 02 AQL Queries
- 03 Graph Daten
- 04 Multimodell Anwendung
- 01 Quickstart Guide
- 02 AQL Referenz Kurzuebersicht
- 03 Datenmodellierung Guide
- 04 Uebungsaufgaben
- 05 Best Practices Guide
- Training Documents
- Training Overview
- 01 Einfuehrung Und Uebersicht
- 02 Datenmodelle Und Architektur
- 03 AQL Abfragesprache
- 04 Installation Und Setup
- 05 Anwendungsbeispiele
- Training Presentations
- Dependencies Readme
- Processmonitor Readme
- Themis.admintools.shared Readme
- Themis.aqlquerybuilder Readme
- Themis.aqlquerybuilder Roadmap
- Themis.auditlogviewer Readme
- Themis.auditlogviewer Roadmap
- Themis.classificationdashboard Readme
- Themis.classificationdashboard Roadmap
- Themis.compliancereports Readme
- Themis.compliancereports Roadmap
- Themis.gisviewer.controlpanel Readme
- Themis.gisviewer.controlpanel Roadmap
- Themis.impactanalysisviewer Readme
- Themis.impactanalysisviewer Roadmap
- Themis.ingestiontool Readme
- Themis.ingestiontool Roadmap
- Themis.keyrotationdashboard Readme
- Themis.keyrotationdashboard Roadmap
- Themis.piimanager Readme
- Themis.piimanager Roadmap
- Themis.retentionmanager Readme
- Themis.retentionmanager Roadmap
- Themis.sagaverifier Readme
- Themis.sagaverifier Roadmap
- Themis.usbadmintool Readme
- Themis.usbadmintool Roadmap
- CI Readme
- CI Roadmap
- Compiler Diagnostics Readme
- Compiler Diagnostics Roadmap
- Completion Readme
- Copilot Ollama Router Readme
- Copilot Ollama Router Roadmap
- Gnn Readme
- Gnn Roadmap
- Rope Visualizer Readme
- Rope Visualizer Roadmap
- Tco Calculator Readme
- Tco Calculator Roadmap
- Tests Readme
- Tests Roadmap
- Themis Config Wx Readme
- Themis Docs Builder Readme
- Wikipedia Ingestion Readme