Skip to content

feat(embeddings): optional CUDA device selection and NVIDIA NIM embedding preset - #358

Open
Coding-Dev-Tools wants to merge 5 commits into
mainfrom
feat/nvidia-embedding-backend
Open

Coding-Dev-Tools wants to merge 5 commits into
mainfrom
feat/nvidia-embedding-backend

Conversation

@Coding-Dev-Tools

Copy link
Copy Markdown
Owner

Summary

Adds optional NVIDIA CUDA device selection for local sentence-transformers embeddings and an opt-in NVIDIA NIM embeddings preset on the existing OpenAI-compatible ApiEmbedder, without changing Engraphis's default offline/CPU behavior.

What changed & why

  • Optional CUDA device selection (engraphis/backends/embedder_st.py, engraphis/config.py, engraphis/factory.py, engraphis/service.py):
    • Adds ENGRAPHIS_EMBED_DEVICE (auto | cpu | cuda | cuda:<index>) and resolve_embed_device().
    • When unset (default), behavior is 100% identical (no torch import, no device kwarg passed to SentenceTransformer).
    • auto selects cuda when torch.cuda.is_available() is true and falls back cleanly to cpu on CPU-only/PyTorch-free installs. Explicit cuda / cuda:<index> falls back to cpu with a warning unless require_exact_backends=True, in which case an actionable error is raised.
  • Opt-in NVIDIA NIM embeddings preset (engraphis/backends/embedder_api.py, engraphis/backends/embedder_st.py):
    • Extends existing ApiEmbedder (no duplicate backend module) with create_nvidia_nim_embedder() and factory routing for ENGRAPHIS_EMBED_MODEL=nvidia-nim[:<model>] and ENGRAPHIS_EMBED_PROVIDER=nvidia-nim.
    • Defaults to https://integrate.api.nvidia.com/v1 + nvidia/nv-embedqa-e5-v5 + NVIDIA_API_KEY (or ENGRAPHIS_EMBED_API_KEY), and supports self-hosted NIM via ENGRAPHIS_EMBED_BASE_URL / NVIDIA_NIM_BASE_URL (HTTPS required for non-loopback; loopback self-hosted NIM permits unauthenticated local containers).
    • Adds asymmetric input_type ("passage" on writes/rebuilds/sync, "query" on recall/history/grounded support) and truncate="END" / encoding_format="float" in both batch and per-item fallback requests via a backward-compatible embed_texts() helper in engraphis/core/interfaces.py.
  • Privacy, secret-memory guards & dimension safety (engraphis/core/engine.py, engraphis/core/recall.py, engraphis/core/grounded.py, engraphis/core/sync.py):
    • Preserves reject_secrets before embedding and prevents sensitivity="secret" memories from being sent to remote embedding APIs during writes and versioned rebuilds (is_remote_embedder()).
    • Preserves versioned embedding-space fingerprinting and guarded rebuilds so switching models/dimensions (e.g. 384d local -> 1024d NIM) never silently mixes vector dimensions, and unversioned API embedders remain fail-closed on persistent stores.
    • Keeps all API keys, URLs, and model names redacted from logs and errors.
  • Docs & benchmark evidence (docs/CONFIGURATION.md, docs/LLM_PROVIDERS.md, .env.example, BENCHMARKS.md, README.md, docs/benchmark-evidence/, docs/images/):
    • Documents all new env vars, hosted & self-hosted NIM examples, local CUDA opt-in, and privacy/secret-memory guarantees (no secret values).
    • Refreshes the immutable offline benchmark evidence artifact (offline-fixtures-nvidia-embeddings-20261127.json) and rendered benchmark visuals.

Verification

All HTTP and PyTorch interactions in unit tests are mocked (no network, no GPU required):

  • python -m pytest tests/test_nvidia_embeddings.py tests/test_embeddings.py tests/test_backends_factories.py tests/test_provider_error_redaction.py tests/test_config.py tests/test_grounded.py tests/test_eval_performance_engine.py tests/test_benchmark_evidence.py -q -> PASS (PYTEST_EXIT=0, 268 passed, 1 skipped)
  • python -m ruff check . -> PASS (All checks passed!)
  • python -m pyright --pythonpath .venv/Scripts/python.exe engraphis/core/interfaces.py engraphis/core/engine.py engraphis/core/recall.py engraphis/core/grounded.py engraphis/core/sync.py engraphis/backends/embedder_api.py engraphis/backends/embedder_st.py engraphis/factory.py -> PASS (0 errors, 0 warnings, 0 informations; note local .venv has a pre-existing partial transformers install causing unrelated AutoTokenizer/AutoProcessor missing-symbol errors in untouched extractor.py/eval/harness.py and an unrelated ImportError in tests/test_mcp_server.py::test_stdio_first_semantic_tool_call_completes_with_cached_model)
  • python scripts/check_commercial_manifest.py -> PASS (commercial manifest check: OK)
  • python scripts/externalize_dashboard_assets.py -> PASS (exit 0)
  • All 9 offline eval gates (sample.jsonl, codemem.jsonl, ablation, reinforcement, adversarial_memory_security, grounded, code_arm, spec_crawl, evidence_contracts) -> PASS (exit 0 each)
  • media_gate.py on regenerated docs/images/context-efficiency.png and docs/images/evidence-backed-agent-examples.png -> PASS

