Skip to content

perf(app): reduce peak memory usage #8090

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions invokeai/app/invocations/compel.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,13 @@ def _lora_loader() -> Iterator[Tuple[ModelPatchRaw, float]]:

c, _options = compel.build_conditioning_tensor_for_conjunction(conjunction)

del compel
del patched_tokenizer
del tokenizer
del ti_manager
del text_encoder
del text_encoder_info

c = c.detach().to("cpu")

conditioning_data = ConditioningFieldData(conditionings=[BasicConditioningInfo(embeds=c)])
Expand Down Expand Up @@ -222,7 +229,10 @@ def _lora_loader() -> Iterator[Tuple[ModelPatchRaw, float]]:
else:
c_pooled = None

del compel
del patched_tokenizer
del tokenizer
del ti_manager
del text_encoder
del text_encoder_info

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import gc
import traceback
from contextlib import suppress
from threading import BoundedSemaphore, Thread
Expand Down Expand Up @@ -439,6 +440,12 @@ def _process(
poll_now_event.wait(self._polling_interval)
continue

# GC-ing here can reduce peak memory usage of the invoke process by freeing allocated memory blocks.
# Most queue items take seconds to execute, so the relative cost of a GC is very small.
# Python will never cede allocated memory back to the OS, so anything we can do to reduce the peak
# allocation is well worth it.
gc.collect()

self._invoker.services.logger.info(
f"Executing queue item {self._queue_item.item_id}, session {self._queue_item.session_id}"
)
Expand Down
4 changes: 4 additions & 0 deletions invokeai/backend/model_patcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ def apply_ti(
text_encoder: Union[CLIPTextModel, CLIPTextModelWithProjection],
ti_list: List[Tuple[str, TextualInversionModelRaw]],
) -> Iterator[Tuple[CLIPTokenizer, TextualInversionManager]]:
if len(ti_list) == 0:
yield tokenizer, TextualInversionManager(tokenizer)
return

init_tokens_count = None
new_tokens_added = None

Expand Down