Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Start from install folders and user names the system code page cannot spell

Bowen Xue659fd3ad36fe
diff --git a/.gitignore b/.gitignore
index edad71a..72a6a09 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,6 +37,8 @@ vendor/
downloads/
prepared/
kernel-cache/
+# Dedicated compiler scratch files, also under engine in portable installations.
+tmp/
wheels/
machine.json
prepared-cache.json
diff --git a/freevideo_engine/__init__.py b/freevideo_engine/__init__.py
index 2beccf7..1d6a451 100644
--- a/freevideo_engine/__init__.py
+++ b/freevideo_engine/__init__.py
@@ -15,5 +15,7 @@ else:
_build_version = _io_path(_build_version)
from .long_paths import start_process as _start_process
_start_process()
+ from .triton_compat import own_temporary_environment as _temporary_environment
+ _temporary_environment()
if _build_version.is_file():
__version__ = _build_version.read_text(encoding='utf-8').strip()
diff --git a/freevideo_engine/background_compile.py b/freevideo_engine/background_compile.py
index 4ec6bbb..3b6b998 100644
--- a/freevideo_engine/background_compile.py
+++ b/freevideo_engine/background_compile.py
@@ -125,6 +125,8 @@ class BackgroundCompile:
row = dict(started=time.time())
self.attempts.append(row)
with io_path(log).open('ab') as stream:
+ from .triton_compat import temporary_environment
+ environment = temporary_environment(environment.get('FREEVIDEO_HOME') or self.lock.parent, environment)
process = self.process = processes.popen(
command, env=environment, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stream,
stderr=subprocess.STDOUT, start_new_session=True, supervise=True)
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py
index 37f15c7..9243ab0 100644
--- a/freevideo_engine/bootstrap.py
+++ b/freevideo_engine/bootstrap.py
@@ -23,7 +23,7 @@ from urllib.parse import unquote, urlsplit
from . import execution_paths
from .hardware import Hardware, GiB, cgroup_capacity
-from . import __version__
+from . import __version__, subprocess_output
from .policy import resource_budget
from .monitoring import save
from .install_tuning import build_parallelism, required_models, cache_compatible, wheel_key
@@ -211,7 +211,7 @@ def dependency_status(root, layout='unified', system=None):
if python.exists():
code = ('import importlib.metadata as m,json; '
'print(json.dumps({d.metadata["Name"].lower().replace("_","-"):d.version for d in m.distributions()}))')
- check = execution_paths.run([str(python), '-B', '-c', code], capture_output=True, text=True)
+ check = subprocess_output.run_python([str(python), '-B', '-c', code], capture_output=True)
if check.returncode:
row['error'] = check.stderr[-1000:]
else:
@@ -280,8 +280,8 @@ def digest(path, algorithm='sha256', git_blob=False):
def inventory(gpu=None):
smi = nvidia_smi()
query = 'index,uuid,name,compute_cap,memory.total,memory.free,driver_version,pci.bus_id'
- result = subprocess.run([smi, '--query-gpu=' + query, '--format=csv,noheader,nounits'],
- check=True, capture_output=True, text=True, timeout=20)
+ result = subprocess_output.run_external([smi, '--query-gpu=' + query, '--format=csv,noheader,nounits'],
+ check=True, capture_output=True, timeout=20)
rows = [dict(zip(query.split(','), map(str.strip, row))) for row in csv.reader(result.stdout.splitlines())]
selector = gpu if gpu is not None else os.environ.get('CUDA_VISIBLE_DEVICES', '0').split(',')[0]
matches = [r for r in rows if r['index'] == selector or r['uuid'] == selector]
@@ -1302,6 +1302,8 @@ class Installer:
from .package_progress import PackageOutput
if self.cancel.is_set():
raise RuntimeError(self.state.get('resource_guard', 'Installation cancelled.'))
+ from .triton_compat import temporary_environment
+ env = temporary_environment(self.root, env or self.env)
args, cwd = uv_file_arguments(args, cwd)
with self.state_lock:
index = len(self.state['steps'])
@@ -1529,14 +1531,14 @@ class Installer:
# and unpack another copy. Existing installations keep their own base.
if prepared.is_dir() and not any(current.glob('cpython-' + self.versions['python'] + '-*')):
env = dict(self.env, UV_PYTHON_INSTALL_DIR=str(prepared))
- found = execution_paths.run([str(uv), '--no-config', 'python', 'find', '--managed-python',
+ found = subprocess_output.run_external([str(uv), '--no-config', 'python', 'find', '--managed-python',
'--no-python-downloads', self.versions['python']],
- env=env, capture_output=True, text=True, timeout=30)
+ env=env, capture_output=True, timeout=30)
if found.returncode == 0:
candidate = Path(found.stdout.strip())
if candidate.is_file() and candidate.resolve().is_relative_to(prepared.resolve()):
- check = execution_paths.run([str(candidate), '-I', '-B', '-c',
- 'import platform; print(platform.python_version())'], capture_output=True, text=True, timeout=30)
+ check = subprocess_output.run_python([str(candidate), '-I', '-B', '-c',
+ 'import platform; print(platform.python_version())'], capture_output=True, timeout=30)
if check.returncode == 0 and check.stdout.strip() == self.versions['python']:
self.env['UV_PYTHON_INSTALL_DIR'] = str(prepared)
self.command('python-bootstrap-reuse', [candidate, '-I', '-B', '-c',
@@ -1566,10 +1568,10 @@ class Installer:
'python="cp"+str(sys.version_info.major)+str(sys.version_info.minor), '
'torch=str(torch.__version__),cuda=torch.version.cuda,cxx11_abi=torch.compiled_with_cxx11_abi(), '
'machine=platform.machine(),glibc=platform.libc_ver())))')
- identity = json.loads(subprocess.check_output([str(python), '-c', code], env=self.env, text=True))
+ identity = json.loads(subprocess_output.output_python([str(python), '-c', code], env=self.env))
identity.update(arch='.'.join(map(str, self.plan['inventory']['hardware']['capability'])),
- source=self.spec['sageattention']['commit'], compiler=subprocess.check_output(
- ['g++', '--version'], text=True).splitlines()[0])
+ source=self.spec['sageattention']['commit'], compiler=subprocess_output.output_external(
+ ['g++', '--version']).splitlines()[0])
wheel_dir = Path(self.plan['wheel_cache']) / wheel_key(identity)
manifest = wheel_dir / 'manifest.json'
record = json.loads(manifest.read_text(encoding='utf-8')) if manifest.is_file() else None
@@ -1594,7 +1596,7 @@ class Installer:
save(stamp, identity)
header_code = ('from pathlib import Path; import site; '
'print(":".join(str(p) for s in site.getsitepackages() for p in (Path(s)/"nvidia").glob("*/include")))')
- headers = subprocess.check_output([str(python), '-c', header_code], env=self.env, text=True).strip()
+ headers = subprocess_output.output_python([str(python), '-c', header_code], env=self.env).strip()
build = self.plan['build']
build_env = dict(self.env, CUDA_HOME=str(toolkit), PATH=str(toolkit / 'bin') + os.pathsep + self.env['PATH'],
CPATH=headers, TORCH_CUDA_ARCH_LIST=identity['arch'], MAX_JOBS=str(build['jobs']),
diff --git a/freevideo_engine/comfy_environment.py b/freevideo_engine/comfy_environment.py
index 34d4443..4b0ea9e 100644
--- a/freevideo_engine/comfy_environment.py
+++ b/freevideo_engine/comfy_environment.py
@@ -34,4 +34,5 @@ def isolated_environment(root, source, environ=None):
env.pop(name, None)
env.update(FREEVIDEO_HOME=str(root), FREEVIDEO_PROXY_MODE=proxy_mode, PYTHONPATH=str(source), PYTHONNOUSERSITE='1',
PYTHONUTF8='1', PYTHONIOENCODING='utf-8', NO_COLOR='1', FREEVIDEO_UI_EVENTS='1')
- return env
+ from .triton_compat import temporary_environment
+ return temporary_environment(root, env)
diff --git a/freevideo_engine/doctor.py b/freevideo_engine/doctor.py
index 2093987..ccd492b 100644
--- a/freevideo_engine/doctor.py
+++ b/freevideo_engine/doctor.py
@@ -6,12 +6,14 @@ import sys
from .hardware import detect, installed_backends
from .paths import vdn_root, base_path, checkpoint_path, comfy_root
from .locking import LOCK_ENV, runtime_lock
-from .kernel_capabilities import identity, package_versions, readiness, receipt_path
+from .kernel_capabilities import identity, package_versions, readiness, receipt_path, view_root, temp_root
from .monitoring import save
-from . import processes
+from . import processes, subprocess_output
def doctor(*, probe=False, hardware=None, backends=None):
+ from .triton_compat import own_temporary_environment
+ own_temporary_environment()
versions = package_versions()
hardware = hardware or detect()
backends = set(installed_backends() if backends is None else backends)
@@ -29,8 +31,8 @@ def doctor(*, probe=False, hardware=None, backends=None):
for backend in [*sorted(backends), *linear]:
command = [sys.executable, '-m', 'freevideo_engine.probe', backend]
try:
- child = processes.run(command, capture_output=True, text=True, timeout=180,
- env=env, pass_fds=(descriptor,))
+ child = subprocess_output.run_python(command, capture_output=True, timeout=180, env=env,
+ pass_fds=(descriptor,), runner=processes.run)
try:
row = json.loads(child.stdout.strip().splitlines()[-1])
if not isinstance(row, dict) or row.get('backend') != backend:
@@ -44,13 +46,16 @@ def doctor(*, probe=False, hardware=None, backends=None):
row['warnings'] = child.stderr[-8000:]
except subprocess.TimeoutExpired as error:
def tail(value):
- return (value.decode('utf-8', errors='replace') if isinstance(value, bytes) else value or '')[-8000:]
+ return (subprocess_output.decode_output(value, 'utf-8') or '')[-8000:]
row = {'backend': backend, 'status': 'error', 'error': 'Kernel probe exceeded 180 seconds',
'stdout_tail': tail(error.stdout), 'stderr_tail': tail(error.stderr)}
except OSError as error:
row = {'backend': backend, 'status': 'error', 'error': 'Could not start kernel probe: ' + str(error)}
result['kernel_probes'].append(row)
- result.update(readiness(result['kernel_probes']), identity=identity(hardware, versions))
+ result.update(readiness(result['kernel_probes']), identity=identity(hardware, versions),
+ view_root=view_root())
+ if temp_root():
+ result['temp_root'] = temp_root() # absent unless the installation's own temporary folder is used
result['receipt'] = str(receipt_path())
result['validation'] = 'Small kernels executed on the listed GPU; this does not validate full-video speed, quality or capacity.'
save(receipt_path(), result)
diff --git a/freevideo_engine/engine_binding.py b/freevideo_engine/engine_binding.py
index b5480b3..46fabc5 100644
--- a/freevideo_engine/engine_binding.py
+++ b/freevideo_engine/engine_binding.py
@@ -9,6 +9,7 @@ import sys
from urllib.parse import urlsplit
from urllib.request import url2pathname
+from . import subprocess_output
from .monitoring import save
from .long_paths import io_path, resolved, plain, plain_text, plain_errors
from .runtime_alias import checked_real_path
@@ -110,7 +111,7 @@ def _bind(uv, python, source, run):
command = [str(uv), 'pip', 'install', '--python', str(python), '--no-deps', '--no-build-isolation',
'--reinstall-package', 'freevideo-engine', '-e', str(source)]
try:
- result = run(command, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=180)
+ result = subprocess_output.run_external(command, stdin=subprocess.DEVNULL, capture_output=True, timeout=180, runner=run)
except (OSError, subprocess.SubprocessError) as error:
raise RuntimeError('Editable install failed for %s: %s\n%s' % (python, error, _tail(error))) from error
if result.returncode:
@@ -118,9 +119,9 @@ def _bind(uv, python, source, run):
(python, result.returncode, _tail(result)))
uv_tail = _tail(result)
try:
- result = run([str(python), '-I', '-B', '-c',
+ result = subprocess_output.run_python([str(python), '-I', '-B', '-c',
'import freevideo_engine,sys;print(freevideo_engine.__file__)'],
- stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30)
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=30, runner=run)
lines = (result.stdout or '').strip().splitlines()
imported = Path(lines[-1]) if lines else None
if (result.returncode or imported is None or not imported.is_absolute()
diff --git a/freevideo_engine/hardware.py b/freevideo_engine/hardware.py
index 22a9014..49b1e98 100644
--- a/freevideo_engine/hardware.py
+++ b/freevideo_engine/hardware.py
@@ -177,8 +177,9 @@ def detect():
import json
import subprocess
import sys
+ from . import subprocess_output
code = 'import json; from freevideo_engine.hardware import _detect_local; print(json.dumps(_detect_local().to_dict()))'
- result = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True)
+ result = subprocess_output.run_python([sys.executable, '-c', code], capture_output=True)
if result.returncode:
error = RuntimeError('Hardware detection failed: ' + result.stderr[-2000:])
# The probe imports torch; a damaged library can end it without a word
@@ -200,6 +201,7 @@ def detect():
def _detect_local():
from .system import system_memory, nvidia_smi
+ from . import subprocess_output
import subprocess
import torch
if not torch.cuda.is_available():
@@ -216,7 +218,7 @@ def _detect_local():
query = [nvidia_smi(), '--query-gpu=driver_version', '--format=csv,noheader']
if uuid:
query += ['--id=' + uuid]
- driver = subprocess.check_output(query, text=True, stderr=subprocess.DEVNULL, timeout=5).strip().splitlines()[0]
+ driver = subprocess_output.output_external(query, stderr=subprocess.DEVNULL, timeout=5).strip().splitlines()[0]
except (OSError, RuntimeError, subprocess.SubprocessError, IndexError):
pass
return Hardware(torch.cuda.get_device_name(index), torch.cuda.get_device_capability(index),
diff --git a/freevideo_engine/install.py b/freevideo_engine/install.py
index 2cd3890..73385e8 100644
--- a/freevideo_engine/install.py
+++ b/freevideo_engine/install.py
@@ -8,7 +8,7 @@ import sys
import time
from . import execution_paths
from .paths import vdn_root
-from . import network
+from . import network, subprocess_output
def install(root=None, *, packages=False):
@@ -16,8 +16,8 @@ def install(root=None, *, packages=False):
spec = dependencies['vdn']
root = (root or vdn_root()).expanduser().resolve()
network.clone(root, spec['url'], spec['commit'])
- head = execution_paths.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip()
- dirty = execution_paths.check_output(['git', 'status', '--porcelain', '--untracked-files=no'], cwd=root, text=True)
+ head = subprocess_output.output_external(['git', 'rev-parse', 'HEAD'], cwd=root).strip()
+ dirty = subprocess_output.output_external(['git', 'status', '--porcelain', '--untracked-files=no'], cwd=root)
if head != spec['commit'] or dirty:
raise RuntimeError('Existing VDN checkout does not match the clean pinned dependency; use another --vdn-root.')
diffusers = prepare_diffusers(root, dependencies)
@@ -30,8 +30,10 @@ def install(root=None, *, packages=False):
# support; avoid pip's optional PySocks dependency during bootstrap.
command = ([env['FREEVIDEO_UV'], 'pip', 'install', '--python', sys.executable]
if env.get('FREEVIDEO_UV') else [sys.executable, '-m', 'pip', 'install'])
- result = execution_paths.run([*command, '-e', str(diffusers), '--no-deps'],
- env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
+ # uv is a native program; pip runs in this interpreter's own Python.
+ run = subprocess_output.run_external if env.get('FREEVIDEO_UV') else subprocess_output.run_python
+ result = run([*command, '-e', str(diffusers), '--no-deps'],
+ env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(result.stdout, flush=True)
if result.returncode:
raise RuntimeError(result.stdout[-2500:])
@@ -56,14 +58,14 @@ def prepare_diffusers(root, dependencies):
raise RuntimeError('Expected the two pinned VDN Diffusers patches')
for path in patches:
execution_paths.run(['git', 'apply', '--index', str(path)], cwd=checkout, check=True)
- tree = execution_paths.check_output(['git', 'write-tree'], cwd=checkout, text=True).strip()
+ tree = subprocess_output.output_external(['git', 'write-tree'], cwd=checkout).strip()
if tree != spec['patched_tree']:
raise RuntimeError('Patched Diffusers source tree does not match the tested dependency')
execution_paths.run(['git', '-c', 'user.name=VDN Engine dependency setup', '-c', 'user.email=engine@localhost',
'commit', '--quiet', '-m', 'Apply pinned OpenVDN MiniMax H3 patches'], cwd=checkout, check=True)
checkout.rename(target)
- tree = execution_paths.check_output(['git', 'rev-parse', 'HEAD^{tree}'], cwd=target, text=True).strip()
- dirty = execution_paths.check_output(['git', 'status', '--porcelain', '--untracked-files=no'], cwd=target, text=True)
+ tree = subprocess_output.output_external(['git', 'rev-parse', 'HEAD^{tree}'], cwd=target).strip()
+ dirty = subprocess_output.output_external(['git', 'status', '--porcelain', '--untracked-files=no'], cwd=target)
if tree != spec['patched_tree'] or dirty:
raise RuntimeError('Existing Diffusers differs from the clean tested tree; use another VDN dependency directory.')
return target
diff --git a/freevideo_engine/kernel_capabilities.py b/freevideo_engine/kernel_capabilities.py
index 731b96a..dec6b94 100644
--- a/freevideo_engine/kernel_capabilities.py
+++ b/freevideo_engine/kernel_capabilities.py
@@ -7,6 +7,7 @@ import sys
from .hardware import installed_backends
from .paths import data_root
+from .triton_compat import temp_root
PACKAGES = ('torch', 'triton', 'triton-windows', 'diffusers', 'sageattention', 'flash-attn', 'flash-attn-4')
COMPUTE_FILES = ('attention.py', 'backends/__init__.py', 'backends/base.py', 'backends/cuda.py',
@@ -47,9 +48,23 @@ def receipt_path():
return data_root() / 'kernel-capabilities.json'
+def view_root(environ=None):
+ """The short folder this process runs the installation from; None from the installation's own."""
+ from . import launch_view
+ view = launch_view.current(environ) or launch_view.current()
+ return str(view.root) if view is not None and view.used else None
+
+
LINEAR_PROBES = ('linear', 'linear-int8')
+def needs_path_recheck(receipt, environ=None):
+ """Retry failed checks once after changing the installation or temporary view."""
+ return (not readiness(receipt['kernel_probes'])['ready']
+ and (receipt.get('view_root') != view_root(environ)
+ or receipt.get('temp_root') != temp_root(environ)))
+
+
def readiness(rows):
passed = {row['backend'] for row in rows if row.get('status') == 'complete'}
attention = sorted(passed - set(LINEAR_PROBES))
@@ -89,6 +104,10 @@ def available_backends(hardware, *, discovered=None, probe_missing=True):
"""
discovered = set(installed_backends() if discovered is None else discovered)
receipt = matching_receipt(hardware, discovered)
+ if receipt is not None and probe_missing and needs_path_recheck(receipt):
+ # They failed while the installation ran from another folder, and compilers take some
+ # paths only as that folder spells them. What passed is kept wherever it ran from.
+ receipt = None
if receipt is None:
if not probe_missing:
return discovered
diff --git a/freevideo_engine/network.py b/freevideo_engine/network.py
index 4da1905..f72c702 100644
--- a/freevideo_engine/network.py
+++ b/freevideo_engine/network.py
@@ -16,6 +16,7 @@ import re
import shutil
import subprocess
from . import execution_paths
+from . import subprocess_output
from .windows_ux import external_python, hidden_console
import threading
import time
@@ -303,7 +304,7 @@ def probe(family, name, spec, versions, timeout, env, *, measure_speed=False):
origin_proxy = execution_paths.run(['git', 'config', '--get', 'remote.origin.proxy'], env=env,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=3, **hidden_console())
if origin_proxy.returncode == 0:
- settings['remote.' + remote + '.proxy'] = origin_proxy.stdout.decode().rstrip('\r\n')
+ settings['remote.' + remote + '.proxy'] = subprocess_output.decode_output(origin_proxy.stdout).rstrip('\r\n')
elif origin_proxy.returncode != 1:
raise RuntimeError('Git proxy configuration could not be read')
git_env = proxy.git_environment(env, settings)
@@ -969,8 +970,8 @@ MIN_GIT = (2, 17)
def git_version(executable, env=None):
"""(major, minor) of a Git executable, or None when it cannot be run or read."""
try:
- output = execution_paths.run([str(executable), '--version'], env=env, stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT, text=True, timeout=30, **hidden_console()).stdout
+ output = subprocess_output.run_external([str(executable), '--version'], env=env, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, timeout=30, **hidden_console()).stdout
except (OSError, ValueError, subprocess.SubprocessError):
return None
found = re.search(r'git version (\d+)\.(\d+)', output or '')
@@ -1001,14 +1002,14 @@ def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None)
command = [git, *command[1:]]
if run:
return run(label, command, env=env)
- result = execution_paths.run(list(map(str, command)), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, **hidden_console())
+ result = subprocess_output.run_external(list(map(str, command)), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **hidden_console())
if result.returncode:
raise RuntimeError(result.stdout[-2500:])
if target.exists():
if not (target / '.git').exists():
raise ValueError('Existing dependency is not a Git checkout of the pinned source: ' + str(target))
- head = execution_paths.check_output([git, '-C', str(target), 'rev-parse', 'HEAD'], env=env, text=True, **hidden_console()).strip()
- dirty = execution_paths.check_output([git, '-C', str(target), 'status', '--porcelain', '--untracked-files=no'], env=env, text=True, **hidden_console())
+ head = subprocess_output.output_external([git, '-C', str(target), 'rev-parse', 'HEAD'], env=env, **hidden_console()).strip()
+ dirty = subprocess_output.output_external([git, '-C', str(target), 'status', '--porcelain', '--untracked-files=no'], env=env, **hidden_console())
if head != commit or dirty:
raise ValueError('Existing dependency differs from the pinned clean source: ' + str(target))
return target
@@ -1044,7 +1045,7 @@ def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None)
finally:
env = original
execute(target.name + '-checkout', ['git', '-C', temporary, 'checkout', '--detach', commit])
- actual = execution_paths.check_output([git, '-C', str(temporary), 'rev-parse', 'HEAD'], env=env, text=True, **hidden_console()).strip()
+ actual = subprocess_output.output_external([git, '-C', str(temporary), 'rev-parse', 'HEAD'], env=env, **hidden_console()).strip()
if actual != commit:
raise ValueError('Downloaded source did not match its pinned commit')
temporary.rename(target)
diff --git a/freevideo_engine/optimize.py b/freevideo_engine/optimize.py
index fd42a8b..46bc8c7 100644
--- a/freevideo_engine/optimize.py
+++ b/freevideo_engine/optimize.py
@@ -522,6 +522,8 @@ def search_plan(row, base, maximum, seconds, *, reject=None):
def run(args, machine, ui):
from .testing import environment, run_process, artifact_manifest, artifact_estimate
+ from .triton_compat import own_temporary_environment
+ own_temporary_environment(machine.get('root'))
env = environment(machine)
os.environ.update(execution_environment(env))
if args.disable:
@@ -784,6 +786,8 @@ def main(argv=None):
if not machine.get('ready'):
raise ValueError('Setup is incomplete')
from .testing import environment
+ from .triton_compat import own_temporary_environment
+ own_temporary_environment(machine.get('root'))
os.environ.update(execution_environment(environment(machine)))
with nullcontext() if args.plan else runtime_lock() as descriptor:
previous = os.environ.get(LOCK_ENV)
diff --git a/freevideo_engine/portable.py b/freevideo_engine/portable.py
index b21fa6d..f58309b 100644
--- a/freevideo_engine/portable.py
+++ b/freevideo_engine/portable.py
@@ -170,6 +170,8 @@ def own_environment(root, value):
runtime through that folder, as the environment it was started with did:
what it starts with the inherited environment imports and loads from there.
"""
+ from .triton_compat import own_temporary_environment
+ own_temporary_environment(Path(plain(root)) / 'engine')
from .execution_paths import execution_environment
return execution_environment(environment(root, value))
diff --git a/freevideo_engine/portable_launcher.py b/freevideo_engine/portable_launcher.py
index 6c2a619..71e296b 100644
--- a/freevideo_engine/portable_launcher.py
+++ b/freevideo_engine/portable_launcher.py
@@ -179,6 +179,10 @@ class PortableController(Controller):
'import sys;sys.path.insert(0,sys.argv[1]);'
'from freevideo_engine.portable import main;'
'sys.exit(main(sys.argv[2], ["--initialize"]))', str(self.source), str(self.root)]
+ # -I ignores PYTHONUTF8, so name the mode on the command line: the start
+ # process then reads and writes UTF-8 like every other FreeVideo process,
+ # whatever the system code page is.
+ command[1:1] = ['-X', 'utf8']
tail = ''
view = launch_view.view_for(self.root)
self.progress(dict(stage='verify', done=0, total=None, detail='Check local files'))
@@ -377,6 +381,8 @@ def gui(root):
def portable_session(root):
from .launcher_session import Session
root = Path(plain(resolved(root)))
+ from .triton_compat import own_temporary_environment
+ own_temporary_environment(root / 'engine')
os.environ.update(portable.environment(root, portable.manifest(root)))
os.environ['FREEVIDEO_LAUNCHER_HOME'] = str(root/'engine/launcher')
class PortableSession(Session):
diff --git a/freevideo_engine/precompile.py b/freevideo_engine/precompile.py
index f12f8a3..b9c4d4c 100644
--- a/freevideo_engine/precompile.py
+++ b/freevideo_engine/precompile.py
@@ -172,6 +172,9 @@ def run(machine, *, environment=None, timeout=TIMEOUT_SECONDS, background=False,
from .resource_history import ResourceHistory
environment = dict(os.environ if environment is None else environment)
root = Path(machine['root'])
+ from .triton_compat import own_temporary_environment, temporary_environment
+ own_temporary_environment(root)
+ environment = temporary_environment(root, environment)
receipt = dict(success=False, started=time.time(), shapes=[])
if machine.get('gpu_vendor') == 'amd':
# Not measured on AMD GPUs yet; their first request compiles as before.
@@ -281,11 +284,15 @@ def check_kernels(hardware, machine, environment, room):
In the background they run in a child this process watches like a worker
and stops when the room is needed; an interrupted check publishes no receipt.
"""
- from .kernel_capabilities import available_backends, matching_receipt
+ from .kernel_capabilities import available_backends, matching_receipt, needs_path_recheck
+ from .triton_compat import own_temporary_environment, temporary_environment
+ own_temporary_environment(machine['root'])
+ environment = temporary_environment(machine['root'], environment)
if room is None:
available_backends(hardware)
return
- if matching_receipt(hardware) is not None:
+ receipt = matching_receipt(hardware)
+ if receipt is not None and not needs_path_recheck(receipt, environment):
return
# A forced stop skips the cleanup below; an hour-old folder is no live check.
for stale in Path(tempfile.gettempdir()).glob('freevideo-kernel-checks-*'):
@@ -442,6 +449,11 @@ def watch_worker(command, env, descriptor, log, timeout, room):
from .ram import ProcessMemory
memory = ProcessMemory() if room is not None else None
checkpoint(room) # Never start a child after a stop or with the room needed.
+ from .triton_compat import temporary_environment, temp_root
+ from .system import install_root
+ managed_temp = temp_root(env)
+ root = env.get('FREEVIDEO_HOME') or (Path(managed_temp).parent if managed_temp else install_root())
+ env = temporary_environment(root, env)
with log.open('wb') as stream:
process = processes.popen(command, env=env, stdout=stream, stderr=subprocess.STDOUT,
pass_fds=(descriptor,) if descriptor is not None else (), start_new_session=True)
@@ -515,6 +527,8 @@ def main(argv=None):
try:
from .testing import environment
# A request's own variables: the installation, its caches and its GPU.
+ from .triton_compat import own_temporary_environment
+ own_temporary_environment(machine.get('root'))
os.environ.update(execution_environment(environment(machine)))
owner = os.environ.get(OWNER_ENV)
receipt = run(machine, background=args.background, owner=int(owner) if owner else None)
diff --git a/freevideo_engine/resident_process.py b/freevideo_engine/resident_process.py
index a16607c..e76366b 100644
--- a/freevideo_engine/resident_process.py
+++ b/freevideo_engine/resident_process.py
@@ -484,6 +484,8 @@ def serve(endpoint, runner, snapshot):
environment = execution_environment(request['environment'])
os.environ.clear()
os.environ.update(environment)
+ from .triton_compat import own_temporary_environment
+ own_temporary_environment()
os.environ.pop(processes.HANDLE_ENV, None)
os.environ['FREEVIDEO_RUNTIME_LOCK_FD'] = str(descriptor)
from .locking import runtime_lock
diff --git a/freevideo_engine/runtime_alias.py b/freevideo_engine/runtime_alias.py
index 02c93c7..68b4142 100644
--- a/freevideo_engine/runtime_alias.py
+++ b/freevideo_engine/runtime_alias.py
@@ -149,6 +149,10 @@ class _WinAPI:
def __init__(self):
dll = ctypes.WinDLL('kernel32', use_last_error=True)
declarations = {
+ 'GetACP': ([], _DWORD),
+ 'WideCharToMultiByte': ([_DWORD, _DWORD, ctypes.c_wchar_p, ctypes.c_int,
+ ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p,
+ ctypes.POINTER(_BOOL)], ctypes.c_int),
'CreateDirectoryW': ([ctypes.c_wchar_p, ctypes.c_void_p], _BOOL),
'CreateFileW': ([ctypes.c_wchar_p, _DWORD, _DWORD, ctypes.c_void_p,
_DWORD, _DWORD, _HANDLE], _HANDLE),
@@ -256,6 +260,22 @@ class _Backend:
except (ImportError, AttributeError, OSError, ValueError):
return False
+ def ansi_path(self, path):
+ """Whether the system code page spells this path without substitution."""
+ try:
+ api = _win_api()
+ code_page = api.GetACP()
+ if code_page == 65001:
+ return True
+ substituted = _BOOL()
+ # WC_NO_BEST_FIT_CHARS: even a similar character names a different file.
+ api.check(api.WideCharToMultiByte(code_page, 0x400, str(path), -1,
+ None, 0, None, ctypes.byref(substituted)))
+ return not substituted.value
+ except (AttributeError, OSError, ValueError, TypeError, ctypes.ArgumentError):
+ # Not knowing is no reason for a short folder: the length decides, as it did.
+ return True
+
def locations(self):
return [Path(plain(value, windows=True)) / 'FV' for key in ('ProgramData', 'LOCALAPPDATA')
if (value := os.environ.get(key)) and Path(plain(value, windows=True)).is_absolute()]
@@ -505,6 +525,11 @@ def needs_view(root, longest=None) -> bool:
return False
if os.environ.get('FREEVIDEO_RUNTIME_ALIAS') == '1':
return True
+ # The kernel compiler reads its cache folder and finds its own headers through the system's
+ # ANSI code page. A folder that code page cannot spell is one it cannot use, whatever its
+ # length; the short folder is plain letters.
+ if not _backend.ansi_path(root):
+ return True
# An installation that runs from where it is keeps doing so; only one beyond its budget is
# given the short folder.
if longest is None and system_long_paths():
diff --git a/freevideo_engine/subprocess_output.py b/freevideo_engine/subprocess_output.py
new file mode 100644
index 0000000..263f8f1
--- /dev/null
+++ b/freevideo_engine/subprocess_output.py
@@ -0,0 +1,110 @@
+"""Explicit pipe encodings for Python workers and byte capture for native tools."""
+import locale
+import os
+import subprocess
+import sys
+
+from . import execution_paths
+
+
+def python_environment(environ=None):
+ """Copy per-child settings without changing the launcher's environment."""
+ env = dict(os.environ if environ is None else environ)
+ env.update(PYTHONUTF8='1', PYTHONIOENCODING='utf-8')
+ return env
+
+
+def python_command(command):
+ command = list(command)
+ # The frozen executable has its own argument parser, not Python's. Its
+ # --freevideo-module entry configures the streams before dispatching.
+ if getattr(sys, 'frozen', False) and str(command[0]) == sys.executable:
+ return command
+ # -I/-E and Windows portable ._pth ignore PYTHON* environment settings.
+ # The command-line mode still makes redirected stdout/stderr UTF-8.
+ return [command[0], '-X', 'utf8', *command[1:]]
+
+
+def _python_options(options):
+ options = dict(options)
+ options['env'] = python_environment(options.get('env'))
+ options.pop('universal_newlines', None)
+ options.update(text=True, encoding='utf-8', errors='backslashreplace')
+ return options
+
+
+def run_python(command, *, runner=None, **options):
+ return (runner or execution_paths.run)(python_command(command), **_python_options(options))
+
+
+def output_python(command, **options):
+ return execution_paths.check_output(python_command(command), **_python_options(options))
+
+
+def decode_output(value, encoding=None):
+ """Prefer UTF-8, then the native code page; preserve undecodable bytes.
+
+ Native programs do not share Python's UTF-8 contract. In particular Git
+ and uv commonly emit UTF-8 even on legacy Windows installations. An
+ unknown byte is displayed as \\xNN, never discarded as empty output.
+ """
+ if value is None or isinstance(value, str):
+ return value
+ try:
+ text = value.decode('utf-8')
+ except UnicodeDecodeError:
+ # Support the stdlib-only diagnostic entry on older bootstrap Python,
+ # while 3.12 uses the native code page even in Python UTF-8 mode.
+ native_encoding = (locale.getencoding() if hasattr(locale, 'getencoding')
+ else locale.getpreferredencoding(False))
+ text = value.decode(encoding or native_encoding, errors='backslashreplace')
+ return text.replace('\r\n', '\n').replace('\r', '\n')
+
+
+def _byte_options(options):
+ options = dict(options)
+ encoding = options.pop('encoding', None)
+ for name in ('text', 'universal_newlines', 'errors'):
+ options.pop(name, None)
+ if isinstance(options.get('input'), str):
+ options['input'] = options['input'].encode(encoding or 'utf-8')
+ return options, encoding
+
+
+def _decode_error(error, encoding):
+ # TimeoutExpired retains partial bytes even for text-mode subprocesses.
+ error.output = decode_output(error.output, encoding)
+ error.stderr = decode_output(error.stderr, encoding)
+
+
+def run_external(command, *, runner=None, **options):
+ options, encoding = _byte_options(options)
+ check = options.pop('check', False)
+
+ def decoded(command, **options):
+ try:
+ result = (runner or subprocess.run)(command, **options)
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
+ _decode_error(error, encoding)
+ raise
+ result.stdout = decode_output(getattr(result, 'stdout', None), encoding)
+ result.stderr = decode_output(getattr(result, 'stderr', None), encoding)
+ return result
+ # Decode first: short installation paths are put back in text, not in bytes.
+ # A caller's own runner already starts its child from the short folder.
+ result = decoded(command, **options) if runner else execution_paths.call(decoded, command, **options)
+ if check:
+ result.check_returncode()
+ return result
+
+
+def output_external(command, **options):
+ options, encoding = _byte_options(options)
+
+ def decoded(command, **options):
+ try:
+ return decode_output(subprocess.check_output(command, **options), encoding)
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
+ _decode_error(error, encoding)
+ raise
+ return execution_paths.call(decoded, command, **options)
diff --git a/freevideo_engine/triton_compat.py b/freevideo_engine/triton_compat.py
index ea15755..e07160a 100644
--- a/freevideo_engine/triton_compat.py
+++ b/freevideo_engine/triton_compat.py
@@ -4,6 +4,132 @@ import os
from pathlib import Path
+TEMP_KEYS = ('TMPDIR', 'TEMP', 'TMP')
+TEMP_ROOT_ENV = 'FREEVIDEO_COMPILER_TEMP_ROOT'
+
+
+def temp_root(environ=None):
+ """The managed compiler temporary folder, or None for caller/system folders."""
+ from . import runtime_alias
+ if not runtime_alias._backend.windows():
+ return None
+ env = os.environ if environ is None else environ
+ root = env.get(TEMP_ROOT_ENV)
+ return root if root and all(env.get(key) == root for key in TEMP_KEYS) else None
+
+
+def _writable_temporary(path):
+ import tempfile
+ from .long_paths import io_path
+ # dir= avoids consulting or caching the parent's default temporary folder.
+ with tempfile.TemporaryFile(prefix='freevideo-temp-check-', dir=io_path(path)) as stream:
+ stream.write(b'ok')
+ stream.flush()
+
+
+def _usable_folder(path):
+ # Nothing is created or written to a folder that is only being looked at.
+ return os.path.isdir(path) and os.access(path, os.W_OK)
+
+
+def _unsafe_temporary(environ):
+ from . import runtime_alias
+ explicit = [os.path.abspath(environ[key]) for key in TEMP_KEYS if environ.get(key)]
+ # Native compilers can prefer TMP over TEMP, unlike Python's TMPDIR first.
+ if any(not runtime_alias._backend.ansi_path(path) for path in explicit):
+ return True
+ for path in explicit:
+ if _usable_folder(path):
+ return False # a folder that is there and writable stays exactly as it is
+ # Python's Windows fallbacks, after unusable or missing explicit choices.
+ profile = environ.get('USERPROFILE') or os.path.expanduser('~')
+ candidates = [os.path.join(profile, 'AppData', 'Local', 'Temp'),
+ os.path.join(environ.get('SYSTEMROOT', r'C:\Windows'), 'Temp'),
+ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp', os.curdir]
+ for path in candidates:
+ path = os.path.abspath(path)
+ if not runtime_alias._backend.ansi_path(path):
+ return True
+ if _usable_folder(path):
+ return False
+ return False
+
+
+def _clean_temporary(path):
+ """Remove day-old children of this dedicated folder, without following links."""
+ import shutil
+ import time
+ cutoff = time.time() - 86400
+ for child in path.iterdir():
+ try:
+ if child.lstat().st_mtime >= cutoff:
+ continue
+ if child.is_symlink():
+ child.unlink()
+ elif child.is_junction():
+ child.rmdir()
+ elif child.is_dir():
+ shutil.rmtree(child)
+ else:
+ child.unlink()
+ except OSError:
+ pass # A compiler may still hold it; try again on the next start.
+
+
+def temporary_environment(root, environ):
+ """Keep spellable temporary choices; otherwise use this installation's tmp."""
+ import logging
+ from . import launch_view, runtime_alias
+ from .long_paths import io_path, path_chars, plain
+ if not runtime_alias._backend.windows():
+ return environ
+ try:
+ # A spellable folder that is there stays as it is, whoever chose it (also another installation's);
+ # a managed one that has been removed is made again, for compilers that read TMP directly.
+ managed = temp_root(environ)
+ if not _unsafe_temporary(environ) and not (managed and not os.path.isdir(managed)):
+ return environ
+ # Keep the lexical short spelling: resolve() would undo the junction.
+ root = Path(os.path.abspath(plain(root)))
+ view = launch_view.current(environ) or launch_view.current() or launch_view.for_engine(root)
+ temporary = Path(launch_view.value(root, view)) / 'tmp'
+ if not runtime_alias._backend.ansi_path(temporary):
+ raise OSError('installation temporary path cannot be represented by the system code page')
+ if path_chars(temporary) > 200:
+ raise OSError('installation temporary path exceeds 200 characters')
+ folder = io_path(temporary)
+ folder.mkdir(parents=True, exist_ok=True)
+ if folder.is_symlink() or folder.is_junction():
+ raise OSError('installation temporary folder is a link')
+ _writable_temporary(temporary)
+ _clean_temporary(folder)
+ return dict(environ, **{key: str(temporary) for key in (*TEMP_KEYS, TEMP_ROOT_ENV)})
+ except Exception as error: # A temporary folder choice never blocks the engine from starting.
+ logging.warning('[FreeVideo] Compiler temporary folder unchanged: %s',
+ str(error).replace('\r', ' ').replace('\n', ' '))
+ return environ
+
+
+def own_temporary_environment(root=None):
+ """Apply before third-party imports and invalidate an already cached tempdir."""
+ from . import runtime_alias
+ if not runtime_alias._backend.windows():
+ return
+ import logging
+ import tempfile
+ try:
+ from .system import install_root
+ env = temporary_environment(root if root is not None else install_root(), os.environ)
+ if env is not os.environ:
+ os.environ.update(env)
+ tempfile.tempdir = None
+ elif tempfile.tempdir and not runtime_alias._backend.ansi_path(tempfile.tempdir):
+ tempfile.tempdir = None # a cached folder the system code page cannot spell is looked up again
+ except Exception as error: # A temporary folder choice never blocks the engine from starting.
+ logging.warning('[FreeVideo] Compiler temporary folder unchanged: %s',
+ str(error).replace('\r', ' ').replace('\n', ' '))
+
+
COMPILER_ENVIRONMENT_KEYS = (
'TRITON_CACHE_DIR', 'TORCHINDUCTOR_CACHE_DIR', 'CUDA_CACHE_PATH',
'CUDA_CACHE_MAXSIZE', 'TORCHINDUCTOR_USE_STATIC_CUDA_LAUNCHER',
@@ -42,7 +168,7 @@ def _same_path(first, second):
def environment(root, environ):
"""Configure child compilers before imports, including encoder prewarming."""
- env = dict(environ)
+ env = dict(temporary_environment(root, environ))
cache = Path(root) / 'kernel-cache'
for key, folder in (('TRITON_CACHE_DIR', 'triton'),
('TORCHINDUCTOR_CACHE_DIR', 'inductor'),
diff --git a/freevideo_engine/tuning.py b/freevideo_engine/tuning.py
index f989186..f4b0533 100644
--- a/freevideo_engine/tuning.py
+++ b/freevideo_engine/tuning.py
@@ -13,7 +13,7 @@ import sys
import time
from urllib.parse import unquote, urlsplit
-from . import execution_paths
+from . import subprocess_output
from .hardware import GiB
from .policy import BLOCK_BYTES
from .monitoring import save
@@ -57,7 +57,7 @@ def state_path():
def package_versions(python=None):
if python and os.path.abspath(python) != os.path.abspath(sys.executable):
code = 'import importlib.metadata as m,json; print(json.dumps({d.metadata["Name"].lower().replace("_","-"):d.version for d in m.distributions()}))'
- result = execution_paths.run([str(python), '-B', '-c', code], capture_output=True, text=True, timeout=15, check=True)
+ result = subprocess_output.run_python([str(python), '-B', '-c', code], capture_output=True, timeout=15, check=True)
installed = json.loads(result.stdout)
else:
installed = {d.metadata['Name'].lower().replace('_', '-'): d.version for d in importlib.metadata.distributions()}
@@ -103,8 +103,8 @@ def identity(machine, hardware):
for checkout, ref, expected in ((machine['vdn_root'], 'HEAD', specs['vdn']['commit']),
(machine['comfy_root'], 'HEAD', specs['encoder']['comfy_commit']),
(str(Path(machine['vdn_root']) / 'diffusers'), 'HEAD^{tree}', specs['diffusers']['patched_tree'])):
- observed_ref = execution_paths.check_output(['git', '-C', checkout, 'rev-parse', ref], text=True, timeout=10).strip()
- dirty = execution_paths.check_output(['git', '-C', checkout, 'status', '--porcelain', '--untracked-files=no'], text=True, timeout=10)
+ observed_ref = subprocess_output.output_external(['git', '-C', checkout, 'rev-parse', ref], timeout=10).strip()
+ dirty = subprocess_output.output_external(['git', '-C', checkout, 'status', '--porcelain', '--untracked-files=no'], timeout=10)
if observed_ref != expected or dirty:
raise ValueError('Pinned model code changed; saved tuning cannot be reused: ' + checkout)
return {'schema': SCHEMA, 'system': hardware.system,