Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added different embedding models #1800

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

himanshugt16
Copy link
Contributor

@himanshugt16 himanshugt16 commented Feb 11, 2025

Summary by CodeRabbit

  • New Features

    • Added support for multiple embedding models, enabling enhanced text representation using diverse techniques.
    • Introduced distinct configurations for sparse and rerank embedding processes.
  • Refactor

    • Improved the training and embedding retrieval workflows to return structured data.
    • Enhanced input validation for better reliability in processing text data.

Copy link

coderabbitai bot commented Feb 11, 2025

Walkthrough

The changes update the LLMProcessor class to support multiple embedding models. A new configuration (vectors_config) is introduced to enable handling of different models, including sparse and rerank embeddings. New class-level attributes and methods—such as load_sparse_embedding_model, load_rerank_embedding_model, get_sparse_embedding, and get_rerank_embedding—are added. The constructor and the train method are modified to initialize and load the respective models, and the get_embedding method now returns a dictionary of embeddings. An auxiliary static method check_empty_string is added for input validation.

Changes

File(s) Change Summary
kairon/.../llm/processor.py - Added class attributes _sparse_embedding and _rerank_embedding
- Introduced vectors_config and sparse_vectors_config in initialization
- Modified train to call new loader methods for embedding models
- Updated get_embedding to support multiple models via get_sparse_embedding and get_rerank_embedding
- Added static method check_empty_string

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant LLMProcessor

    Client->>LLMProcessor: train()
    LLMProcessor->>LLMProcessor: load_sparse_embedding_model()
    LLMProcessor->>LLMProcessor: load_rerank_embedding_model()
    Note over LLMProcessor: Initialize embedding models & configurations

    Client->>LLMProcessor: get_embedding(sentence)
    LLMProcessor->>LLMProcessor: check_empty_string(sentence)
    LLMProcessor->>LLMProcessor: get_sparse_embedding(sentence)
    LLMProcessor->>LLMProcessor: get_rerank_embedding(sentence)
    LLMProcessor->>Client: Return embeddings as dict keyed by model names
Loading

Possibly related PRs

Suggested reviewers

  • hiteshghuge

Poem

Oh, what a joyous hop it is today,
As embeddings dance in a brand-new way.
Sparse and rerank, side by side they play,
In code-burrows deep, where logic holds sway.
I'm a rabbit of code, celebrating each bright display!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (7)
kairon/shared/llm/processor.py (7)

76-77: Consider lazy loading or error handling.
Loading both sparse and rerank embeddings during training can be time-consuming if the models are large. You might consider lazy loading or implement error handling in case model downloads fail.


118-120: Remove commented-out code if no longer needed.
These lines referencing the old single-vector approach are commented out. Consider removing them or adding a clear comment explaining why they are retained.


520-527: Use logging instead of print.
“SPARSE MODEL LOADED” is useful feedback, but consider logging.info(...) instead of print(...) for standardized logging in production.


528-535: Same note on print statements.
As with sparse loading, prefer logging.info(...) for “RERANK MODEL LOADED” to maintain consistent logging.


536-557: Consider removing debug prints and safeguarding array access.

  1. Replace direct print(embedding) with logging or remove it.
  2. If self._sparse_embedding.passage_embed(sentence) unexpectedly returns an empty list, embedding[0] will fail. Consider a pre-check or exception handling.

559-573: Fix docstring mismatch in rerank embedding.
The docstring says “Generate a sparse embedding,” but this method actually returns a rerank embedding from the ColBERT model. Update the docstring to avoid confusion.


574-581: Simplify check_empty_string and handle potential None.
According to static analysis, you can simplify this function to return a boolean in one line. Make sure you handle None safely if it’s ever passed. Example fix:

-    if not value:
-        return True
-    if not value.strip():
-        return True
-    else:
-        return False
+    return not value or not value.strip()
🧰 Tools
🪛 Ruff (0.8.2)

578-581: Return the condition bool(not value.strip()) directly

Replace with return bool(not value.strip())

(SIM103)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e420b3d and 52b66f8.

📒 Files selected for processing (1)
  • kairon/shared/llm/processor.py (9 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
kairon/shared/llm/processor.py

578-581: Return the condition bool(not value.strip()) directly

Replace with return bool(not value.strip())

(SIM103)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (python)
  • GitHub Check: Python CI
🔇 Additional comments (12)
kairon/shared/llm/processor.py (12)

33-34: Be mindful of concurrency issues with class-level embeddings.
Since _sparse_embedding and _rerank_embedding are defined as class-level attributes rather than instance-level, concurrent usage or multithreading might cause unexpected behavior or race conditions. If multiple bots and threads share the same class, ensure proper synchronization or refactor to instance-level as needed.


45-57: Configuration approach looks good.
Defining vectors_config for multiple models is a clean approach to add new or variant embeddings. No major concerns here.


59-62: Sparse config is an effective placeholder.
Keeping a separate config dictionary (sparse_vectors_config) for BM25 is future-friendly. Just confirm that you no longer need the commented vector_config.


121-132: Validate matching array lengths when building points.
You build a dictionary of embeddings per model for each index. Verify that each embedding array matches the length of vector_ids to avoid misalignment issues.


206-206: Docstring aligns with multi-model approach.
Your updated docstring clarifies that multiple models are used for embeddings. Great clarity for maintainers.


212-212: Properly initializing the embeddings dictionary.
Storing embeddings in a dict by model name is a solid approach for organizing multi-model outputs.


221-221: Litellm usage looks correct.
You're extracting embedding vectors from result["data"] properly.


223-227: BM25 embedding usage.
These lines populate the 'bm25' key with sparse embeddings. Ensure your downstream logic fully supports sparse vectors if you plan to query them.


228-231: ColBERT embeddings stored correctly.
You invoke get_rerank_embedding to populate the 'colbertv2.0' key. The usage here is consistent with multi-model design.


234-234: Good single-text return structure.
Returning a dictionary of model → single embedding for single-text inputs keeps usage consistent with multi-text outputs.


345-347: Review Qdrant multivector support.
Assigning both 'vectors' and 'sparse_vectors' in the creation payload is correct for multi-vector indexing, but confirm your Qdrant deployment supports these features (version compatibility, etc.).


518-518: Return statement is straightforward.
No issues here; the function properly modifies and returns the user’s message.

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