From 652cd4520757e1ef71a1dd8816fec41223ee246b Mon Sep 17 00:00:00 2001 From: Carter Francis Date: Thu, 19 Nov 2026 16:14:13 -0600 Subject: [PATCH 1/5] Install torch per machine for an app that leaves it out of its lock An app can leave torch out of uv.lock ([tool.uv] exclude-dependencies, recorded as [manifest] excludes) so each machine gets the build for its GPU. Setup only handled a locked torch: otherwise it ran an exact uv sync, which installed no torch on a first run and removed one installed by hand on every upgrade, and the backend died on import. Setup now reads the exclusion from the lock and, on every platform, syncs inexactly (an installed torch survives, nothing re-downloads), installs the app, then probes the env's torch: kept when it loads and has kernels for the GPU, installed with --torch-backend=auto when missing, reinstalled when it does not load, upgraded when it has no kernels for the GPU (2.6.0+cu124 on sm_120). A failed install is said in the overlay, not thrown: the backend starts, and the stamp is dropped so the next launch retries. From a wheelhouse torch comes from the folder or not at all. installTorchPerMachine works without a pin and takes reinstall/upgrade for a Fix button. A locked torch is unchanged. Claude-Session: https://claude.ai/code/session_01DzXsKAUJSM4XYpqqzrcuV5 --- README.md | 19 + de_shell/js/main/envProgress.ts | 5 + de_shell/js/main/envSetup.ts | 4 +- de_shell/js/main/index.ts | 4 +- de_shell/js/main/pythonEnv.test.ts | 269 ++++++++++++++ de_shell/js/main/pythonEnv.ts | 330 ++++++++++++++++-- .../+torch-per-machine.bugfix.rst | 1 + .../+torch-per-machine.new_feature.rst | 1 + 8 files changed, 607 insertions(+), 26 deletions(-) create mode 100644 upcoming_changes/+torch-per-machine.bugfix.rst create mode 100644 upcoming_changes/+torch-per-machine.new_feature.rst diff --git a/README.md b/README.md index 46ed543..dd19ba0 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,25 @@ needs lives in `shell/packaging/`. installed when `nvidia-smi` finds a device. `_GPU=0|1` overrides the probe either way. +**torch.** A lock holds one torch build, and which build a machine needs +depends on its GPU. There are two ways to ship it: + +* *Locked* (SpyDE): the lock pins torch. On Windows and Linux, setup syncs + everything else, then installs that release with `--torch-backend=auto`. +* *Per machine* (Autopilot): leave torch out of the lock with + `[tool.uv] exclude-dependencies = ["torch"]`, which uv records in `uv.lock`. + Setup syncs with `--inexact`, so a torch already installed survives an + upgrade. It then installs the newest torch the app's specifier allows, built + for this machine, but only when torch is missing, does not load, or has no + kernels for the GPU. A failed install is reported in the setup overlay, the + app starts without torch, and the next launch tries again. From a + wheelhouse, torch comes from the wheelhouse folder or not at all: the + wheelhouse builder works from the lock, so a site that needs torch offline + adds the torch wheels to the folder itself. + +A "Fix PyTorch" button calls `installTorchPerMachine` with `{ reinstall: true }` +for a locked torch, or `{ upgrade: true }` per machine. + **Offline sites.** Unzip the release's wheelhouse into the install folder (next to the app's `.exe`) or into `userData/wheelhouse`, or let the user choose it with "Install from a folder…" when the online install fails. The first launch then installs with no network: diff --git a/de_shell/js/main/envProgress.ts b/de_shell/js/main/envProgress.ts index 8b7d3a9..1a4451f 100644 --- a/de_shell/js/main/envProgress.ts +++ b/de_shell/js/main/envProgress.ts @@ -61,6 +61,11 @@ export function parseUvLine(raw: string): EnvProgressEvent | null { if (/two-step|full locked|uv sync|deferred/i.test(msg)) { return { phase: 'resolving', step: 'Preparing the analysis environment', percent: null } } + // A torch line that is not the install itself (checking, keeping, why it + // failed) is news for the operator: show it as written. + if (/torch/i.test(msg) && !/^installing\b|install complete/i.test(msg)) { + return { phase: 'torch', step: capitalize(msg), percent: null } + } if (/torch/i.test(msg)) { return { phase: 'torch', step: 'Installing PyTorch for your GPU', percent: null } } diff --git a/de_shell/js/main/envSetup.ts b/de_shell/js/main/envSetup.ts index 38856d3..21c40f2 100644 --- a/de_shell/js/main/envSetup.ts +++ b/de_shell/js/main/envSetup.ts @@ -20,7 +20,7 @@ import { app, dialog, ipcMain } from 'electron' import { channel, shellConfig } from './config' import { runEnvSetupMachine } from './envSetupMachine' import type { EnvSetupAnswer } from './envSetupMachine' -import { readLockedTorchVersion, resolvePythonEnv } from './pythonEnv' +import { readTorchSetup, resolvePythonEnv } from './pythonEnv' import type { EnsureOptions, ResolvedPython } from './pythonEnv' import type { ShellWindow } from './window' @@ -58,7 +58,7 @@ export function runEnvSetup( listenForAnswers() return runEnvSetupMachine({ initialWheelhouse: opts.wheelhouse ?? null, - torch: readLockedTorchVersion(join(opts.resourcesPath, 'python')) !== null, + torch: readTorchSetup(join(opts.resourcesPath, 'python')).kind !== 'none', run: (wheelhouse, onProgress) => resolvePythonEnv({ ...opts, wheelhouse, diff --git a/de_shell/js/main/index.ts b/de_shell/js/main/index.ts index b27f12c..3dd6c02 100644 --- a/de_shell/js/main/index.ts +++ b/de_shell/js/main/index.ts @@ -43,10 +43,12 @@ export type { BackendHandlers } from './backendProcess' export { resolvePythonEnv, managedEnvPaths, venvPython, readLockedTorchVersion, installTorchPerMachine, hasNvidiaGpu, readWheelhouse, findWheelhouse, - wheelhouseCandidates, lockStamp, buildSyncArgs, offlinePlan, + wheelhouseCandidates, lockStamp, buildSyncArgs, offlinePlan, readTorchSetup, + torchInstallArgs, probeTorch, ensureTorchPerMachine, } from './pythonEnv' export type { ResolvedPython, EnsureOptions, WheelhouseManifest, CommandRunner, OfflinePlan, + TorchSetup, TorchStatus, UvCall, } from './pythonEnv' export { parseUvLine } from './envProgress' diff --git a/de_shell/js/main/pythonEnv.test.ts b/de_shell/js/main/pythonEnv.test.ts index 67d038b..e311933 100644 --- a/de_shell/js/main/pythonEnv.test.ts +++ b/de_shell/js/main/pythonEnv.test.ts @@ -32,6 +32,10 @@ import { gpuEnvOverride, platformMatches, fileUrl, checkWheelhouseExtras, venvPython, clearBrokenEnv, withoutPythonDownloadLines, uvNetworkEnv, } from './pythonEnv.ts' +import { + readTorchSetup, torchInstallArgs, probeTorch, ensureTorchPerMachine, recordEnvStamp, +} from './pythonEnv.ts' +import type { CommandRunner } from './pythonEnv.ts' configureShell({ appId: 'testapp', @@ -331,6 +335,271 @@ test('checkWheelhouseExtras names the missing extra', () => { checkWheelhouseExtras(['gpu'], goodManifest) }) +// ── torch: locked, or installed per machine ───────────────────────────────── + +/** A lock that pins torch, as SpyDE's does: the cu124 entry and the PyPI one. */ +const LOCK_PINS_TORCH = `version = 1 + +[[package]] +name = "torch" +version = "2.6.0+cu124" +source = { registry = "https://download.pytorch.org/whl/cu124" } + +[[package]] +name = "torch" +version = "2.6.0" +source = { registry = "https://pypi.org/simple" } +` + +/** A lock written with `[tool.uv] exclude-dependencies = ["torch"]` (uv 0.10). */ +const LOCK_EXCLUDES_TORCH = `version = 1 +revision = 3 +requires-python = ">=3.13" + +[options] +prerelease-mode = "allow" + +[manifest] +excludes = ["torch"] + +[[package]] +name = "testapp" +version = "0.1.0" +source = { editable = "." } +dependencies = [ + { name = "six" }, +] + +[package.metadata] +requires-dist = [ + { name = "pytest", marker = "extra == 'tests'" }, + { name = "six" }, + { name = "torch", marker = "extra == 'cuda'", specifier = ">=9" }, + { name = "torch", specifier = ">=2.4,<3" }, +] +` + +function projectWithLock(lock: string): string { + const dir = tempDir('project-') + writeFileSync(join(dir, 'uv.lock'), lock) + return dir +} + +test('readTorchSetup: a lock that pins torch is the locked two-step', () => { + assert.deepEqual(readTorchSetup(projectWithLock(LOCK_PINS_TORCH)), + { kind: 'locked', version: '2.6.0' }) +}) + +test('readTorchSetup: a lock that excludes torch installs it per machine, with its specifier', () => { + assert.deepEqual(readTorchSetup(projectWithLock(LOCK_EXCLUDES_TORCH)), + { kind: 'per-machine', requirement: 'torch>=2.4,<3' }) +}) + +test('readTorchSetup: a bare torch dependency, and a multi-line excludes list', () => { + const lock = LOCK_EXCLUDES_TORCH + .replace('excludes = ["torch"]', 'excludes = [\n "numpy",\n "torch",\n]') + .replace('{ name = "torch", specifier = ">=2.4,<3" }', '{ name = "torch" }') + assert.deepEqual(readTorchSetup(projectWithLock(lock)), + { kind: 'per-machine', requirement: 'torch' }) +}) + +test('readTorchSetup: no torch, another exclusion, or no lock at all is none', () => { + assert.deepEqual(readTorchSetup(projectWithLock('version = 1\n')), { kind: 'none' }) + assert.deepEqual( + readTorchSetup(projectWithLock(LOCK_EXCLUDES_TORCH.replace('["torch"]', '["numpy"]'))), + { kind: 'none' }) + // `excludes` outside [manifest] is not uv's exclusion list. + assert.deepEqual( + readTorchSetup(projectWithLock('version = 1\n\n[options]\nexcludes = ["torch"]\n')), + { kind: 'none' }) + assert.deepEqual(readTorchSetup(emptyDir()), { kind: 'none' }) +}) + +test('buildSyncArgs syncs inexactly on request, so a per-machine torch survives', () => { + assert.deepEqual(buildSyncArgs(['--no-install-project'], [], [], true), + ['sync', '--frozen', '--no-dev', '--inexact', '--no-install-project']) + assert.ok(!buildSyncArgs([], []).includes('--inexact')) +}) + +test('torchInstallArgs keeps the locked pin unchanged', () => { + assert.deepEqual(torchInstallArgs({ kind: 'locked', version: '2.6.0' }, 'py'), + ['pip', 'install', 'torch==2.6.0', '--torch-backend=auto', '--python', 'py']) +}) + +test('torchInstallArgs: per machine, no pin — the backend picks the build, the app config stays out', () => { + const args = torchInstallArgs({ kind: 'per-machine', requirement: 'torch' }, 'py') + assert.deepEqual(args, + ['pip', 'install', '--no-config', 'torch', '--torch-backend=auto', '--python', 'py']) + assert.ok(!args!.some((a) => a.startsWith('torch=='))) +}) + +test('torchInstallArgs: reinstall replaces a damaged torch, upgrade a build without kernels', () => { + const args = torchInstallArgs({ kind: 'per-machine', requirement: 'torch' }, 'py', { reinstall: true }) + assert.equal(args![args!.indexOf('--reinstall-package') + 1], 'torch') + const upgrade = torchInstallArgs({ kind: 'per-machine', requirement: 'torch' }, 'py', { upgrade: true }) + assert.equal(upgrade![upgrade!.indexOf('--upgrade-package') + 1], 'torch') + assert.ok(!upgrade!.includes('--reinstall-package')) + const locked = torchInstallArgs({ kind: 'locked', version: '2.6.0' }, 'py', { reinstall: true }) + assert.ok(locked!.includes('--reinstall-package')) +}) + +test('torchInstallArgs: from a wheelhouse, offline from the folder and no backend probe', () => { + const args = torchInstallArgs({ kind: 'per-machine', requirement: 'torch' }, 'py', { wheelhouse: '/wh' })! + for (const flag of ['--offline', '--no-index', '--no-config']) assert.ok(args.includes(flag), flag) + assert.equal(args[args.indexOf('--find-links') + 1], '/wh') + assert.ok(!args.includes('--torch-backend=auto')) +}) + +test('torchInstallArgs is null for an app with no torch', () => { + assert.equal(torchInstallArgs({ kind: 'none' }, 'py'), null) +}) + +/** A probe runner answering with each code in turn (stdout `out`), recording its calls. */ +function probes(...answers: Array<[number | null, string?]>): CommandRunner & { calls: string[][] } { + const calls: string[][] = [] + const run = async (cmd: string, args: string[]) => { + calls.push([cmd, ...args]) + const [code, out] = answers.shift() ?? [0, '2.9.1'] + return { code, stdout: out ?? '' } + } + return Object.assign(run, { calls }) +} + +test('probeTorch reads the probe exit code, isolated from PYTHONPATH', async () => { + const run = probes([0, '2.9.1+cu128\n'], [3], [4, 'OSError: [WinError 126] c10.dll\n'], + [5, '2.6.0+cu124\nNVIDIA GeForce RTX 5090\n'], [null], [1]) + assert.deepEqual(await probeTorch('py', run), { state: 'usable', version: '2.9.1+cu128' }) + assert.deepEqual(await probeTorch('py', run), { state: 'missing' }) + assert.deepEqual(await probeTorch('py', run), + { state: 'broken', detail: 'OSError: [WinError 126] c10.dll' }) + assert.deepEqual(await probeTorch('py', run), + { state: 'no-kernels', version: '2.6.0+cu124', device: 'NVIDIA GeForce RTX 5090' }) + assert.deepEqual(await probeTorch('py', run), { state: 'unknown' }) // timed out + assert.deepEqual(await probeTorch('py', run), { state: 'unknown' }) // Python itself failed + assert.deepEqual(run.calls[0].slice(0, 3), ['py', '-I', '-c']) + assert.deepEqual(await probeTorch('py', async () => { throw new Error('ENOENT') }), + { state: 'unknown' }) +}) + +/** ensureTorchPerMachine with fakes: the uv calls it made and what it narrated. */ +async function ensure( + probe: CommandRunner, + o: { uvFails?: boolean; wheelhouse?: boolean } = {}, +): Promise<{ + ready: boolean; uv: string[][]; env: Array | undefined>; said: string +}> { + const uv: string[][] = [] + const env: Array | undefined> = [] + const said: string[] = [] + const ready = await ensureTorchPerMachine({ + requirement: 'torch', + pythonExe: 'py', + wheelhouse: o.wheelhouse ? { dir: '/wh', env: { UV_OFFLINE: '1' } } : null, + uv: async (args, _progress, extraEnv) => { + uv.push(args) + env.push(extraEnv) + if (o.uvFails) throw new Error('uv pip exited with code 1') + }, + onProgress: (line) => said.push(line), + probe, + }) + return { ready, uv, env, said: said.join('') } +} + +test('ensureTorchPerMachine keeps a usable torch: an upgrade downloads nothing', async () => { + const r = await ensure(probes([0, '2.9.1+cu128'])) + assert.equal(r.ready, true) + assert.deepEqual(r.uv, []) + assert.match(r.said, /keeping the installed PyTorch 2\.9\.1\+cu128/) +}) + +test('ensureTorchPerMachine installs a missing torch for this machine', async () => { + const r = await ensure(probes([3], [0, '2.9.1+cu128'])) + assert.equal(r.ready, true) + assert.deepEqual(r.uv, + [['pip', 'install', '--no-config', 'torch', '--torch-backend=auto', '--python', 'py']]) + assert.match(r.said, /installing torch for this machine with --torch-backend=auto/) +}) + +test('ensureTorchPerMachine reinstalls a torch that does not load', async () => { + const r = await ensure(probes([4, 'ImportError: x'], [0, '2.9.1+cu128'])) + assert.equal(r.ready, true) + assert.ok(r.uv[0].includes('--reinstall-package')) + assert.match(r.said, /does not load \(ImportError: x\)/) +}) + +test('ensureTorchPerMachine upgrades a torch with no kernels for this GPU (the sm_120 case)', async () => { + const r = await ensure(probes([5, '2.6.0+cu124\nNVIDIA GeForce RTX 5090'], [0, '2.11.0+cu128'])) + assert.equal(r.ready, true) + assert.ok(r.uv[0].includes('--upgrade-package')) + assert.ok(!r.uv[0].includes('--reinstall-package')) + assert.match(r.said, /2\.6\.0\+cu124 has no kernels for NVIDIA GeForce RTX 5090/) +}) + +test('ensureTorchPerMachine leaves a torch it could not check alone', async () => { + const r = await ensure(probes([null])) + assert.equal(r.ready, true) + assert.deepEqual(r.uv, []) +}) + +test('a failed torch install is said, not thrown, and reports torch not ready', async () => { + const r = await ensure(probes([3]), { uvFails: true }) + assert.equal(r.ready, false) + assert.match(r.said, + /PyTorch could not be installed \(uv pip exited with code 1\)\. Test App will start without it/) +}) + +test('a torch still missing or broken after the install is not ready', async () => { + assert.equal((await ensure(probes([3], [3]))).ready, false) + assert.equal((await ensure(probes([3], [4, 'ImportError: x']))).ready, false) +}) + +test('a build without kernels for this GPU after the install is kept, and says why', async () => { + // A card the newer builds dropped (Pascal on cu128): retrying would not help. + const r = await ensure(probes([3], [5, '2.11.0+cu128\nNVIDIA TITAN X (Pascal)'])) + assert.equal(r.ready, true) + assert.match(r.said, /PyTorch 2\.11\.0\+cu128 has no kernels for NVIDIA TITAN X \(Pascal\)/) + assert.match(r.said, /it will run on the CPU/) +}) + +test('from a wheelhouse, torch comes from the folder or not at all, and says so', async () => { + const ok = await ensure(probes([3], [0, '2.9.1+cpu']), { wheelhouse: true }) + assert.equal(ok.ready, true) + assert.ok(ok.uv[0].includes('--offline')) + assert.deepEqual(ok.env[0], { UV_OFFLINE: '1' }) + + const missing = await ensure(probes([3]), { wheelhouse: true, uvFails: true }) + assert.equal(missing.ready, false) + assert.match(missing.said, /the wheelhouse has no torch wheel for this machine/) + assert.match(missing.said, /Add the torch wheels for this machine to the wheelhouse folder/) + + // Offline, a torch without kernels for the GPU is kept: there is nothing to fetch. + const kept = await ensure(probes([5, 'RTX 5090']), { wheelhouse: true }) + assert.equal(kept.ready, true) + assert.deepEqual(kept.uv, []) +}) + +test('recordEnvStamp writes the stamp, or drops it when torch is not ready', () => { + const stampFile = join(tempDir('stamp-'), 'python-env', '.testapp-lock-hash') + recordEnvStamp(stampFile, 'abc', true) + assert.equal(existsSync(stampFile), true) + // Not ready: the next launch must run setup again to retry torch. + recordEnvStamp(stampFile, 'def', false) + assert.equal(existsSync(stampFile), false) +}) + +test('the setup window narrates the per-machine torch step', () => { + const sync = parseUvLine('[env-setup] running uv sync (as locked, keeping the per-machine torch)') + assert.equal(sync?.phase, 'resolving') + const install = parseUvLine('[env-setup] installing torch for this machine with --torch-backend=auto') + assert.equal(install?.step, 'Installing PyTorch for your GPU') + assert.equal(parseUvLine('[env-setup] keeping the installed PyTorch 2.9.1')?.step, + 'Keeping the installed PyTorch 2.9.1') + const failed = parseUvLine('[env-setup] PyTorch could not be installed (x). Test App will start without it.') + assert.equal(failed?.phase, 'torch') + assert.match(failed?.step ?? '', /could not be installed/) +}) + /** A packaged layout whose managed env already matches the shipped lock, so * resolvePythonEnv() answers from disk without shelling out to uv. */ function packagedLayout(): { resourcesPath: string; userData: string; envDir: string } { diff --git a/de_shell/js/main/pythonEnv.ts b/de_shell/js/main/pythonEnv.ts index 030c221..9e2e68f 100644 --- a/de_shell/js/main/pythonEnv.ts +++ b/de_shell/js/main/pythonEnv.ts @@ -21,6 +21,15 @@ * path), so the working install path can never regress. macOS keeps the plain * sync (no CUDA pin there; PyPI torch already carries MPS). * + * An app can instead leave torch out of its lock altogether + * (`[tool.uv] exclude-dependencies = ["torch"]`, which uv records in the lock + * as `[manifest] excludes`): a lock holds one build, and which build a machine + * needs depends on its GPU. Setup then syncs INEXACTLY, so a torch already in + * the env survives an upgrade instead of being removed and downloaded again, + * and installs torch with `--torch-backend=auto` only when it is missing or + * cannot run here — see `ensureTorchPerMachine`. Every platform, since nothing + * else would install it. + * * Extras: `ShellConfig.pythonExtras` are always installed (`--extra X`) and * `gpuExtras` only when an NVIDIA GPU is found (`hasNvidiaGpu`). The effective * extras are folded into the lock stamp, so gaining a GPU or adding an extra @@ -158,6 +167,55 @@ export function readLockedTorchVersion(projectDir: string): string | null { return pick.version.split('+')[0] // "2.6.0+cu124" → "2.6.0" } +/** + * How setup installs torch, read from `/uv.lock`: + * - `locked`: the lock pins torch; the two-step install pins that release. + * - `per-machine`: the lock EXCLUDES torch (`[tool.uv] exclude-dependencies`, + * recorded as `[manifest] excludes`), so nothing in the lock installs it and + * setup installs it for this machine. `requirement` is `torch` plus the + * specifier the app declared, if any (`torch>=2.4`). + * - `none`: the app has no torch. + * + * Read from the lock rather than declared in `configureShell` because the lock + * is what the sync obeys: the exclusion is the very reason the sync will not + * install torch, it ships in every payload, and its hash already drives the + * re-sync. A second declaration could disagree with it. + */ +export type TorchSetup = + | { kind: 'locked'; version: string } + | { kind: 'per-machine'; requirement: string } + | { kind: 'none' } + +export function readTorchSetup(projectDir: string): TorchSetup { + const version = readLockedTorchVersion(projectDir) + if (version) return { kind: 'locked', version } + const lock = readSafe(join(projectDir, 'uv.lock')) + if (!lockExcludes(lock).includes('torch')) return { kind: 'none' } + return { kind: 'per-machine', requirement: declaredTorchRequirement(lock) } +} + +/** Package names in the lock's `[manifest] excludes`, normalized. */ +function lockExcludes(lock: string): string[] { + const manifest = /^\[manifest\]\s*$([\s\S]*?)(?=^\[|(?![\s\S]))/m.exec(lock)?.[1] ?? '' + const list = /^excludes\s*=\s*\[([^\]]*)\]/m.exec(manifest)?.[1] ?? '' + return [...list.matchAll(/"([^"]+)"/g)].map((m) => m[1].toLowerCase().replace(/[_.]+/g, '-')) +} + +/** + * `torch` with the version specifier the app declared for it (the lock's + * `requires-dist`), so a ceiling the app set still holds without a lock. + * Entries behind an extra are skipped: setup does not know they apply. + */ +function declaredTorchRequirement(lock: string): string { + for (const m of lock.matchAll(/\{ name = "torch"(,[^}]*)?\}/g)) { + const rest = m[1] ?? '' + if (/marker = "[^"]*\bextra\b/.test(rest)) continue + const specifier = /specifier = "([^"]+)"/.exec(rest)?.[1] + return specifier ? `torch${specifier}` : 'torch' + } + return 'torch' +} + // ── GPU probe ──────────────────────────────────────────────────────────────── /** Runs a command and reports its exit code + stdout. Injectable so the probe's @@ -238,12 +296,14 @@ export function extraArgs(extras: string[]): string[] { } /** Every `uv sync` argv in one place so the torch two-step and the plain - * fallback cannot drift apart on extras. `skipPackages` → `--no-install-package`. */ + * fallback cannot drift apart on extras. `skipPackages` → `--no-install-package`. + * `inexact` keeps packages the lock does not name (a per-machine torch). */ export function buildSyncArgs( - projectArgs: string[], extras: string[], skipPackages: string[] = [], + projectArgs: string[], extras: string[], skipPackages: string[] = [], inexact = false, ): string[] { return [ - 'sync', '--frozen', '--no-dev', ...projectArgs, ...extraArgs(extras), + 'sync', '--frozen', '--no-dev', ...(inexact ? ['--inexact'] : []), + ...projectArgs, ...extraArgs(extras), ...skipPackages.flatMap((p) => ['--no-install-package', p]), ] } @@ -471,14 +531,11 @@ export async function resolvePythonEnv(opts: EnsureOptions): Promise void): } /** - * Install the locked torch release into the managed env with the backend - * resolved for THIS machine (`--torch-backend=auto`: uv probes the NVIDIA - * driver and picks the matching cuXXX wheel, or the much smaller CPU wheel when - * no GPU is present). Shared by first-run setup (step 2) and the GPU-triage - * "Fix PyTorch install" handler. Throws on failure (caller decides fallback). + * uv's argv to install torch into the env at `pythonExe`, or null when the app + * has no torch. + * + * Online, `--torch-backend=auto` has uv probe the NVIDIA driver and pick the + * matching cuXXX wheel, or the much smaller CPU wheel when there is no GPU. A + * locked torch is pinned to its release; a per-machine one takes the newest + * release the app's specifier allows, so a new GPU gets a build with kernels + * for it. The per-machine install runs with `--no-config`: the app's `[tool.uv]` + * settings are for its lock (`prerelease = "allow"` would let a torch release + * candidate in), and uv's own configuration has no say over this one package. + * + * From a wheelhouse there is no index to probe, so the per-machine torch is + * whichever torch wheel the folder holds. + * + * An installed torch already satisfies the requirement, so uv keeps it unless + * told otherwise: `reinstall` replaces one whose files are damaged with the + * same release, `upgrade` moves one without kernels for this GPU to the newest + * build for this machine — a no-op when it already is that build. + */ +export function torchInstallArgs( + setup: TorchSetup, + pythonExe: string, + o: { reinstall?: boolean; upgrade?: boolean; wheelhouse?: string } = {}, +): string[] | null { + if (setup.kind === 'none') return null + const reinstall = [ + ...(o.reinstall ? ['--reinstall-package', 'torch'] : []), + ...(o.upgrade ? ['--upgrade-package', 'torch'] : []), + ] + if (setup.kind === 'locked') { + return ['pip', 'install', `torch==${setup.version}`, '--torch-backend=auto', + ...reinstall, '--python', pythonExe] + } + const source = o.wheelhouse + ? ['--offline', '--no-index', '--find-links', o.wheelhouse] + : ['--torch-backend=auto'] + return ['pip', 'install', '--no-config', setup.requirement, ...source, ...reinstall, + '--python', pythonExe] +} + +/** + * Install torch into the managed env with the backend resolved for THIS + * machine. Shared by first-run setup and the GPU-triage "Fix PyTorch install" + * handler — which should pass `{ reinstall: true }` (a locked pin) or + * `{ upgrade: true }` (per machine), since a torch of the wrong build already + * satisfies the requirement. Works whether the lock pins torch + * or excludes it (see `readTorchSetup`). Throws on failure (caller decides + * fallback). */ export function installTorchPerMachine( projectDir: string, envDir: string, onProgress?: (line: string) => void, + options: { reinstall?: boolean; upgrade?: boolean } = {}, ): Promise { - const torchVersion = readLockedTorchVersion(projectDir) - if (!torchVersion) { - return Promise.reject(new Error('could not read the locked torch version from uv.lock')) + const setup = readTorchSetup(projectDir) + const args = torchInstallArgs(setup, venvPython(envDir), options) + if (!args || setup.kind === 'none') { + return Promise.reject(new Error('uv.lock neither pins nor excludes torch')) } - onProgress?.(`[env-setup] installing torch==${torchVersion} with --torch-backend=auto\n`) + onProgress?.(setup.kind === 'locked' + ? `[env-setup] installing torch==${setup.version} with --torch-backend=auto\n` + : `[env-setup] installing ${setup.requirement} for this machine with --torch-backend=auto\n`) return runUv( - projectDir, envDir, - ['pip', 'install', `torch==${torchVersion}`, '--torch-backend=auto', - '--python', venvPython(envDir)], + projectDir, envDir, args, '', // no scm pretend-version needed for a plain pip install onProgress, ) } +/** + * Asks the env's Python whether torch is there and can run, without the + * caller importing anything. Exit codes: 0 usable (prints the version), 3 not + * installed, 4 installed but its import fails, 5 a CUDA GPU this build has no + * kernels for (2.6.0+cu124 on an sm_120 card). `-I`: no PYTHONPATH, user site + * or working directory can stand in for the env's own torch. + */ +const TORCH_PROBE = [ + 'import importlib.util, sys', + 'if importlib.util.find_spec("torch") is None: sys.exit(3)', + 'try:', + ' import torch', + 'except Exception as error:', + ' print(f"{type(error).__name__}: {error}"); sys.exit(4)', + 'print(torch.__version__)', + 'try:', + ' if torch.cuda.is_available():', + ' major, minor = torch.cuda.get_device_capability(0)', + ' device = major * 10 + minor', + ' def number(arch): return int("".join(c for c in arch if c.isdigit()))', + ' built = [a.split("_", 1) for a in torch.cuda.get_arch_list()]', + // A cubin runs on its own major at an equal or higher minor; PTX JITs upward. + ' if not any((kind == "sm" and number(n) // 10 == major and number(n) <= device)', + ' or (kind == "compute" and number(n) <= device) for kind, n in built):', + ' print(torch.cuda.get_device_name(0)); sys.exit(5)', + 'except Exception:', + ' pass', +].join('\n') + +export type TorchStatus = + | { state: 'usable'; version: string } + | { state: 'missing' } + | { state: 'broken'; detail: string } + | { state: 'no-kernels'; version: string; device: string } + | { state: 'unknown' } + +/** + * Is torch in the env at `pythonExe`, and can it run here? Never throws. A + * probe that could not finish (a hung import on a cold disk, a Python that will + * not start) is `unknown`, which setup treats as "leave it alone" rather than + * re-downloading gigabytes on a guess. + */ +export async function probeTorch( + pythonExe: string, run: CommandRunner = defaultRunner, +): Promise { + try { + const { code, stdout } = await run(pythonExe, ['-I', '-c', TORCH_PROBE], 180_000) + const lines = (stdout ?? '').trim().split(/\r?\n/) + const last = lines.at(-1)?.trim() ?? '' + if (code === 0) return { state: 'usable', version: last } + if (code === 3) return { state: 'missing' } + if (code === 4) return { state: 'broken', detail: last } + if (code === 5) return { state: 'no-kernels', version: lines[0]?.trim() ?? '', device: last } + return { state: 'unknown' } + } catch { return { state: 'unknown' } } +} + +/** A uv invocation against the managed env: argv after `uv`, progress, extra env. */ +export type UvCall = ( + args: string[], onProgress?: (line: string) => void, extraEnv?: Record, +) => Promise + +/** + * The per-machine torch step, run after the env is otherwise complete: keep a + * torch that runs here, install one when it is missing, and replace one that + * fails to import or has no kernels for this GPU. Narrated through + * `onProgress`. Returns whether torch is ready; a failed install is SAID, never + * thrown, so the backend still starts (and names what it lacks) and the caller + * drops the env stamp to try again next launch. + * + * From a wheelhouse, torch comes from that folder or not at all — an offline + * install never reaches for the network. + */ +export async function ensureTorchPerMachine(o: { + requirement: string + pythonExe: string + wheelhouse: { dir: string; env: Record } | null + uv: UvCall + onProgress?: (line: string) => void + probe?: CommandRunner +}): Promise { + const say = (line: string) => o.onProgress?.(`[env-setup] ${line}\n`) + const app = shellConfig().appName + const setup: TorchSetup = { kind: 'per-machine', requirement: o.requirement } + say('checking the installed PyTorch') + const before = await probeTorch(o.pythonExe, o.probe) + if (before.state === 'usable') { + say(`keeping the installed PyTorch ${before.version}`) + return true + } + if (before.state === 'unknown') { + say('could not check the installed PyTorch; keeping what is there') + return true + } + if (before.state === 'no-kernels' && o.wheelhouse) { + say(`keeping the installed PyTorch ${before.version}: it has no kernels for ` + + `${before.device}, and an offline install cannot fetch another build`) + return true + } + if (before.state === 'broken') say(`the installed PyTorch does not load (${before.detail})`) + if (before.state === 'no-kernels') { + say(`the installed PyTorch ${before.version} has no kernels for ${before.device}`) + } + + const args = torchInstallArgs(setup, o.pythonExe, { + reinstall: before.state === 'broken', upgrade: before.state === 'no-kernels', + wheelhouse: o.wheelhouse?.dir, + })! + say(o.wheelhouse + ? `installing ${o.requirement} from the wheelhouse` + : `installing ${o.requirement} for this machine with --torch-backend=auto`) + const failed = (why: string) => { + say(`PyTorch could not be installed (${why}). ${app} will start without it. ` + (o.wheelhouse + ? 'Add the torch wheels for this machine to the wheelhouse folder, or remove the ' + + 'wheelhouse to install online, and restart.' + : 'Check the internet connection and restart to try again.')) + return false + } + try { + await o.uv(args, o.onProgress, o.wheelhouse?.env) + } catch (err) { + return failed(o.wheelhouse + ? 'the wheelhouse has no torch wheel for this machine' + : ((err as Error)?.message ?? String(err))) + } + const after = await probeTorch(o.pythonExe, o.probe) + if (after.state === 'missing') return failed('it is still missing after the install') + if (after.state === 'broken') return failed(`it does not load: ${after.detail}`) + if (after.state === 'no-kernels') { + // The newest build uv offers this machine still lacks the GPU (a card newer + // than any build, or one the newer builds dropped). Retrying on every launch + // would not change that, so it is said and setup carries on. + say(`PyTorch ${after.version} has no kernels for ${after.device}, and uv has no ` + + 'newer build for this machine; it will run on the CPU') + } + say('per-machine torch install complete') + return true +} + /** The pre-built app wheel staged by bundle-python.mjs at /wheels/ * (a single py3-none-any .whl). Null in dev (no staged wheel) → the caller * installs the project from source the old way (dev tree is writable). @@ -802,6 +1060,11 @@ function installAppWheel( * the app is installed from the wheel afterwards — so NOTHING is built from the * read-only source tree. In dev (no staged wheel) the project installs from * source as before. Logs which path ran to the progress stream. + * + * A lock that EXCLUDES torch (`readTorchSetup`'s `per-machine`) syncs + * inexactly, installs the app, and only then runs `ensureTorchPerMachine`, on + * every platform and from a wheelhouse too. Resolves whether torch is ready — + * always true for the other two kinds. */ async function setupEnv(o: { projectDir: string @@ -810,8 +1073,15 @@ async function setupEnv(o: { extras: string[] wheelhouse: { dir: string; manifest: WheelhouseManifest } | null onProgress?: (line: string) => void -}): Promise { +}): Promise { const { projectDir, envDir, appVersion, extras, wheelhouse, onProgress } = o + const torch = readTorchSetup(projectDir) + const torchPerMachine = (offline: { dir: string; env: Record } | null) => + torch.kind !== 'per-machine' ? true : ensureTorchPerMachine({ + requirement: torch.requirement, pythonExe: venvPython(envDir), wheelhouse: offline, + uv: (args, progress, extraEnv) => runUv(projectDir, envDir, args, '', progress, extraEnv), + onProgress, + }) const wheel = stagedAppWheel(projectDir) const memberWheels = stagedMemberWheels(projectDir, wheel) // With a staged wheel, tell uv sync NOT to touch the project (the app builds @@ -854,7 +1124,20 @@ async function setupEnv(o: { } if (wheel) await installAppWheel(projectDir, envDir, wheel, onProgress, plan.env) onProgress?.('[env-setup] offline install complete\n') - return + return torchPerMachine({ dir, env: plan.env }) + } + + if (torch.kind === 'per-machine') { + // Inexact: torch is not in the lock, so an exact sync would remove the one + // installed for this machine (and its dependencies) on every upgrade. + onProgress?.('[env-setup] running uv sync (as locked, keeping the per-machine torch)\n') + await runUv(projectDir, envDir, buildSyncArgs(projectArgs, extras, [], true), + appVersion, onProgress) + for (const memberWheel of memberWheels) { + await installAppWheel(projectDir, envDir, memberWheel, onProgress) + } + if (wheel) await installAppWheel(projectDir, envDir, wheel, onProgress) + return torchPerMachine(null) } const twoStep = @@ -882,7 +1165,7 @@ async function setupEnv(o: { } if (wheel) await installAppWheel(projectDir, envDir, wheel, onProgress) onProgress?.('[env-setup] per-machine torch install complete\n') - return + return true } catch (err) { onProgress?.(`[env-setup] per-machine torch install failed (${(err as Error)?.message ?? err}); ` + 'falling back to the full locked sync\n') @@ -896,4 +1179,5 @@ async function setupEnv(o: { await installAppWheel(projectDir, envDir, memberWheel, onProgress) } if (wheel) await installAppWheel(projectDir, envDir, wheel, onProgress) + return true } diff --git a/upcoming_changes/+torch-per-machine.bugfix.rst b/upcoming_changes/+torch-per-machine.bugfix.rst new file mode 100644 index 0000000..1fdb6c0 --- /dev/null +++ b/upcoming_changes/+torch-per-machine.bugfix.rst @@ -0,0 +1 @@ +An app that leaves torch out of its lock (``[tool.uv] exclude-dependencies = ["torch"]``) got no torch on its first run and lost the one it had on every upgrade; setup now keeps an installed torch (an ``--inexact`` sync) and installs one for the machine's GPU with ``--torch-backend=auto`` only when it is missing, does not load, or has no kernels for the GPU, and a failed install is reported in the setup overlay while the app still starts and the next launch retries. diff --git a/upcoming_changes/+torch-per-machine.new_feature.rst b/upcoming_changes/+torch-per-machine.new_feature.rst new file mode 100644 index 0000000..0190369 --- /dev/null +++ b/upcoming_changes/+torch-per-machine.new_feature.rst @@ -0,0 +1 @@ +``installTorchPerMachine`` works for a torch left out of the lock (no ``torch==`` pin) and takes ``{ reinstall: true }`` or ``{ upgrade: true }`` so a "Fix PyTorch" button can replace a torch of the wrong build, which uv otherwise keeps. From ebbaa2c8597f14ad5eec7a01e8be049889329bd2 Mon Sep 17 00:00:00 2001 From: Carter Francis Date: Thu, 19 Nov 2026 16:21:37 -0600 Subject: [PATCH 2/5] Tell the three torch cases apart, and keep the PyTorch pill through progress Per machine now needs the app to declare torch (a requires-dist entry) as well as exclude it from the lock; torch merely absent from the lock is an app with none, so Ground Crew keeps its exact sync and no pill. Setup, the two-step and the setup window's PyTorch step all take the case from readTorchSetup (setupHasTorchStep for the start message). The requirement parser also missed a bare `{ name = "torch" }` entry, which is how Autopilot's lock writes it. A progress line rebuilt the setup state without the torch and wheelhouse the start had set, so the pill came back for an app with no torch and an offline install lost its folder line (#44). It now keeps the rest of the state. Claude-Session: https://claude.ai/code/session_01DzXsKAUJSM4XYpqqzrcuV5 --- README.md | 13 ++++++--- de_shell/js/main/envSetup.ts | 4 +-- de_shell/js/main/envSetupMachine.ts | 3 ++- de_shell/js/main/index.ts | 2 +- de_shell/js/main/pythonEnv.test.ts | 16 +++++++++++ de_shell/js/main/pythonEnv.ts | 32 +++++++++++++++------- de_shell/js/renderer/envSetupView.ts | 3 ++- de_shell/js/renderer/shellState.test.ts | 35 +++++++++++++++++++++++++ de_shell/js/renderer/shellState.ts | 3 +++ 9 files changed, 93 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index dd19ba0..d5b6dc2 100644 --- a/README.md +++ b/README.md @@ -171,12 +171,17 @@ installed when `nvidia-smi` finds a device. `_GPU=0|1` overrides the probe either way. **torch.** A lock holds one torch build, and which build a machine needs -depends on its GPU. There are two ways to ship it: +depends on its GPU. Setup tells three cases apart from the lock, and the setup +window shows the PyTorch step for the last two only: +* *No torch* (Ground Crew): an exact `uv sync`, as for any app. * *Locked* (SpyDE): the lock pins torch. On Windows and Linux, setup syncs - everything else, then installs that release with `--torch-backend=auto`. -* *Per machine* (Autopilot): leave torch out of the lock with - `[tool.uv] exclude-dependencies = ["torch"]`, which uv records in `uv.lock`. + everything else exactly, then installs that release with + `--torch-backend=auto`. +* *Per machine* (Autopilot): name torch as a dependency and leave it out of + the lock with `[tool.uv] exclude-dependencies = ["torch"]`, which uv records + in `uv.lock`. Both are needed: torch merely absent from the lock means no + torch. Setup syncs with `--inexact`, so a torch already installed survives an upgrade. It then installs the newest torch the app's specifier allows, built for this machine, but only when torch is missing, does not load, or has no diff --git a/de_shell/js/main/envSetup.ts b/de_shell/js/main/envSetup.ts index 21c40f2..7691e1b 100644 --- a/de_shell/js/main/envSetup.ts +++ b/de_shell/js/main/envSetup.ts @@ -20,7 +20,7 @@ import { app, dialog, ipcMain } from 'electron' import { channel, shellConfig } from './config' import { runEnvSetupMachine } from './envSetupMachine' import type { EnvSetupAnswer } from './envSetupMachine' -import { readTorchSetup, resolvePythonEnv } from './pythonEnv' +import { resolvePythonEnv, setupHasTorchStep } from './pythonEnv' import type { EnsureOptions, ResolvedPython } from './pythonEnv' import type { ShellWindow } from './window' @@ -58,7 +58,7 @@ export function runEnvSetup( listenForAnswers() return runEnvSetupMachine({ initialWheelhouse: opts.wheelhouse ?? null, - torch: readTorchSetup(join(opts.resourcesPath, 'python')).kind !== 'none', + torch: setupHasTorchStep(join(opts.resourcesPath, 'python')), run: (wheelhouse, onProgress) => resolvePythonEnv({ ...opts, wheelhouse, diff --git a/de_shell/js/main/envSetupMachine.ts b/de_shell/js/main/envSetupMachine.ts index f7410dc..5e6fdd5 100644 --- a/de_shell/js/main/envSetupMachine.ts +++ b/de_shell/js/main/envSetupMachine.ts @@ -119,7 +119,8 @@ export interface MachineDeps { /** Native folder picker; null when cancelled. */ pickFolder: () => Promise quit: () => void - /** False when the app's lock has no torch, so the overlay drops that step. */ + /** False when the app has no torch (`setupHasTorchStep`), so the overlay + * drops that step. */ torch?: boolean /** Wheelhouse to start with (an app that already knows the machine is offline). */ initialWheelhouse?: string | null diff --git a/de_shell/js/main/index.ts b/de_shell/js/main/index.ts index 3dd6c02..8aba232 100644 --- a/de_shell/js/main/index.ts +++ b/de_shell/js/main/index.ts @@ -43,7 +43,7 @@ export type { BackendHandlers } from './backendProcess' export { resolvePythonEnv, managedEnvPaths, venvPython, readLockedTorchVersion, installTorchPerMachine, hasNvidiaGpu, readWheelhouse, findWheelhouse, - wheelhouseCandidates, lockStamp, buildSyncArgs, offlinePlan, readTorchSetup, + wheelhouseCandidates, lockStamp, buildSyncArgs, offlinePlan, readTorchSetup, setupHasTorchStep, torchInstallArgs, probeTorch, ensureTorchPerMachine, } from './pythonEnv' export type { diff --git a/de_shell/js/main/pythonEnv.test.ts b/de_shell/js/main/pythonEnv.test.ts index e311933..1777c8a 100644 --- a/de_shell/js/main/pythonEnv.test.ts +++ b/de_shell/js/main/pythonEnv.test.ts @@ -34,6 +34,7 @@ import { } from './pythonEnv.ts' import { readTorchSetup, torchInstallArgs, probeTorch, ensureTorchPerMachine, recordEnvStamp, + setupHasTorchStep, } from './pythonEnv.ts' import type { CommandRunner } from './pythonEnv.ts' @@ -415,6 +416,21 @@ test('readTorchSetup: no torch, another exclusion, or no lock at all is none', ( assert.deepEqual(readTorchSetup(emptyDir()), { kind: 'none' }) }) +test('readTorchSetup: excluding torch the app does not declare is none, not per machine', () => { + // Only a torch the app names as a dependency is installed per machine. + const lock = LOCK_EXCLUDES_TORCH + .replace(/^ {4}\{ name = "torch".*\n/gm, '') + assert.ok(!lock.includes('name = "torch"')) + assert.deepEqual(readTorchSetup(projectWithLock(lock)), { kind: 'none' }) +}) + +test('the PyTorch step: none for an app with no torch, shown for locked and per machine', () => { + // Ground Crew (no torch), SpyDE (locked), Autopilot (per machine). + assert.equal(setupHasTorchStep(projectWithLock('version = 1\n')), false) + assert.equal(setupHasTorchStep(projectWithLock(LOCK_PINS_TORCH)), true) + assert.equal(setupHasTorchStep(projectWithLock(LOCK_EXCLUDES_TORCH)), true) +}) + test('buildSyncArgs syncs inexactly on request, so a per-machine torch survives', () => { assert.deepEqual(buildSyncArgs(['--no-install-project'], [], [], true), ['sync', '--frozen', '--no-dev', '--inexact', '--no-install-project']) diff --git a/de_shell/js/main/pythonEnv.ts b/de_shell/js/main/pythonEnv.ts index 9e2e68f..ba6c258 100644 --- a/de_shell/js/main/pythonEnv.ts +++ b/de_shell/js/main/pythonEnv.ts @@ -174,7 +174,12 @@ export function readLockedTorchVersion(projectDir: string): string | null { * recorded as `[manifest] excludes`), so nothing in the lock installs it and * setup installs it for this machine. `requirement` is `torch` plus the * specifier the app declared, if any (`torch>=2.4`). - * - `none`: the app has no torch. + * - `none`: the app has no torch (Ground Crew): no PyTorch step, no pill, + * and the exact sync as before. + * + * Per machine needs BOTH declarations: the app names torch as a dependency + * (the lock's `requires-dist`, copied from its pyproject) and excludes it from + * the lock. Torch merely being absent from the lock means the app has none. * * Read from the lock rather than declared in `configureShell` because the lock * is what the sync obeys: the exclusion is the very reason the sync will not @@ -190,8 +195,16 @@ export function readTorchSetup(projectDir: string): TorchSetup { const version = readLockedTorchVersion(projectDir) if (version) return { kind: 'locked', version } const lock = readSafe(join(projectDir, 'uv.lock')) - if (!lockExcludes(lock).includes('torch')) return { kind: 'none' } - return { kind: 'per-machine', requirement: declaredTorchRequirement(lock) } + const requirement = declaredTorchRequirement(lock) + if (!requirement || !lockExcludes(lock).includes('torch')) return { kind: 'none' } + return { kind: 'per-machine', requirement } +} + +/** Whether setup has a PyTorch step, so the setup window shows the PyTorch + * pill: a locked or a per-machine torch, never an app with none. The overlay + * and setup take it from the same `readTorchSetup`, so they cannot disagree. */ +export function setupHasTorchStep(projectDir: string): boolean { + return readTorchSetup(projectDir).kind !== 'none' } /** Package names in the lock's `[manifest] excludes`, normalized. */ @@ -203,17 +216,18 @@ function lockExcludes(lock: string): string[] { /** * `torch` with the version specifier the app declared for it (the lock's - * `requires-dist`), so a ceiling the app set still holds without a lock. - * Entries behind an extra are skipped: setup does not know they apply. + * `requires-dist`), so a ceiling the app set still holds without a lock; null + * when the app does not declare torch. Entries behind an extra are skipped: + * setup does not know they apply. */ -function declaredTorchRequirement(lock: string): string { - for (const m of lock.matchAll(/\{ name = "torch"(,[^}]*)?\}/g)) { +function declaredTorchRequirement(lock: string): string | null { + for (const m of lock.matchAll(/\{ name = "torch"(,[^}]*)?\s*\}/g)) { const rest = m[1] ?? '' if (/marker = "[^"]*\bextra\b/.test(rest)) continue const specifier = /specifier = "([^"]+)"/.exec(rest)?.[1] return specifier ? `torch${specifier}` : 'torch' } - return 'torch' + return null } // ── GPU probe ──────────────────────────────────────────────────────────────── @@ -1142,7 +1156,7 @@ async function setupEnv(o: { const twoStep = (process.platform === 'win32' || process.platform === 'linux') && - readLockedTorchVersion(projectDir) !== null + torch.kind === 'locked' if (twoStep) { try { diff --git a/de_shell/js/renderer/envSetupView.ts b/de_shell/js/renderer/envSetupView.ts index cf299d5..58aed47 100644 --- a/de_shell/js/renderer/envSetupView.ts +++ b/de_shell/js/renderer/envSetupView.ts @@ -16,7 +16,8 @@ export const ENV_PHASES: ReadonlyArray<{ key: EnvPhase; label: string }> = [ export type PillState = 'done' | 'active' | 'todo' -/** `torch` false leaves out the PyTorch pill, for an app with no torch in its lock. */ +/** `torch` false leaves out the PyTorch pill, for an app with no torch at all + * (a torch kept out of the lock and installed per machine still has the step). */ export function phasePills(phase: EnvPhase, torch = true) { const phases = torch ? ENV_PHASES : ENV_PHASES.filter(p => p.key !== 'torch') const active = phase === 'working' ? 'resolving' : phase diff --git a/de_shell/js/renderer/shellState.test.ts b/de_shell/js/renderer/shellState.test.ts index dee5000..e7750c7 100644 --- a/de_shell/js/renderer/shellState.test.ts +++ b/de_shell/js/renderer/shellState.test.ts @@ -13,6 +13,7 @@ import { shellReducer, shellInitialState, toShellAction, LOG_MAX, STREAM_MAX, type ShellState, type LogEntry, } from './shellState.ts' +import { phasePills } from './envSetupView.ts' /** A state shaped like an app's: the shell's fields plus one of its own. */ interface AppState extends ShellState { mine: number } @@ -173,6 +174,40 @@ describe('toShellAction', () => { assert.equal(shellReducer(appState, { type: 'ENV_SETUP_START' }).envSetup?.torch, true) }) + test('a progress line keeps the torch and wheelhouse the start set (#44)', () => { + let s = shellReducer(appState, toShellAction( + { type: 'env_setup', state: 'start', torch: false, wheelhouse: 'wheels' })!) + s = shellReducer(s, { + type: 'ENV_SETUP_PROGRESS', phase: 'resolving', step: 'Resolving', percent: null, + raw: 'Resolved 120 packages', + }) + assert.equal(s.envSetup?.torch, false) + assert.equal(s.envSetup?.wheelhouse, 'wheels') + assert.equal(s.envSetup?.step, 'Resolving') + assert.deepEqual(s.envSetup?.lines, ['Resolved 120 packages']) + }) + + test('the PyTorch pill through progress and a failure: none, locked, per machine', () => { + // What main sends as `torch` for each kind (setupHasTorchStep). + const cases = [['no torch', false], ['locked torch', true], ['per-machine torch', true]] as const + for (const [kind, torch] of cases) { + let s = shellReducer(appState, toShellAction({ type: 'env_setup', state: 'start', torch })!) + s = shellReducer(s, { + type: 'ENV_SETUP_PROGRESS', phase: 'downloading', step: 'Downloading six', percent: 40, + raw: 'Downloading six', + }) + // A progress line that parses to nothing keeps the phase and step too. + s = shellReducer(s, { type: 'ENV_SETUP_PROGRESS', percent: null, raw: '…' }) + assert.equal(s.envSetup?.phase, 'downloading', kind) + assert.equal(s.envSetup?.step, 'Downloading six', kind) + const pill = () => phasePills(s.envSetup!.phase, s.envSetup!.torch ?? true) + .some((p) => p.key === 'torch') + assert.equal(pill(), torch, kind) + s = shellReducer(s, toShellAction({ type: 'env_setup', state: 'error', message: 'x' })!) + assert.equal(pill(), torch, `${kind}, after a failure`) + } + }) + test('maps the chrome messages', () => { assert.deepEqual(toShellAction({ type: 'status', text: 'hi' }), { type: 'STATUS', text: 'hi' }) diff --git a/de_shell/js/renderer/shellState.ts b/de_shell/js/renderer/shellState.ts index 54f35c1..37e307d 100644 --- a/de_shell/js/renderer/shellState.ts +++ b/de_shell/js/renderer/shellState.ts @@ -221,6 +221,9 @@ export function shellReducer(state: S, action: ShellAction return { ...state, envSetup: { + // Whether setup has a PyTorch step, and the wheelhouse it installs + // from, outlive every progress line (#44). + ...prev, phase: action.phase ?? prev.phase, step: action.step ?? prev.step, percent: action.percent, From 838a1055ad0b54c2bc79ba52208d0099598e7f56 Mon Sep 17 00:00:00 2001 From: Carter Francis Date: Thu, 19 Nov 2026 16:21:50 -0600 Subject: [PATCH 3/5] Add the changelog fragment for #44 Claude-Session: https://claude.ai/code/session_01DzXsKAUJSM4XYpqqzrcuV5 --- upcoming_changes/+env-setup-progress.bugfix.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 upcoming_changes/+env-setup-progress.bugfix.rst diff --git a/upcoming_changes/+env-setup-progress.bugfix.rst b/upcoming_changes/+env-setup-progress.bugfix.rst new file mode 100644 index 0000000..1a43271 --- /dev/null +++ b/upcoming_changes/+env-setup-progress.bugfix.rst @@ -0,0 +1 @@ +The setup window showed the PyTorch pill again for an app with no torch, and an offline install lost its "Installing from" line, after the first progress line: a progress line now keeps what the start set. From 44c8d3bfaabd13e47f533f6c78b3b7f5849ef76c Mon Sep 17 00:00:00 2001 From: Carter Francis Date: Thu, 19 Nov 2026 16:59:24 -0600 Subject: [PATCH 4/5] Number the changelog fragments for #45 Claude-Session: https://claude.ai/code/session_01DzXsKAUJSM4XYpqqzrcuV5 --- .../{+env-setup-progress.bugfix.rst => 45.bugfix.1.rst} | 0 upcoming_changes/{+torch-per-machine.bugfix.rst => 45.bugfix.rst} | 0 .../{+torch-per-machine.new_feature.rst => 45.new_feature.rst} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename upcoming_changes/{+env-setup-progress.bugfix.rst => 45.bugfix.1.rst} (100%) rename upcoming_changes/{+torch-per-machine.bugfix.rst => 45.bugfix.rst} (100%) rename upcoming_changes/{+torch-per-machine.new_feature.rst => 45.new_feature.rst} (100%) diff --git a/upcoming_changes/+env-setup-progress.bugfix.rst b/upcoming_changes/45.bugfix.1.rst similarity index 100% rename from upcoming_changes/+env-setup-progress.bugfix.rst rename to upcoming_changes/45.bugfix.1.rst diff --git a/upcoming_changes/+torch-per-machine.bugfix.rst b/upcoming_changes/45.bugfix.rst similarity index 100% rename from upcoming_changes/+torch-per-machine.bugfix.rst rename to upcoming_changes/45.bugfix.rst diff --git a/upcoming_changes/+torch-per-machine.new_feature.rst b/upcoming_changes/45.new_feature.rst similarity index 100% rename from upcoming_changes/+torch-per-machine.new_feature.rst rename to upcoming_changes/45.new_feature.rst From 3c8251e8cb42971e3a40124bed0f0f0c3fc4816c Mon Sep 17 00:00:00 2001 From: Carter Francis Date: Thu, 19 Nov 2026 22:21:50 -0600 Subject: [PATCH 5/5] Choose the torch build from the GPU's compute capability before downloading uv's --torch-backend=auto reads only the driver version, so a recent driver on a card older than sm_70 (Pascal, Maxwell) got a cu128+ build with no kernels for it. Read the compute capability from nvidia-smi first and use cu126 for such a card; _TORCH_BACKEND overrides the choice. --- README.md | 8 +++ de_shell/js/main/index.ts | 2 +- de_shell/js/main/pythonEnv.test.ts | 44 ++++++++++++++++- de_shell/js/main/pythonEnv.ts | 78 ++++++++++++++++++++++-------- upcoming_changes/45.bugfix.2.rst | 1 + 5 files changed, 110 insertions(+), 23 deletions(-) create mode 100644 upcoming_changes/45.bugfix.2.rst diff --git a/README.md b/README.md index d5b6dc2..bc9b573 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,14 @@ window shows the PyTorch step for the last two only: wheelhouse builder works from the lock, so a site that needs torch offline adds the torch wheels to the folder itself. +**Which torch build.** Setup chooses `--torch-backend` before it downloads +anything. uv's `auto` looks only at the driver version, so a recent driver on +a card older than sm_70 (Pascal, Maxwell) would get a build with no kernels +for it. Setup therefore reads the compute capability from `nvidia-smi` first: +below 7.0 it installs cu126, the newest build that still supports those cards, +and otherwise `auto`. `_TORCH_BACKEND` (for example `cu126` or `cpu`) +overrides the choice. + A "Fix PyTorch" button calls `installTorchPerMachine` with `{ reinstall: true }` for a locked torch, or `{ upgrade: true }` per machine. diff --git a/de_shell/js/main/index.ts b/de_shell/js/main/index.ts index 8aba232..39c7c54 100644 --- a/de_shell/js/main/index.ts +++ b/de_shell/js/main/index.ts @@ -44,7 +44,7 @@ export { resolvePythonEnv, managedEnvPaths, venvPython, readLockedTorchVersion, installTorchPerMachine, hasNvidiaGpu, readWheelhouse, findWheelhouse, wheelhouseCandidates, lockStamp, buildSyncArgs, offlinePlan, readTorchSetup, setupHasTorchStep, - torchInstallArgs, probeTorch, ensureTorchPerMachine, + torchInstallArgs, probeTorch, ensureTorchPerMachine, torchBackend, } from './pythonEnv' export type { ResolvedPython, EnsureOptions, WheelhouseManifest, CommandRunner, OfflinePlan, diff --git a/de_shell/js/main/pythonEnv.test.ts b/de_shell/js/main/pythonEnv.test.ts index 1777c8a..0ac44ae 100644 --- a/de_shell/js/main/pythonEnv.test.ts +++ b/de_shell/js/main/pythonEnv.test.ts @@ -33,7 +33,7 @@ import { withoutPythonDownloadLines, uvNetworkEnv, } from './pythonEnv.ts' import { - readTorchSetup, torchInstallArgs, probeTorch, ensureTorchPerMachine, recordEnvStamp, + readTorchSetup, torchInstallArgs, probeTorch, ensureTorchPerMachine, recordEnvStamp, torchBackend, setupHasTorchStep, } from './pythonEnv.ts' import type { CommandRunner } from './pythonEnv.ts' @@ -199,6 +199,32 @@ test('hasNvidiaGpu never throws and asks for a ~5 s timeout', async () => { assert.deepEqual(seen, ['nvidia-smi', ['-L'], 5000]) }) +test('torchBackend: cu126 for a card older than sm_70, auto otherwise', async () => { + const none = {} + assert.equal(await torchBackend(runner(0, '6.1\n'), none), 'cu126') // TITAN X (Pascal) + assert.equal(await torchBackend(runner(0, '8.6\n'), none), 'auto') + assert.equal(await torchBackend(runner(0, '12.0\n'), none), 'auto') // RTX 5090 + assert.equal(await torchBackend(runner(0, '8.6\n6.1\n'), none), 'cu126') // the oldest decides +}) + +test('torchBackend: no driver or unreadable output leaves it to auto, and never throws', async () => { + const none = {} + assert.equal(await torchBackend(runner(null), none), 'auto') + assert.equal(await torchBackend(runner(9, '6.1'), none), 'auto') + assert.equal(await torchBackend(runner(0, 'Field "compute_cap" is not a valid field'), none), 'auto') + assert.equal(await torchBackend(async () => { throw new Error('ENOENT') }, none), 'auto') + let seen: unknown[] = [] + await torchBackend(async (cmd, args, t) => { seen = [cmd, args, t]; return { code: 1, stdout: '' } }, none) + assert.deepEqual(seen, ['nvidia-smi', ['--query-gpu=compute_cap', '--format=csv,noheader'], 5000]) +}) + +test('torchBackend: _TORCH_BACKEND beats the probe', async () => { + let probed = false + const run = async () => { probed = true; return { code: 0, stdout: '6.1' } } + assert.equal(await torchBackend(run, { TESTAPP_TORCH_BACKEND: ' cpu ' }), 'cpu') + assert.equal(probed, false) +}) + test('gpuEnvOverride reads _GPU', () => { assert.equal(gpuEnvOverride({ TESTAPP_GPU: '0' }), false) assert.equal(gpuEnvOverride({ TESTAPP_GPU: '1' }), true) @@ -500,7 +526,7 @@ test('probeTorch reads the probe exit code, isolated from PYTHONPATH', async () /** ensureTorchPerMachine with fakes: the uv calls it made and what it narrated. */ async function ensure( probe: CommandRunner, - o: { uvFails?: boolean; wheelhouse?: boolean } = {}, + o: { uvFails?: boolean; wheelhouse?: boolean; backend?: string } = {}, ): Promise<{ ready: boolean; uv: string[][]; env: Array | undefined>; said: string }> { @@ -518,6 +544,7 @@ async function ensure( }, onProgress: (line) => said.push(line), probe, + backend: o.backend ?? 'auto', }) return { ready, uv, env, said: said.join('') } } @@ -537,6 +564,19 @@ test('ensureTorchPerMachine installs a missing torch for this machine', async () assert.match(r.said, /installing torch for this machine with --torch-backend=auto/) }) +test('ensureTorchPerMachine installs the build torchBackend chose (cu126 on a Pascal card)', async () => { + const r = await ensure(probes([3], [0, '2.14.1+cu126']), { backend: 'cu126' }) + assert.equal(r.ready, true) + assert.deepEqual(r.uv, + [['pip', 'install', '--no-config', 'torch', '--torch-backend=cu126', '--python', 'py']]) + assert.match(r.said, /with --torch-backend=cu126/) +}) + +test('torchInstallArgs passes the chosen backend for a locked pin too', () => { + assert.deepEqual(torchInstallArgs({ kind: 'locked', version: '2.6.0' }, 'py', { backend: 'cu126' }), + ['pip', 'install', 'torch==2.6.0', '--torch-backend=cu126', '--python', 'py']) +}) + test('ensureTorchPerMachine reinstalls a torch that does not load', async () => { const r = await ensure(probes([4, 'ImportError: x'], [0, '2.9.1+cu128'])) assert.equal(r.ready, true) diff --git a/de_shell/js/main/pythonEnv.ts b/de_shell/js/main/pythonEnv.ts index ba6c258..d50b89c 100644 --- a/de_shell/js/main/pythonEnv.ts +++ b/de_shell/js/main/pythonEnv.ts @@ -13,9 +13,9 @@ * user. Instead the first-run install is two-step: * 1. `uv sync --frozen --no-dev --no-install-package torch` (lock-exact for * everything EXCEPT torch) - * 2. `uv pip install torch== --torch-backend=auto - * --python ` (uv probes the machine's driver and picks the - * matching CUDA / CPU wheel — verified: `--python` is required, uv pip + * 2. `uv pip install torch== --torch-backend= + * --python ` (`torchBackend`: cu126 below sm_70, else `auto`, + * where uv probes the machine's driver and picks the matching CUDA / CPU wheel — verified: `--python` is required, uv pip * IGNORES UV_PROJECT_ENVIRONMENT; needs uv >= 0.5, the staged uv is 0.10.x) * Any step-2 failure falls back to the plain full `uv sync` (the old cu124 * path), so the working install path can never regress. macOS keeps the plain @@ -26,7 +26,7 @@ * as `[manifest] excludes`): a lock holds one build, and which build a machine * needs depends on its GPU. Setup then syncs INEXACTLY, so a torch already in * the env survives an upgrade instead of being removed and downloaded again, - * and installs torch with `--torch-backend=auto` only when it is missing or + * and installs torch for this machine (`torchBackend`) only when it is missing or * cannot run here — see `ensureTorchPerMachine`. Every platform, since nothing * else would install it. * @@ -275,6 +275,37 @@ export async function hasNvidiaGpu(run: CommandRunner = defaultRunner): Promise< } catch { return false } } +/** + * The `--torch-backend` for this machine, chosen BEFORE anything downloads. + * + * uv's `auto` reads only the driver version and takes the newest CUDA build + * that driver runs. A recent driver on an older card then gets a build with no + * kernels for it: the cu128+ builds dropped everything below sm_70 (Pascal, + * Maxwell), yet `torch.cuda.is_available()` still says True and the first + * kernel fails. So the compute capability is read first, and a card below 7.0 + * gets cu126, the newest build that still carries sm_50–sm_61. With several + * GPUs the oldest one decides, so every device can run. + * + * `_TORCH_BACKEND` (any value uv takes: `cu126`, `cpu`, …) beats the + * probe. No `nvidia-smi`, or output it cannot parse, leaves the choice to + * `auto`. Never throws. + */ +export async function torchBackend( + run: CommandRunner = defaultRunner, env: NodeJS.ProcessEnv = process.env, +): Promise { + const override = (env[`${envPrefix()}_TORCH_BACKEND`] ?? '').trim() + if (override) return override + try { + const { code, stdout } = await run( + 'nvidia-smi', ['--query-gpu=compute_cap', '--format=csv,noheader'], 5000) + if (code !== 0) return 'auto' + const capabilities = (stdout ?? '').split(/\r?\n/).map((l) => Number.parseFloat(l)) + .filter((c) => Number.isFinite(c)) + if (capabilities.length && Math.min(...capabilities) < 7) return 'cu126' + } catch { /* no driver: auto falls back to the CPU build */ } + return 'auto' +} + /** The `_GPU` override: '0'/'false' → false, '1'/'true' → true, else * undefined (no override). */ export function gpuEnvOverride(env: NodeJS.ProcessEnv = process.env): boolean | undefined { @@ -783,8 +814,10 @@ export function withoutPythonDownloadLines(onProgress?: (line: string) => void): * uv's argv to install torch into the env at `pythonExe`, or null when the app * has no torch. * - * Online, `--torch-backend=auto` has uv probe the NVIDIA driver and pick the - * matching cuXXX wheel, or the much smaller CPU wheel when there is no GPU. A + * Online, `--torch-backend` picks the build: `backend` from `torchBackend` + * (cu126 for a card older than sm_70), otherwise `auto`, where uv probes the + * NVIDIA driver for the matching cuXXX wheel, or the much smaller CPU wheel + * when there is no GPU. A * locked torch is pinned to its release; a per-machine one takes the newest * release the app's specifier allows, so a new GPU gets a build with kernels * for it. The per-machine install runs with `--no-config`: the app's `[tool.uv]` @@ -802,20 +835,21 @@ export function withoutPythonDownloadLines(onProgress?: (line: string) => void): export function torchInstallArgs( setup: TorchSetup, pythonExe: string, - o: { reinstall?: boolean; upgrade?: boolean; wheelhouse?: string } = {}, + o: { reinstall?: boolean; upgrade?: boolean; wheelhouse?: string; backend?: string } = {}, ): string[] | null { if (setup.kind === 'none') return null + const backend = `--torch-backend=${o.backend ?? 'auto'}` const reinstall = [ ...(o.reinstall ? ['--reinstall-package', 'torch'] : []), ...(o.upgrade ? ['--upgrade-package', 'torch'] : []), ] if (setup.kind === 'locked') { - return ['pip', 'install', `torch==${setup.version}`, '--torch-backend=auto', + return ['pip', 'install', `torch==${setup.version}`, backend, ...reinstall, '--python', pythonExe] } const source = o.wheelhouse ? ['--offline', '--no-index', '--find-links', o.wheelhouse] - : ['--torch-backend=auto'] + : [backend] return ['pip', 'install', '--no-config', setup.requirement, ...source, ...reinstall, '--python', pythonExe] } @@ -829,20 +863,19 @@ export function torchInstallArgs( * or excludes it (see `readTorchSetup`). Throws on failure (caller decides * fallback). */ -export function installTorchPerMachine( +export async function installTorchPerMachine( projectDir: string, envDir: string, onProgress?: (line: string) => void, options: { reinstall?: boolean; upgrade?: boolean } = {}, ): Promise { const setup = readTorchSetup(projectDir) - const args = torchInstallArgs(setup, venvPython(envDir), options) - if (!args || setup.kind === 'none') { - return Promise.reject(new Error('uv.lock neither pins nor excludes torch')) - } + if (setup.kind === 'none') throw new Error('uv.lock neither pins nor excludes torch') + const backend = await torchBackend() + const args = torchInstallArgs(setup, venvPython(envDir), { ...options, backend })! onProgress?.(setup.kind === 'locked' - ? `[env-setup] installing torch==${setup.version} with --torch-backend=auto\n` - : `[env-setup] installing ${setup.requirement} for this machine with --torch-backend=auto\n`) + ? `[env-setup] installing torch==${setup.version} with --torch-backend=${backend}\n` + : `[env-setup] installing ${setup.requirement} for this machine with --torch-backend=${backend}\n`) return runUv( projectDir, envDir, args, '', // no scm pretend-version needed for a plain pip install @@ -930,6 +963,9 @@ export async function ensureTorchPerMachine(o: { uv: UvCall onProgress?: (line: string) => void probe?: CommandRunner + /** The `--torch-backend`; read with `torchBackend` when an online install + * is needed and none is given. */ + backend?: string }): Promise { const say = (line: string) => o.onProgress?.(`[env-setup] ${line}\n`) const app = shellConfig().appName @@ -954,13 +990,14 @@ export async function ensureTorchPerMachine(o: { say(`the installed PyTorch ${before.version} has no kernels for ${before.device}`) } + const backend = o.wheelhouse ? undefined : (o.backend ?? await torchBackend()) const args = torchInstallArgs(setup, o.pythonExe, { reinstall: before.state === 'broken', upgrade: before.state === 'no-kernels', - wheelhouse: o.wheelhouse?.dir, + wheelhouse: o.wheelhouse?.dir, backend, })! say(o.wheelhouse ? `installing ${o.requirement} from the wheelhouse` - : `installing ${o.requirement} for this machine with --torch-backend=auto`) + : `installing ${o.requirement} for this machine with --torch-backend=${backend}`) const failed = (why: string) => { say(`PyTorch could not be installed (${why}). ${app} will start without it. ` + (o.wheelhouse ? 'Add the torch wheels for this machine to the wheelhouse folder, or remove the ' + @@ -983,7 +1020,8 @@ export async function ensureTorchPerMachine(o: { // than any build, or one the newer builds dropped). Retrying on every launch // would not change that, so it is said and setup carries on. say(`PyTorch ${after.version} has no kernels for ${after.device}, and uv has no ` + - 'newer build for this machine; it will run on the CPU') + `newer build for this machine; it will run on the CPU. Set ${envPrefix()}_TORCH_BACKEND ` + + '(for example cu126) to choose the build.') } say('per-machine torch install complete') return true @@ -1161,7 +1199,7 @@ async function setupEnv(o: { if (twoStep) { try { onProgress?.('[env-setup] two-step install: uv sync (lock-exact, torch deferred) ' - + 'then torch via --torch-backend=auto\n') + + 'then torch for this machine\n') // Step 1: every DEPENDENCY except torch, exactly as locked. torch is the // only torch-family package in the lock, so one exclusion covers it. await runUv( diff --git a/upcoming_changes/45.bugfix.2.rst b/upcoming_changes/45.bugfix.2.rst new file mode 100644 index 0000000..0eda33d --- /dev/null +++ b/upcoming_changes/45.bugfix.2.rst @@ -0,0 +1 @@ +A GPU older than sm_70 (Pascal, Maxwell) on a recent driver got a torch build with no kernels for it, because ``--torch-backend=auto`` looks only at the driver version, so every GPU operation failed; setup now reads the compute capability from ``nvidia-smi`` before downloading and installs the cu126 build for such a card, and ``_TORCH_BACKEND`` overrides the choice.