Needs 2 fresh reviewers before merge.

…ding preset

Add optional CUDA acceleration for local sentence-transformers embeddings
and an opt-in NVIDIA NIM preset on the existing OpenAI-compatible
ApiEmbedder while keeping default offline CPU behavior 100% unchanged:

- Add ENGRAPHIS_EMBED_DEVICE (auto | cpu | cuda | cuda:<index>) resolution
  in embedder_st.py with safe fallback to CPU when CUDA or torch is
  unavailable (or actionable RuntimeError under require_exact_backends).
- Extend ApiEmbedder with create_nvidia_nim_embedder() preset (default
  https://integrate.api.nvidia.com/v1, model nvidia/nv-embedqa-e5-v5,
  NVIDIA_API_KEY / ENGRAPHIS_EMBED_API_KEY, self-hosted NIM base URL via
  ENGRAPHIS_EMBED_BASE_URL / NVIDIA_NIM_BASE_URL, and asymmetric
  input_type query/passage + truncate handling).
- Forward input_type="query" vs "passage" through core/interfaces.py
  embed_texts() without breaking existing Embedder implementations.
- Enforce remote privacy guards so sensitivity="secret" memories are never
  transmitted to remote embedding APIs during writes or rebuilds, while
  preserving existing versioned embedding-space rebuild and dimension
  mismatch protections.
- Document env vars, examples, and privacy notes in docs/CONFIGURATION.md,
  docs/LLM_PROVIDERS.md, and .env.example, add mocked unit tests in
  tests/test_nvidia_embeddings.py, and refresh the offline benchmark
  evidence artifact.
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-27T10:12:19.168919Z
We couldn’t complete this review. Comment @codex review to try again.
666aef3 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Coding-Dev-Tools

Copy link
Copy Markdown
Owner Author

2-Agent Independent Review & Verification Summary (Head b420e46f)

  • Changes after review rounds: Closed all remote secret-memory embedding paths (grounded_recall, adaptive_context, SyncEngine._write, update_memory including legacy metadata-secret rows, why/_relatedness, correct, approve_for_prompt, promote, merge, and consolidation digests/profiles), reverted .env.example (0 protected paths), removed contiguous AKIA test literal, added C0 control-char & trailing-dot loopback handling, added non-strict startup/history outage fallbacks, skipped single-item retry duplication, and refreshed offline benchmark evidence + PNGs (media_gate.py OK).
  • CI & local gates (all PASS): 30/30 GitHub Actions checks green (mergeState=CLEAN), tests/test_nvidia_embeddings.py + tests/test_benchmark_evidence.py (71/71), live 11-path secret-memory audit (0 leaks, 0 MemoryConflict), ruff check . (0 errors), pyright on all touched included modules (0 errors).
  • 2-agent final review: 2/2 fresh independent reviewers APPROVE (0 blockers, 0 code majors). Schema-v2 approval staged at agent-config/review/approvals/engraphis-358-b420e46f.json (authorization: null).
  • Merge-gate size note: Diff is 2,514 lines (920 source + 770 tests + 703 generated docs/benchmark-evidence/*.json + 121 docs/SVGs) vs maxChangedLines: 1500 because docs/benchmark-evidence/* is not in profiles/engraphis.json generated globs; requires operator-authorized -MaxChangedLines override.

Three defects in the NVIDIA NIM embedding work:

* `_select_api_provider()` consulted `ENGRAPHIS_EMBED_PROVIDER` before
  exempting the `local:` prefix or an explicit `provider="local"`. With
  `ENGRAPHIS_EMBED_PROVIDER=nvidia-nim`, `get_embedder("local:...")` was
  routed to the remote API, so scripts/importer.py's offline import guard
  sent local document text and a bogus "local:..." model id to NIM.
  Honor `local:` and explicit local providers first, and reject an
  unknown explicit provider when require_exact is set.
* `correct()`, `approve()`, and `_merge_locked()` rewrote
  `memories.sensitivity` from the column alone. Legacy rows keep the
  secret flag in metadata, so finalizing reset them to 'normal' and
  `SyncEngine.export_workspace()` (which filters on sensitivity !=
  'secret') then exported them. Fold `is_secret_memory()` into every
  finalizer and into the merge sensitivity lattice.
* `is_secret_memory()` matched only the literal 'secret', failing open
  on labels such as 'restricted' or 'confidential'. Apply the
  {"normal", "sensitive"} allowlist the rest of the codebase already
  uses so unknown labels fail closed.
`tests/test_benchmark_evidence.py` hashes every `.py` under `engraphis/`
and `eval/`, so the embedder_st, engine, and interfaces changes
invalidated the committed registry artifact and failed the whole Python
matrix. Export a new immutable artifact and repoint the test constants,
README prefix, BENCHMARKS.md name/sha, and the fixture-suite digest. The
SVGs and PNGs were regenerated so their embedded provenance matches.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant