2022-12-01 05:33:20 +00:00
|
|
|
# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)
|
|
|
|
|
2023-05-21 10:24:37 +00:00
|
|
|
from logging import Logger
|
2023-08-18 14:57:18 +00:00
|
|
|
|
2024-02-07 06:41:23 +00:00
|
|
|
import torch
|
|
|
|
|
2024-07-03 16:04:22 +00:00
|
|
|
from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage
|
|
|
|
from invokeai.app.services.board_images.board_images_default import BoardImagesService
|
|
|
|
from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage
|
|
|
|
from invokeai.app.services.boards.boards_default import BoardService
|
|
|
|
from invokeai.app.services.bulk_download.bulk_download_default import BulkDownloadService
|
|
|
|
from invokeai.app.services.config.config_default import InvokeAIAppConfig
|
|
|
|
from invokeai.app.services.download.download_default import DownloadQueueService
|
|
|
|
from invokeai.app.services.events.events_fastapievents import FastAPIEventService
|
|
|
|
from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
|
|
|
|
from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
|
|
|
|
from invokeai.app.services.images.images_default import ImageService
|
|
|
|
from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
|
|
|
|
from invokeai.app.services.invocation_services import InvocationServices
|
|
|
|
from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
|
|
|
|
from invokeai.app.services.invoker import Invoker
|
|
|
|
from invokeai.app.services.model_images.model_images_default import ModelImageFileStorageDisk
|
|
|
|
from invokeai.app.services.model_manager.model_manager_default import ModelManagerService
|
|
|
|
from invokeai.app.services.model_records.model_records_sql import ModelRecordServiceSQL
|
|
|
|
from invokeai.app.services.names.names_default import SimpleNameService
|
2024-02-08 05:09:59 +00:00
|
|
|
from invokeai.app.services.object_serializer.object_serializer_disk import ObjectSerializerDisk
|
2024-02-07 12:30:46 +00:00
|
|
|
from invokeai.app.services.object_serializer.object_serializer_forward_cache import ObjectSerializerForwardCache
|
2024-07-03 16:04:22 +00:00
|
|
|
from invokeai.app.services.session_processor.session_processor_default import (
|
|
|
|
DefaultSessionProcessor,
|
|
|
|
DefaultSessionRunner,
|
|
|
|
)
|
|
|
|
from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue
|
2023-12-13 00:19:59 +00:00
|
|
|
from invokeai.app.services.shared.sqlite.sqlite_util import init_db
|
2024-07-03 16:04:22 +00:00
|
|
|
from invokeai.app.services.urls.urls_default import LocalUrlService
|
|
|
|
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
|
2024-02-07 06:41:23 +00:00
|
|
|
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData
|
2023-05-21 10:24:37 +00:00
|
|
|
from invokeai.backend.util.logging import InvokeAILogger
|
2023-07-08 00:47:29 +00:00
|
|
|
from invokeai.version.invokeai_version import __version__
|
2023-04-06 04:06:05 +00:00
|
|
|
|
2022-12-01 05:33:20 +00:00
|
|
|
|
|
|
|
# TODO: is there a better way to achieve this?
|
2023-03-03 06:02:00 +00:00
|
|
|
def check_internet() -> bool:
|
|
|
|
"""
|
2022-12-01 05:33:20 +00:00
|
|
|
Return true if the internet is reachable.
|
|
|
|
It does this by pinging huggingface.co.
|
2023-03-03 06:02:00 +00:00
|
|
|
"""
|
2022-12-01 05:33:20 +00:00
|
|
|
import urllib.request
|
2023-03-03 06:02:00 +00:00
|
|
|
|
|
|
|
host = "http://huggingface.co"
|
2022-12-01 05:33:20 +00:00
|
|
|
try:
|
2023-03-03 06:02:00 +00:00
|
|
|
urllib.request.urlopen(host, timeout=1)
|
2022-12-01 05:33:20 +00:00
|
|
|
return True
|
2023-08-17 22:45:25 +00:00
|
|
|
except Exception:
|
2022-12-01 05:33:20 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
|
2023-08-17 23:17:38 +00:00
|
|
|
logger = InvokeAILogger.get_logger()
|
2023-05-21 10:24:37 +00:00
|
|
|
|
|
|
|
|
2022-12-01 05:33:20 +00:00
|
|
|
class ApiDependencies:
|
|
|
|
"""Contains and initializes all dependencies for the API"""
|
2023-03-03 06:02:00 +00:00
|
|
|
|
2023-08-01 07:28:05 +00:00
|
|
|
invoker: Invoker
|
2022-12-01 05:33:20 +00:00
|
|
|
|
2023-05-24 15:00:07 +00:00
|
|
|
@staticmethod
|
2024-01-14 19:54:53 +00:00
|
|
|
def initialize(config: InvokeAIAppConfig, event_handler_id: int, logger: Logger = logger) -> None:
|
2023-07-21 02:45:35 +00:00
|
|
|
logger.info(f"InvokeAI version {__version__}")
|
|
|
|
logger.info(f"Root directory = {str(config.root_path)}")
|
2022-12-01 05:33:20 +00:00
|
|
|
|
2024-03-11 12:01:48 +00:00
|
|
|
output_folder = config.outputs_path
|
2024-02-07 06:41:23 +00:00
|
|
|
if output_folder is None:
|
|
|
|
raise ValueError("Output folder is not set")
|
|
|
|
|
2023-12-10 08:51:45 +00:00
|
|
|
image_files = DiskImageFileStorage(f"{output_folder}/images")
|
2022-12-01 05:33:20 +00:00
|
|
|
|
2024-03-06 03:57:05 +00:00
|
|
|
model_images_folder = config.models_path
|
|
|
|
|
2023-12-13 00:19:59 +00:00
|
|
|
db = init_db(config=config, logger=logger, image_files=image_files)
|
2023-12-10 13:47:53 +00:00
|
|
|
|
2023-09-24 05:12:51 +00:00
|
|
|
configuration = config
|
|
|
|
logger = logger
|
2023-04-06 04:06:05 +00:00
|
|
|
|
2023-09-24 05:12:51 +00:00
|
|
|
board_image_records = SqliteBoardImageRecordStorage(db=db)
|
|
|
|
board_images = BoardImagesService()
|
|
|
|
board_records = SqliteBoardRecordStorage(db=db)
|
|
|
|
boards = BoardService()
|
|
|
|
events = FastAPIEventService(event_handler_id)
|
2024-02-17 05:29:05 +00:00
|
|
|
bulk_download = BulkDownloadService()
|
2023-09-24 05:12:51 +00:00
|
|
|
image_records = SqliteImageRecordStorage(db=db)
|
|
|
|
images = ImageService()
|
|
|
|
invocation_cache = MemoryInvocationCache(max_cache_size=config.node_cache_size)
|
2024-02-08 05:09:59 +00:00
|
|
|
tensors = ObjectSerializerForwardCache(
|
2024-02-10 08:11:28 +00:00
|
|
|
ObjectSerializerDisk[torch.Tensor](output_folder / "tensors", ephemeral=True)
|
2024-02-08 05:09:59 +00:00
|
|
|
)
|
2024-02-07 12:30:46 +00:00
|
|
|
conditioning = ObjectSerializerForwardCache(
|
2024-02-10 08:11:28 +00:00
|
|
|
ObjectSerializerDisk[ConditioningFieldData](output_folder / "conditioning", ephemeral=True)
|
2024-02-07 06:41:23 +00:00
|
|
|
)
|
2024-05-06 01:00:31 +00:00
|
|
|
download_queue_service = DownloadQueueService(app_config=configuration, event_bus=events)
|
2024-03-07 00:31:39 +00:00
|
|
|
model_images_service = ModelImageFileStorageDisk(model_images_folder / "model_images")
|
2024-02-10 23:09:45 +00:00
|
|
|
model_manager = ModelManagerService.build_model_manager(
|
2024-02-16 03:41:29 +00:00
|
|
|
app_config=configuration,
|
2024-07-10 13:41:46 +00:00
|
|
|
model_record_service=ModelRecordServiceSQL(db=db, logger=logger),
|
2024-02-16 03:41:29 +00:00
|
|
|
download_queue=download_queue_service,
|
|
|
|
events=events,
|
2023-11-26 22:13:31 +00:00
|
|
|
)
|
2023-09-24 05:12:51 +00:00
|
|
|
names = SimpleNameService()
|
|
|
|
performance_statistics = InvocationStatsService()
|
2024-05-24 01:23:26 +00:00
|
|
|
session_processor = DefaultSessionProcessor(session_runner=DefaultSessionRunner())
|
2023-09-24 05:12:51 +00:00
|
|
|
session_queue = SqliteSessionQueue(db=db)
|
|
|
|
urls = LocalUrlService()
|
2023-10-17 06:02:15 +00:00
|
|
|
workflow_records = SqliteWorkflowRecordsStorage(db=db)
|
2022-12-01 05:33:20 +00:00
|
|
|
|
2023-02-25 04:11:28 +00:00
|
|
|
services = InvocationServices(
|
2023-09-24 05:12:51 +00:00
|
|
|
board_image_records=board_image_records,
|
2023-06-14 14:07:20 +00:00
|
|
|
board_images=board_images,
|
2023-09-24 05:12:51 +00:00
|
|
|
board_records=board_records,
|
|
|
|
boards=boards,
|
2024-01-08 02:29:42 +00:00
|
|
|
bulk_download=bulk_download,
|
2023-09-24 05:12:51 +00:00
|
|
|
configuration=configuration,
|
|
|
|
events=events,
|
|
|
|
image_files=image_files,
|
|
|
|
image_records=image_records,
|
|
|
|
images=images,
|
|
|
|
invocation_cache=invocation_cache,
|
2023-05-04 02:30:30 +00:00
|
|
|
logger=logger,
|
2024-03-06 03:57:05 +00:00
|
|
|
model_images=model_images_service,
|
2023-09-24 05:12:51 +00:00
|
|
|
model_manager=model_manager,
|
2023-12-22 17:35:57 +00:00
|
|
|
download_queue=download_queue_service,
|
2023-09-24 05:12:51 +00:00
|
|
|
names=names,
|
|
|
|
performance_statistics=performance_statistics,
|
|
|
|
session_processor=session_processor,
|
|
|
|
session_queue=session_queue,
|
|
|
|
urls=urls,
|
2023-10-17 06:02:15 +00:00
|
|
|
workflow_records=workflow_records,
|
2024-02-07 06:41:23 +00:00
|
|
|
tensors=tensors,
|
|
|
|
conditioning=conditioning,
|
2022-12-01 05:33:20 +00:00
|
|
|
)
|
|
|
|
|
2023-02-25 04:11:28 +00:00
|
|
|
ApiDependencies.invoker = Invoker(services)
|
2023-09-24 05:12:51 +00:00
|
|
|
db.clean()
|
feat: queued generation (#4502)
* fix(config): fix typing issues in `config/`
`config/invokeai_config.py`:
- use `Optional` for things that are optional
- fix typing of `ram_cache_size()` and `vram_cache_size()`
- remove unused and incorrectly typed method `autoconvert_path`
- fix types and logic for `parse_args()`, in which `InvokeAIAppConfig.initconf` *must* be a `DictConfig`, but function would allow it to be set as a `ListConfig`, which presumably would cause issues elsewhere
`config/base.py`:
- use `cls` for first arg of class methods
- use `Optional` for things that are optional
- fix minor type issue related to setting of `env_prefix`
- remove unused `add_subparser()` method, which calls `add_parser()` on an `ArgumentParser` (method only available on the `_SubParsersAction` object, which is returned from ArgumentParser.add_subparsers()`)
* feat: queued generation and batches
Due to a very messy branch with broad addition of `isort` on `main` alongside it, some git surgery was needed to get an agreeable git history. This commit represents all of the work on queued generation. See PR for notes.
* chore: flake8, isort, black
* fix(nodes): fix incorrect service stop() method
* fix(nodes): improve names of a few variables
* fix(tests): fix up tests after changes to batches/queue
* feat(tests): add unit tests for session queue helper functions
* feat(ui): dynamic prompts is always enabled
* feat(queue): add queue_status_changed event
* feat(ui): wip queue graphs
* feat(nodes): move cleanup til after invoker startup
* feat(nodes): add cancel_by_batch_ids
* feat(ui): wip batch graphs & UI
* fix(nodes): remove `Batch.batch_id` from required
* fix(ui): cleanup and use fixedCacheKey for all mutations
* fix(ui): remove orphaned nodes from canvas graphs
* fix(nodes): fix cancel_by_batch_ids result count
* fix(ui): only show cancel batch tooltip when batches were canceled
* chore: isort
* fix(api): return `[""]` when dynamic prompts generates no prompts
Just a simple fallback so we always have a prompt.
* feat(ui): dynamicPrompts.combinatorial is always on
There seems to be little purpose in using the combinatorial generation for dynamic prompts. I've disabled it by hiding it from the UI and defaulting combinatorial to true. If we want to enable it again in the future it's straightforward to do so.
* feat: add queue_id & support logic
* feat(ui): fix upscale button
It prepends the upscale operation to queue
* feat(nodes): return queue item when enqueuing a single graph
This facilitates one-off graph async workflows in the client.
* feat(ui): move controlnet autoprocess to queue
* fix(ui): fix non-serializable DOMRect in redux state
* feat(ui): QueueTable performance tweaks
* feat(ui): update queue list
Queue items expand to show the full queue item. Just as JSON for now.
* wip threaded session_processor
* feat(nodes,ui): fully migrate queue to session_processor
* feat(nodes,ui): add processor events
* feat(ui): ui tweaks
* feat(nodes,ui): consolidate events, reduce network requests
* feat(ui): cleanup & abstract queue hooks
* feat(nodes): optimize batch permutation
Use a generator to do only as much work as is needed.
Previously, though we only ended up creating exactly as many queue items as was needed, there was still some intermediary work that calculated *all* permutations. When that number was very high, the system had a very hard time and used a lot of memory.
The logic has been refactored to use a generator. Additionally, the batch validators are optimized to return early and use less memory.
* feat(ui): add seed behaviour parameter
This dynamic prompts parameter allows the seed to be randomized per prompt or per iteration:
- Per iteration: Use the same seed for all prompts in a single dynamic prompt expansion
- Per prompt: Use a different seed for every single prompt
"Per iteration" is appropriate for exploring a the latents space with a stable starting noise, while "Per prompt" provides more variation.
* fix(ui): remove extraneous random seed nodes from linear graphs
* fix(ui): fix controlnet autoprocess not working when queue is running
* feat(queue): add timestamps to queue status updates
Also show execution time in queue list
* feat(queue): change all execution-related events to use the `queue_id` as the room, also include `queue_item_id` in InvocationQueueItem
This allows for much simpler handling of queue items.
* feat(api): deprecate sessions router
* chore(backend): tidy logging in `dependencies.py`
* fix(backend): respect `use_memory_db`
* feat(backend): add `config.log_sql` (enables sql trace logging)
* feat: add invocation cache
Supersedes #4574
The invocation cache provides simple node memoization functionality. Nodes that use the cache are memoized and not re-executed if their inputs haven't changed. Instead, the stored output is returned.
## Results
This feature provides anywhere some significant to massive performance improvement.
The improvement is most marked on large batches of generations where you only change a couple things (e.g. different seed or prompt for each iteration) and low-VRAM systems, where skipping an extraneous model load is a big deal.
## Overview
A new `invocation_cache` service is added to handle the caching. There's not much to it.
All nodes now inherit a boolean `use_cache` field from `BaseInvocation`. This is a node field and not a class attribute, because specific instances of nodes may want to opt in or out of caching.
The recently-added `invoke_internal()` method on `BaseInvocation` is used as an entrypoint for the cache logic.
To create a cache key, the invocation is first serialized using pydantic's provided `json()` method, skipping the unique `id` field. Then python's very fast builtin `hash()` is used to create an integer key. All implementations of `InvocationCacheBase` must provide a class method `create_key()` which accepts an invocation and outputs a string or integer key.
## In-Memory Implementation
An in-memory implementation is provided. In this implementation, the node outputs are stored in memory as python classes. The in-memory cache does not persist application restarts.
Max node cache size is added as `node_cache_size` under the `Generation` config category.
It defaults to 512 - this number is up for discussion, but given that these are relatively lightweight pydantic models, I think it's safe to up this even higher.
Note that the cache isn't storing the big stuff - tensors and images are store on disk, and outputs include only references to them.
## Node Definition
The default for all nodes is to use the cache. The `@invocation` decorator now accepts an optional `use_cache: bool` argument to override the default of `True`.
Non-deterministic nodes, however, should set this to `False`. Currently, all random-stuff nodes, including `dynamic_prompt`, are set to `False`.
The field name `use_cache` is now effectively a reserved field name and possibly a breaking change if any community nodes use this as a field name. In hindsight, all our reserved field names should have been prefixed with underscores or something.
## One Gotcha
Leaf nodes probably want to opt out of the cache, because if they are not cached, their outputs are not saved again.
If you run the same graph multiple times, you only end up with a single image output, because the image storage side-effects are in the `invoke()` method, which is bypassed if we have a cache hit.
## Linear UI
The linear graphs _almost_ just work, but due to the gotcha, we need to be careful about the final image-outputting node. To resolve this, a `SaveImageInvocation` node is added and used in the linear graphs.
This node is similar to `ImagePrimitive`, except it saves a copy of its input image, and has `use_cache` set to `False` by default.
This is now the leaf node in all linear graphs, and is the only node in those graphs with `use_cache == False` _and_ the only node with `is_intermedate == False`.
## Workflow Editor
All nodes now have a footer with a new `Use Cache [ ]` checkbox. It defaults to the value set by the invocation in its python definition, but can be changed by the user.
The workflow/node validation logic has been updated to migrate old workflows to use the new default values for `use_cache`. Users may still want to review the settings that have been chosen. In the event of catastrophic failure when running this migration, the default value of `True` is applied, as this is correct for most nodes.
Users should consider saving their workflows after loading them in and having them updated.
## Future Enhancements - Callback
A future enhancement would be to provide a callback to the `use_cache` flag that would be run as the node is executed to determine, based on its own internal state, if the cache should be used or not.
This would be useful for `DynamicPromptInvocation`, where the deterministic behaviour is determined by the `combinatorial: bool` field.
## Future Enhancements - Persisted Cache
Similar to how the latents storage is backed by disk, the invocation cache could be persisted to the database or disk. We'd need to be very careful about deserializing outputs, but it's perhaps worth exploring in the future.
* fix(ui): fix queue list item width
* feat(nodes): do not send the whole node on every generator progress
* feat(ui): strip out old logic related to sessions
Things like `isProcessing` are no longer relevant with queue. Removed them all & updated everything be appropriate for queue. May be a few little quirks I've missed...
* feat(ui): fix up param collapse labels
* feat(ui): click queue count to go to queue tab
* tidy(queue): update comment, query format
* feat(ui): fix progress bar when canceling
* fix(ui): fix circular dependency
* feat(nodes): bail on node caching logic if `node_cache_size == 0`
* feat(nodes): handle KeyError on node cache pop
* feat(nodes): bypass cache codepath if caches is disabled
more better no do thing
* fix(ui): reset api cache on connect/disconnect
* feat(ui): prevent enqueue when no prompts generated
* feat(ui): add queue controls to workflow editor
* feat(ui): update floating buttons & other incidental UI tweaks
* fix(ui): fix missing/incorrect translation keys
* fix(tests): add config service to mock invocation services
invoking needs access to `node_cache_size` to occur
* optionally remove pause/resume buttons from queue UI
* option to disable prepending
* chore(ui): remove unused file
* feat(queue): remove `order_id` entirely, `item_id` is now an autoinc pk
---------
Co-authored-by: Mary Hipp <maryhipp@Marys-MacBook-Air.local>
2023-09-20 05:09:24 +00:00
|
|
|
|
2022-12-01 05:33:20 +00:00
|
|
|
@staticmethod
|
2024-01-14 19:54:53 +00:00
|
|
|
def shutdown() -> None:
|
2022-12-01 05:33:20 +00:00
|
|
|
if ApiDependencies.invoker:
|
|
|
|
ApiDependencies.invoker.stop()
|