Skip to content
Merged
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
12 changes: 8 additions & 4 deletions freevideo_engine/comfy_launcher_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1447,19 +1447,22 @@ def _open_access_proxy(self):
self.state = dict(self.state, selection=dict(self.selection))
self.refresh_access_links()

def _stop_without_cuda_devices(self, command, env, directory, context):
def _stop_without_cuda_devices(self, command, env, directory, context, source=None):
"""Stop before ComfyUI starts when the CUDA driver is there and shows no device.
ComfyUI would import Torch and quit on the same fact ("No CUDA GPUs are available") before it
loads any node, and the launcher could only report that it quit. The count is read in a child
with the environment ComfyUI gets, so a CUDA_VISIBLE_DEVICES that hides every card counts too.
A machine without the CUDA driver library (AMD, Intel, Mac), a read that fails, a CPU-only
control process and a started device executor all go on as before.
The child is ComfyUI's own Python (command[0]) with the installed engine (source): the packaged
Windows launcher cannot run a module itself.
"""
if sys.platform == 'darwin' or '--cpu' in command or env.get('FREEVIDEO_EXECUTOR_DEVICE'):
return
from . import cuda_inventory
found = cuda_inventory.count_devices(env)
child = dict(python=command[0], source=source) if source is not None else {}
found = cuda_inventory.count_devices(env, **child)
visible = env.get('CUDA_VISIBLE_DEVICES')
if found is not None:
cuda_inventory.remember(found, visible)
Expand All @@ -1469,7 +1472,7 @@ def _stop_without_cuda_devices(self, command, env, directory, context):
cuda_inventory.report_line(found, visible)]
if visible is not None:
# Only the variable is the cause when the driver shows a card without it: the card says so then.
free = cuda_inventory.count_devices({name: value for name, value in env.items() if name != 'CUDA_VISIBLE_DEVICES'})
free = cuda_inventory.count_devices({name: value for name, value in env.items() if name != 'CUDA_VISIBLE_DEVICES'}, **child)
if free and free.get('library') is True and free.get('init') == 0 and (free.get('count') or 0) > 0:
lines.append('CUDA devices without CUDA_VISIBLE_DEVICES: %d' % free['count'])
card = cuda_inventory.named_card()
Expand Down Expand Up @@ -1650,7 +1653,8 @@ def _connect_comfy(self):
env = launch_view.environment_view(env, view)
from .windows_ux import external_python
if managed:
self._stop_without_cuda_devices(command, env, directory, context)
self._stop_without_cuda_devices(command, env, directory, context,
source=launch_view.value(selected['source'], view) if view.used else selected['source'])
with self._server_lock, external_python(), io_path(self.server_log).open('wb') as log:
if self._closed or self.cancelled.is_set():
raise RuntimeError('ComfyUI startup cancelled')
Expand Down
11 changes: 9 additions & 2 deletions freevideo_engine/cuda_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@


def probe(selector=None):
if processes.frozen_windows():
# Started here, FreeVideo.exe would open its own extraction again rather than run this module.
raise RuntimeError('the CUDA reading runs in the installed Python, not in the packaged launcher')
env = dict(os.environ)
# Enumerate physical devices, then select by stable UUID in the worker too.
env.pop('CUDA_VISIBLE_DEVICES', None)
Expand All @@ -35,15 +38,19 @@ def probe(selector=None):
return json.loads(result.stdout)


