Physics-inspired text embedding library
Project description
lsdembed - Physics-Inspired Text Embedding Library
Lagrangian Semantic Dynamics Embeddings[LSDEmbed] is a novel text embedding library that uses physics-inspired algorithms to create high-quality semantic embeddings. By modeling text tokens as particles in a physical system with forces of attraction and repulsion, lsdembed captures nuanced semantic relationships that traditional methods might miss.
pip install lsdembed
Features
- Physics-Inspired Embeddings: Uses particle physics simulation to model semantic relationships
- High Performance: Optimized C++ backend with OpenMP parallelization
- Flexible Parameters: Customizable physics parameters for different use cases
- Memory Efficient: Spatial hashing and memory-aware processing
- Easy Persistence: Save and load trained models with compression support
- Multiple Export Formats: Export embeddings as NPZ, CSV, or JSON
Installation
Prerequisites
- Python 3.8 or higher
- C++ compiler with C++17 support
- OpenMP (optional, for parallel processing)
Install from Source
git clone https://github.com/datasciritwik/lsdembed.git
cd lsdembed
pip install -e .
Dependencies
The library requires:
numpy>=1.21.0scipy>=1.7.0pandas>=1.3.0pybind11>=2.6.0(for building)
Quick Start
from lsdembed import LSdembed
from lsdembed.text_processor import TextProcessor
# Single text input (new preferred method)
model = LSdembed({'d': 128})
model.fit("Your entire document text here", chunk_size=300)
# Custom chunking parameters
processor = TextProcessor(chunk_size=200, chunk_overlap=50)
chunks = processor.chunk_text("Your text here")
# Backward compatible list input
model.fit(["Text 1", "Text 2", "Text 3"])
Advanced Usage
Custom Parameters
# Configure physics parameters for your use case
params = {
'd': 256, # Embedding dimension
'alpha': 1.5, # Repulsion strength
'beta': 0.3, # Attraction strength
'gamma': 0.2, # Damping coefficient
'r_cutoff': 2.5, # Force cutoff radius
'dt': 0.05, # Integration time step
'scale': 0.1, # Initial position scale
'seed': 42 # Random seed for reproducibility
}
model = lsdembed(params)
Model Persistence
# Save trained model
model.save_model('my_model.pkl', compress=True)
# Load model later
loaded_model = lsdembed.from_pretrained('my_model.pkl.gz')
# Or load into existing instance
model = lsdembed()
model.load_model('my_model.pkl.gz')
Export Embeddings
# Export in different formats
model.export_embeddings('embeddings.npz', format='npz')
model.export_embeddings('embeddings.csv', format='csv')
model.export_embeddings('embeddings.json', format='json')
Model Information
# Get detailed model information
info = model.get_model_info()
print(f"Status: {info['status']}")
print(f"Chunks: {info['num_chunks']}")
print(f"Dimension: {info['embedding_dimension']}")
print(f"Memory usage: {info['memory_usage_mb']['total_approximate']:.2f} MB")
Physics Parameters Guide
Understanding the physics parameters helps you tune the model for your specific use case:
d(dimension): Higher dimensions capture more nuanced relationships but require more memoryalpha(repulsion): Controls how strongly dissimilar tokens repel each otherbeta(attraction): Controls sequential attraction between adjacent tokensgamma(damping): Higher values lead to faster convergence but may reduce qualityr_cutoff: Limits interaction range, affecting both performance and qualitydt: Smaller values improve stability but increase computation timescale: Initial randomization scale, affects convergence behavior
Recommended Configurations
High Precision (slower, better quality):
params = {'d': 512, 'alpha': 2.0, 'beta': 0.8, 'r_cutoff': 4.0, 'dt': 0.02}
Fast Inference (faster, good quality):
params = {'d': 128, 'alpha': 1.0, 'beta': 0.3, 'r_cutoff': 2.0, 'dt': 0.1}
Balanced (recommended starting point):
params = {'d': 256, 'alpha': 1.5, 'beta': 0.5, 'r_cutoff': 3.0, 'dt': 0.05}
API Reference
lsdembed Class
__init__(params=None)
Initialize the lsdembed model with optional parameters.
fit(texts, chunk_size=1000)
Fit the model on a corpus of texts.
texts: List of strings to train onchunk_size: Maximum characters per chunk
embed_query(query)
Embed a single query string.
- Returns: numpy array of embedding
search(query, top_k=5)
Search for similar chunks.
- Returns: List of (text, score) tuples
save_model(filepath, compress=True)
Save the fitted model to disk.
load_model(filepath)
Load a saved model from disk.
export_embeddings(filepath, format='npz')
Export embeddings in specified format ('npz', 'csv', 'json').
get_model_info()
Get comprehensive model information.
update_params(**kwargs)
Update model parameters after initialization.
TextProcessor Class
tokenize(text)
Tokenize text using the configured pattern.
chunk_texts(texts, max_chars=300)
Split texts into chunks.
calculate_idf(chunks)
Calculate IDF scores for tokens.
Performance Tips
- Memory Management: For large corpora, use smaller embedding dimensions or process in batches
- Parallel Processing: Ensure OpenMP is available for best performance
- Parameter Tuning: Start with balanced parameters and adjust based on your data
- Chunk Size: Optimal chunk size depends on your text length and domain
Examples
See the examples/ directory for complete examples:
basic_usage.py: Simple usage examplemodel_persistence.py: Saving and loading models
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Citation
If you use lsdembed in your research, please cite:
@software{lsdembed,
title={lsdembed: Physics-Inspired Text Embedding Library},
author={Ritwik singh},
year={2025},
url={https://github.com/datasciritwik/lsdembed}
}
Changelog
Version 0.1.0
- Initial release
- Physics-inspired embedding algorithm
- C++ backend with Python bindings
- Model persistence and export functionality
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file lsdembed-0.3.0.tar.gz.
File metadata
- Download URL: lsdembed-0.3.0.tar.gz
- Upload date:
- Size: 26.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9c89d3375b435f5fcc44e4eba9e79bda371149e697cae987caa61a496bfb9846
|
|
| MD5 |
65156e6b160dd2817e52fb848795bebf
|
|
| BLAKE2b-256 |
538dc7124fd9fd85cb2a0759d263d57ae215142b3780c2a403780e979d458485
|
File details
Details for the file lsdembed-0.3.0-cp312-cp312-manylinux_2_39_x86_64.whl.
File metadata
- Download URL: lsdembed-0.3.0-cp312-cp312-manylinux_2_39_x86_64.whl
- Upload date:
- Size: 128.1 kB
- Tags: CPython 3.12, manylinux: glibc 2.39+ x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d93f75ea2a1ddd3132d8cfee0c94b09d30383328edb90bed58ff8ada94817226
|
|
| MD5 |
3ce74f0fa70f20846eca946b50b26ffe
|
|
| BLAKE2b-256 |
cfe4b6849d2ad682f4cdd7ed5db5fc3480a17b4aa0c9da308e99227bccc84dcf
|