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

[Improvements] Manage segment cache and memory #1670

Merged
merged 16 commits into from
Jan 31, 2024

Conversation

nicolasgere
Copy link
Contributor

@nicolasgere nicolasgere commented Jan 23, 2024

The goal is too limit the memory usage by setting a limit that Chroma will do the best effort to not use more memory than the threshold by removing from cache segment.
How?
When a segment need to be load from the disk, we will check what is the size of all the already loaded index in memory, and will free some memory using LRU kind algo.

Copy link

Reviewer Checklist

Please leverage this checklist to ensure your code review is thorough before approving

Testing, Bugs, Errors, Logs, Documentation

  • Can you think of any use case in which the code does not behave as intended? Have they been tested?
  • Can you think of any inputs or external events that could break the code? Is user input validated and safe? Have they been tested?
  • If appropriate, are there adequate property based tests?
  • If appropriate, are there adequate unit tests?
  • Should any logging, debugging, tracing information be added or removed?
  • Are error messages user-friendly?
  • Have all documentation changes needed been made?
  • Have all non-obvious changes been commented?

System Compatibility

  • Are there any potential impacts on other parts of the system or backward compatibility?
  • Does this change intersect with any items on our roadmap, and if so, is there a plan for fitting them together?

Quality

  • Is this code of a unexpectedly high quality (Readability, Modularity, Intuitiveness)

@@ -116,6 +116,7 @@ class Settings(BaseSettings): # type: ignore
is_persistent: bool = False
persist_directory: str = "./chroma"

chroma_memory_limit: int = 0
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit add units to this chroma_memory_limit_gb etc

Copy link
Collaborator

@HammadB HammadB left a comment

Choose a reason for hiding this comment

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

Can we add a test for this? We could do a property-based state machine test or basic unit tests with a couple cases. The former is preferable as we can also test edge cases like partial sizes/best-effort exhaustively etc

@@ -116,6 +116,7 @@ class Settings(BaseSettings): # type: ignore
is_persistent: bool = False
persist_directory: str = "./chroma"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I would update the documentation.

@nicolasgere nicolasgere changed the title WIP: [inprovements] Manage segment cache and memory [Improvements] Manage segment cache and memory Jan 25, 2024
@@ -116,6 +116,7 @@ class Settings(BaseSettings): # type: ignore
is_persistent: bool = False
persist_directory: str = "./chroma"

chroma_memory_limit_bytes: int = 0
Copy link
Collaborator

Choose a reason for hiding this comment

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

How do I turn this capability on and off? Is 0 implicitly off?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes. 0 is unlimited

SEGMENT_TYPE_IMPLS = {
SegmentType.SQLITE: "chromadb.segment.impl.metadata.sqlite.SqliteMetadataSegment",
SegmentType.HNSW_LOCAL_MEMORY: "chromadb.segment.impl.vector.local_hnsw.LocalHnswSegment",
SegmentType.HNSW_LOCAL_PERSISTED: "chromadb.segment.impl.vector.local_persistent_hnsw.PersistentLocalHnswSegment",
}


def get_directory_size(directory: str) -> int:
Copy link
Collaborator

Choose a reason for hiding this comment

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

can we move this into utils

total_size = sum(segment_sizes.values())
new_segment_size = self._get_segment_disk_size(collection_id)

while total_size + new_segment_size >= target_size and self._segment_cache.keys():
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we move this LRU logic into a cleaner abstraction with eviction handles - like https://github.com/chroma-core/chroma/blob/main/chromadb/utils/lru_cache.py

@@ -150,6 +197,9 @@ def get_segment(self, collection_id: UUID, type: Type[S]) -> S:
raise ValueError(f"Invalid segment type: {type}")

if scope not in self._segment_cache[collection_id]:
memory_limit = self._system.settings.require("chroma_memory_limit_bytes")
if type == VectorReader and self._system.settings.require("is_persistent") and memory_limit > 0:
self._cleanup_segment(collection_id, memory_limit)
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: cleanup_segment could be renamed a bit more explicitly / when we have a proper lru cache abstraction for this


@invariant()
@precondition(lambda self: self.system.settings.is_persistent is True)
def cache_should_not_be_bigger_than_settings(self):
Copy link
Collaborator

Choose a reason for hiding this comment

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

whats the behavior for boundary conditions? Eg. if the limit is 10GB and we have two files - 6GB and 7GB, will we always only allow one?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, it this what we want? We could add a message in log when a collection got evicted for memory constraint

Copy link
Collaborator

Choose a reason for hiding this comment

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

Yeah lets log



@patch('chromadb.segment.impl.manager.local.get_directory_size', SegmentManagerStateMachine.mock_directory_size)
def test_segment_manager(caplog: pytest.LogCaptureFixture, system: System) -> None:
Copy link
Collaborator

Choose a reason for hiding this comment

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

nice

@@ -116,6 +116,7 @@ class Settings(BaseSettings): # type: ignore
is_persistent: bool = False
persist_directory: str = "./chroma"

chroma_memory_limit_bytes: int = 0
chroma_server_host: Optional[str] = None
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we introduce a config - called segment_manager_cache_policy and make this one of many types?

@@ -60,7 +59,12 @@ def __init__(self, system: System):
self._system = system
self._opentelemetry_client = system.require(OpenTelemetryClient)
self._instances = {}
self._segment_cache = defaultdict(dict)
self.segment_cache: Dict[SegmentScope, SegmentCache] = {SegmentScope.METADATA: BasicCache(), SegmentScope.VECTOR: BasicCache()}
if system.settings.chroma_segment_cache_policy is "LRU" and system.settings.chroma_memory_limit_bytes > 0:
Copy link
Collaborator

Choose a reason for hiding this comment

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

should use require() and catch the exception since its optional

@@ -97,7 +106,9 @@ def reset_state(self) -> None:
instance.stop()
instance.reset_state()
self._instances = {}
self._segment_cache = defaultdict(dict)
self.segment_cache[SegmentScope.METADATA].reset()
Copy link
Collaborator

Choose a reason for hiding this comment

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

we don't need to to cache metadata segments with LRU, since its all one segment in sqlite

if len(segments) == 0:
return 0
size = get_directory_size(
os.path.join(self._system.settings.require("persist_directory"), str(segments[0]["id"])))
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: leave comment stating assumption of one vector segment for this line - otherwise hardcoded [0] is confusing

Copy link
Collaborator

@HammadB HammadB left a comment

Choose a reason for hiding this comment

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

Some minor changes, but otherwise looks great!

@MrZoidberg
Copy link
Contributor

I think the memory management should use docker limits if present as a default limit.

@nicolasgere
Copy link
Contributor Author

It can be possible, even if for now, our limit is not an hard limit. We are adding documentation to explain more about how to use it. chroma-core/docs#211

@nicolasgere nicolasgere merged commit e5751fd into main Jan 31, 2024
98 checks passed
tazarov pushed a commit to amikos-tech/chroma-core that referenced this pull request Feb 10, 2024
Add configuration to limit the memory use by segment cache.
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.

None yet

3 participants