def count_devices(env=None, timeout=15):
def count_devices(env=None, timeout=15, *, python=None, source=None):
"""What the CUDA driver says about this process's devices, read in a child that exits again.
Returns dict(library, init, count) or None when it could not be read. `library` is False when
the machine has no CUDA driver library (AMD, Intel, no driver); nothing is claimed then. The child
sees `env` as it is, CUDA_VISIBLE_DEVICES included, so the count is the one Torch would get.
python and source run it in ComfyUI's own Python with the installed engine; without them the packaged
Windows launcher reads nothing (see processes.frozen_windows).
"""
if python is None and processes.frozen_windows():
return None
try:
result = subprocess_output.run_python(processes.module_command(__name__, '--count'),
result = subprocess_output.run_python(processes.module_command(__name__, '--count', python=python, source=source),
env=env, capture_output=True, timeout=timeout)
value = json.loads(result.stdout.strip().splitlines()[-1])
if result.returncode or not isinstance(value, dict):
Expand Down
34 changes: 34 additions & 0 deletions freevideo_engine/frozen_checks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""What the packaged launcher's own smoke test checks about starting itself.
In the packaged Windows launcher sys.executable is FreeVideo.exe. A child it starts with its environment shares its
PyInstaller extraction and runs the startup hooks again instead of running Python. self_start() reads, inside the real
packaged process: the CUDA count must start no child there, and the onefile hook that restores data aliases must run a
second time in this extraction, as such a child would, without failing.
"""
import os
from pathlib import Path
import sys


def self_start():
from . import cuda_inventory, subprocess_output
calls, run = [], subprocess_output.run_python

def counted(*args, **kwargs):
calls.append(args[0] if args else kwargs.get('command'))
return run(*args, **kwargs)
subprocess_output.run_python = counted
try:
found = cuda_inventory.count_devices(dict(os.environ))
finally:
subprocess_output.run_python = run
result = dict(count=found, count_children=len(calls))
bundle = getattr(sys, '_MEIPASS', None)
if bundle and (Path(bundle) / '_freevideo-data-links.json').is_file():
import runpy
hook = runpy.run_path(str(Path(bundle) / 'engine-source' / 'scripts' / 'pyi_rth_bundle_data.py'), run_name='freevideo_hook_again')
hook['restore_data_links'](bundle)
result['hook_again'] = 'ok'
else:
result['hook_again'] = 'no onefile extraction'
return result
3 changes: 3 additions & 0 deletions freevideo_engine/modern_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,9 @@ def smoke_test(app, engine, window, bridge, destination):
build = current_build()
if getattr(sys, 'frozen', False) and build is None:
raise ValueError('Packaged launcher update identity is missing')
if getattr(sys, 'frozen', False) and os.name == 'nt':
from .frozen_checks import self_start
payload['self_start'] = self_start()
events = queue.Queue()
runner = LauncherRunner(session.source, events, destination / 'help')
runner.start('help', destination / 'engine', ['--help'])
Expand Down
18 changes: 15 additions & 3 deletions freevideo_engine/processes.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,26 @@ def descriptors():
return () if descriptor is None else (descriptor,)


def module_command(module, *arguments):
"""Also works with portable Windows Python, whose ._pth ignores PYTHONPATH."""
if getattr(sys, 'frozen', False) and sys.platform.startswith('linux'):
def frozen_windows():
"""The packaged Windows launcher: sys.executable is FreeVideo.exe, which has no Python command line. A child it
starts with its own environment joins its PyInstaller extraction instead of running Python."""
return bool(getattr(sys, 'frozen', False)) and os.name == 'nt'


def module_command(module, *arguments, python=None, source=None):
"""Also works with portable Windows Python, whose ._pth ignores PYTHONPATH.
python and source name another interpreter and the folder holding freevideo_engine, as the packaged Windows
launcher needs: it cannot run a module itself (frozen_windows)."""
if python is None and getattr(sys, 'frozen', False) and sys.platform.startswith('linux'):
# The Linux launcher (AppImage) runs its own helpers; see modern_launcher.main.
return [sys.executable, '--freevideo-module', module, *map(str, arguments)]
from .installed_entry import INSTALLED_ONLY
code = (INSTALLED_ONLY + "import runpy;sys.path.insert(0,sys.argv.pop(1));"
"runpy.run_module(sys.argv.pop(1),run_name='__main__',alter_sys=True)")
if python is not None:
return [str(python), '-B', '-X', 'utf8', '-c', code, str(source or Path(__file__).resolve().parents[1]), module,
*map(str, arguments)]
source = Path(__file__).resolve().parents[1]
view = launch_view.current()
if view is not None:
Expand Down
Loading
Loading