Heuristic:666ghj BettaFish Lazy Model Loading
| Knowledge Sources | |
|---|---|
| Domains | Optimization, Machine_Learning, LLMs |
| Last Updated | 2026-10-08 21:30 GMT |
Overview
Defer loading of heavy ML models (SentenceTransformer, sentiment models) until first use to reduce startup time and memory footprint.
Description
Heavy models like `paraphrase-multilingual-MiniLM-L12-v2` (SentenceTransformer for clustering) and the WeiboMultilingualSentiment model are not loaded at agent initialization. Instead, they are loaded lazily on first invocation via a cached property pattern. This avoids loading GPU/CPU models that may never be needed for a given run, and reduces initial memory consumption by hundreds of MB.
Usage
Use this heuristic when startup time matters, when memory is constrained, or when a model may not be needed for every run. Particularly useful for the clustering model (only needed when search results exceed `MAX_CLUSTERED_RESULTS=50`) and the sentiment analyzer (only needed when sentiment analysis is enabled).
The Insight (Rule of Thumb)
- Action: Initialize model reference as `None` in `__init__`, then load on first access via a cached getter method.
- Value: `self._clustering_model = None` → loaded on first call to `_get_clustering_model()`.
- Trade-off: First invocation is slower (model load latency), but subsequent calls are fast (cached). Overall memory footprint is lower if the model is never used.
- Compatibility: Works with any model that has a significant load time (SentenceTransformer, HuggingFace models, PyTorch models).
Reasoning
Loading a SentenceTransformer or multilingual BERT model can take 5-30 seconds and consume 500MB-2GB of memory. If a search query returns fewer than 50 results, clustering is never triggered, making the load unnecessary. By deferring to first use, the system avoids wasted resources. The pattern is especially valuable in multi-agent architectures where multiple heavy models could be loaded but only a subset is needed per run.
Code Evidence
Lazy clustering model from `InsightEngine/agent.py:59-61,95-102`:
# In __init__:
self._clustering_model = None # Lazy-loaded
# On first access:
def _get_clustering_model(self):
if self._clustering_model is None:
logger.info(" 加载聚类模型 (paraphrase-multilingual-MiniLM-L12-v2)...")
self._clustering_model = SentenceTransformer(
"paraphrase-multilingual-MiniLM-L12-v2"
)
return self._clustering_model
Lazy sentiment analyzer initialization from `InsightEngine/tools/sentiment_analyzer.py:85-117`:
class WeiboMultilingualSentimentAnalyzer:
def __init__(self):
self.model = None
self.tokenizer = None
self.device = None
self.is_initialized = False
self.is_disabled = False
# ...
if not SENTIMENT_ANALYSIS_ENABLED:
self.disable("情感分析功能已在配置中关闭。")
elif not (TORCH_AVAILABLE and TRANSFORMERS_AVAILABLE):
self.disable(f"缺少依赖: {missing},情感分析已禁用。")