Project NOMAD is an offline-first knowledge and education server. Wikipedia, thousands of books, courses, maps, and optional local AI, all running on hardware you own with no internet required.
TypeScript
fix(gpu): keep an existing AMD HSA override across reinstall and update
jakeaturnera1b899f49a5c
diff --git a/admin/app/services/docker_service.ts b/admin/app/services/docker_service.tsindex e0ef20c7..ca8fc0d2 100644--- a/admin/app/services/docker_service.ts+++ b/admin/app/services/docker_service.ts@@ -4,7 +4,7 @@ import logger from '@adonisjs/core/services/logger'import { inject } from '@adonisjs/core'import transmit from '@adonisjs/transmit/services/main'import { doResumableDownloadWithRetry } from '../utils/downloads.js'-import { mapGfxToHsaOverride } from '../utils/amd_hsa_override.js'+import { pickAmdHsaOverride } from '../utils/amd_hsa_override.js'import { join } from 'path'import os from 'node:os'import env from '#start/env'@@ -28,6 +28,9 @@ import { BROADCAST_CHANNELS } from '../../constants/broadcast.js'import { KIWIX_LIBRARY_CMD } from '../../constants/kiwix.js'import { DEFAULT_OLLAMA_CONTEXT_LENGTH } from '../../constants/ollama.js'+// Written by install_nomad.sh with the host AMD GPU's gfx target.+const AMD_GFX_MARKER_PATH = '/app/storage/.nomad-amd-gfx'+@inject()export class DockerService {public docker: Docker@@ -388,6 +391,17 @@ export class DockerService {if (container) {const dockerContainer = this.docker.getContainer(container.Id)+ if (serviceName === SERVICE_NAMES.OLLAMA) {+ // The recreate builds env from scratch, so capture a working HSA override+ // before this container, the only place it lives, is removed (#1377).+ try {+ const inspect = await dockerContainer.inspect()+ await this._adoptContainerHsaOverride(inspect.Config?.Env)+ } catch (error: any) {+ logger.warn(`[DockerService] Could not preserve the Ollama HSA override: ${error.message}`)+ }+ }+// Only try to stop if it's runningif (container.State === 'running') {this._broadcast(serviceName, 'stopping', `Stopping container...`)@@ -1555,7 +1569,9 @@ export class DockerService {* Exposed so GpuPassthroughRemediationProvider can tell whether a reinstall would* change the running container.*/- async getAmdHsaOverride(options: { quiet?: boolean } = {}): Promise<string | null> {+ async getAmdHsaOverride(+ options: { quiet?: boolean; containerEnv?: string[] | null } = {}+ ): Promise<string | null> {return this._resolveAmdHsaOverride(options)}@@ -1572,9 +1588,11 @@ export class DockerService {* Resolution order:* 1. KV `ai.amdHsaOverride` — manual user override; accepts 'none' (disable) or a semver-style value.* 2. Marker file `/app/storage/.nomad-amd-gfx` written by install_nomad.sh.- * 3. Default: none — let ROCm discover the GPU natively. Users on hardware that still+ * 3. The override the existing container runs with, when the caller passes its env (#1377).+ * 4. Default: none — let ROCm discover the GPU natively. Users on hardware that still* needs coercion can force a value via the KV. A hardcoded default gets more wrong* as ROCm adds native targets, so null is the safer forward-looking default.+ * The pure ordering lives in pickAmdHsaOverride (../utils/amd_hsa_override.ts).** Returns null when no override should be applied.*/@@ -1598,43 +1616,76 @@ export class DockerService {return pepper}- private async _resolveAmdHsaOverride({ quiet = false }: { quiet?: boolean } = {}): Promise<string | null> {- const manualRaw = await KVStore.getValue('ai.amdHsaOverride')- if (manualRaw !== null && manualRaw !== undefined && String(manualRaw).trim() !== '') {- const manual = String(manualRaw).trim().toLowerCase()- if (manual === 'none' || manual === 'off' || manual === 'false') {- if (!quiet) logger.info('[DockerService] HSA override disabled via ai.amdHsaOverride')- return null- }- if (/^\d+\.\d+\.\d+$/.test(manual)) {- if (!quiet) logger.info(`[DockerService] HSA override forced to ${manual} via ai.amdHsaOverride`)- return manual- }- if (!quiet) logger.warn(`[DockerService] Ignoring invalid ai.amdHsaOverride value: ${manualRaw}`)+ private async _resolveAmdHsaOverride({+ quiet = false,+ containerEnv,+ }: { quiet?: boolean; containerEnv?: string[] | null } = {}): Promise<string | null> {+ const manual = await KVStore.getValue('ai.amdHsaOverride')+ const markerGfx = await this._readAmdGfxMarker()+ const resolved = pickAmdHsaOverride({ manual, markerGfx, containerEnv })+ if (quiet) return resolved.value++ if (resolved.invalidManual !== undefined) {+ logger.warn(`[DockerService] Ignoring invalid ai.amdHsaOverride value: ${resolved.invalidManual}`)}-- try {- const gfx = (await readFile('/app/storage/.nomad-amd-gfx', 'utf8')).trim()- const mapped = this._mapGfxToHsaOverride(gfx)- if (!quiet) logger.info(`[DockerService] AMD gfx marker '${gfx}' → HSA override ${mapped ?? 'none'}`)- return mapped- } catch {- // Marker absent — most likely an existing install upgraded without re-running- // install_nomad.sh. Fall through to the default.+ switch (resolved.source) {+ case 'kv-disabled':+ logger.info('[DockerService] HSA override disabled via ai.amdHsaOverride')+ break+ case 'kv':+ logger.info(`[DockerService] HSA override forced to ${resolved.value} via ai.amdHsaOverride`)+ break+ case 'marker':+ logger.info(+ `[DockerService] AMD gfx marker '${markerGfx}' → HSA override ${resolved.value ?? 'none'}`+ )+ break+ case 'container':+ logger.info(+ `[DockerService] Keeping HSA override ${resolved.value} from the existing container`+ )+ break+ case 'default':+ logger.warn(+ `[DockerService] AMD GPU configured but no gfx marker (${AMD_GFX_MARKER_PATH}) and no ` ++ 'ai.amdHsaOverride KV; relying on native ROCm discovery. iGPUs not on the bundled rocblas ' ++ 'allowlist (e.g. 780M/gfx1103, 680M/gfx1035) will silently fall back to CPU. Set the ' ++ 'ai.amdHsaOverride KV (e.g. 11.0.0 for a 780M) and force-reinstall the AI service if so.'+ )+ break}+ return resolved.value+ }++ /**+ * Before a force reinstall removes nomad_ollama, persist the HSA override it runs with+ * when nothing else would supply one (#1377). The recreate builds env from scratch, so+ * without this an upgraded box with a hand-set override loses it. Persisting rather than+ * passing it along in memory keeps it through a reinstall that fails after removal, and+ * shows it in the Set GFX Override modal.+ */+ private async _adoptContainerHsaOverride(containerEnv: string[] | null | undefined): Promise<void> {+ const resolved = pickAmdHsaOverride({+ manual: await KVStore.getValue('ai.amdHsaOverride'),+ markerGfx: await this._readAmdGfxMarker(),+ containerEnv,+ })+ if (resolved.source !== 'container' || !resolved.value) return- if (!quiet) logger.warn(- '[DockerService] AMD GPU configured but no gfx marker (/app/storage/.nomad-amd-gfx) and no ' +- 'ai.amdHsaOverride KV; relying on native ROCm discovery. iGPUs not on the bundled rocblas ' +- 'allowlist (e.g. 780M/gfx1103, 680M/gfx1035) will silently fall back to CPU. Set the ' +- 'ai.amdHsaOverride KV (e.g. 11.0.0 for a 780M) and force-reinstall the AI service if so.'+ await KVStore.setValue('ai.amdHsaOverride', resolved.value)+ logger.info(+ `[DockerService] Persisted HSA override ${resolved.value} from the existing container to ai.amdHsaOverride`)- return null}- private _mapGfxToHsaOverride(gfx: string): string | null {- // Pure mapping lives in ../utils/amd_hsa_override.ts so it stays unit-testable.- return mapGfxToHsaOverride(gfx)+ private async _readAmdGfxMarker(): Promise<string | null> {+ try {+ return (await readFile(AMD_GFX_MARKER_PATH, 'utf8')).trim()+ } catch {+ // Marker absent: most likely an existing install upgraded without re-running+ // install_nomad.sh.+ return null+ }}/**@@ -1836,7 +1887,7 @@ export class DockerService {const baseEnv = inspectData.Config?.Env || []let finalEnv = baseEnvif (updatedAmdGpuConfigured) {- const hsaOverride = await this._resolveAmdHsaOverride()+ const hsaOverride = await this._resolveAmdHsaOverride({ containerEnv: baseEnv })finalEnv = baseEnv.filter((e: string) =>!e.startsWith('HSA_OVERRIDE_GFX_VERSION=') && !e.startsWith('OLLAMA_IGPU_ENABLE=')diff --git a/admin/app/services/ollama_compute.ts b/admin/app/services/ollama_compute.tsindex 81b61bfc..2f2b8925 100644--- a/admin/app/services/ollama_compute.ts+++ b/admin/app/services/ollama_compute.ts@@ -1,5 +1,5 @@import type Docker from 'dockerode'-import { mapGfxToHsaOverride } from '../utils/amd_hsa_override.js'+import { mapGfxToHsaOverride, readHsaOverrideFromEnv } from '../utils/amd_hsa_override.js'/*** Pure helpers for classifying which compute backend Ollama actually loaded,@@ -156,8 +156,7 @@ export function diffAmdOllamaConfig(if (!hasDevice(container, '/dev/kfd')) drift.push('/dev/kfd is not passed through')if (!hasDevice(container, '/dev/dri')) drift.push('/dev/dri is not passed through')- const currentOverride =- env.find((e) => e.startsWith('HSA_OVERRIDE_GFX_VERSION='))?.split('=')[1] ?? null+ const currentOverride = readHsaOverrideFromEnv(env)if (currentOverride !== desiredHsaOverride) {drift.push(`HSA_OVERRIDE_GFX_VERSION is ${currentOverride ?? 'unset'}, expected ${desiredHsaOverride ?? 'unset'}`@@ -180,7 +179,9 @@ export function parseAmdGfxTargetFromLogs(logText: string): string | null {/*** Why an AMD container expected on the GPU is running on CPU, in the shape- * GpuHealthStatus reports to the UI.+ * GpuHealthStatus reports to the UI. desiredHsaOverride must come from+ * DockerService.getAmdHsaOverride with this container's env, so the diff matches+ * what a reinstall would build.*/export function diagnoseAmdCpuFallback(container: OllamaContainerSnapshot,@@ -188,10 +189,11 @@ export function diagnoseAmdCpuFallback(desiredHsaOverride: string | null) {const gfx = parseAmdGfxTargetFromLogs(logText)- const current = (container.Config?.Env ?? [])- .find((e) => e.startsWith('HSA_OVERRIDE_GFX_VERSION='))- ?.split('=')[1]- const suggested = gfx ? mapGfxToHsaOverride(gfx) : null+ const current = readHsaOverrideFromEnv(container.Config?.Env)+ // With an override applied, Ollama logs the coerced target (gfx1100 for a 780M on+ // 11.0.0), which maps to "no override" and would suggest removing a working value.+ // The override the container carries is the better suggestion then (#1377).+ const suggested = current ?? (gfx ? mapGfxToHsaOverride(gfx) : null)return {amdReinstallWouldChange: diffAmdOllamaConfig(container, desiredHsaOverride).length > 0,...(gfx && { amdGfxTarget: gfx }),diff --git a/admin/app/services/system_service.ts b/admin/app/services/system_service.tsindex 73d627e2..2e620c7f 100644--- a/admin/app/services/system_service.ts+++ b/admin/app/services/system_service.ts@@ -623,7 +623,12 @@ export class SystemService {diagnoseAmdCpuFallback(ollama.inspect,ollamaLogs,- await this.dockerService.getAmdHsaOverride({ quiet: true })+ // Pass the container env so the diff matches what a reinstall would+ // really build, including an override it keeps from the container (#1377).+ await this.dockerService.getAmdHsaOverride({+ quiet: true,+ containerEnv: ollama.inspect.Config?.Env,+ })))}diff --git a/admin/app/utils/amd_hsa_override.ts b/admin/app/utils/amd_hsa_override.tsindex 14b74ef1..1bb4523c 100644--- a/admin/app/utils/amd_hsa_override.ts+++ b/admin/app/utils/amd_hsa_override.ts@@ -50,3 +50,57 @@ export function mapGfxToHsaOverride(gfx: string): string | null {// Unknown/newer target: prefer native discovery over a coercion that's likely wrong.return null}++const HSA_OVERRIDE_ENV_PREFIX = 'HSA_OVERRIDE_GFX_VERSION='+const HSA_OVERRIDE_VALUE_RE = /^\d+\.\d+\.\d+$/++/** The raw HSA_OVERRIDE_GFX_VERSION in a container env, or null when it is not set. */+export function readHsaOverrideFromEnv(env: string[] | null | undefined): string | null {+ const entry = (env ?? []).find((e) => e.startsWith(HSA_OVERRIDE_ENV_PREFIX))+ return entry ? entry.slice(HSA_OVERRIDE_ENV_PREFIX.length) : null+}++export type AmdHsaOverrideResolution = {+ value: string | null+ source: 'kv' | 'kv-disabled' | 'marker' | 'container' | 'default'+ /** Set when the KV held something unusable and was skipped. */+ invalidManual?: string+}++/**+ * Pick the HSA_OVERRIDE_GFX_VERSION an AMD install should apply. Resolution order:+ * 1. KV `ai.amdHsaOverride`: a version forces it, 'none'/'off'/'false' disables it.+ * 2. The gfx marker install_nomad.sh writes, mapped through mapGfxToHsaOverride. A+ * marker is authoritative even when it maps to none.+ * 3. The override the existing container already runs with (#1377). Upgraded installs+ * that got it by hand or from an older install path have neither 1 nor 2, and+ * dropping a working override would push the GPU back to CPU.+ * 4. None, letting ROCm discover the GPU natively.+ */+export function pickAmdHsaOverride(input: {+ manual: unknown+ markerGfx: string | null+ containerEnv?: string[] | null+}): AmdHsaOverrideResolution {+ let invalidManual: string | undefined+ if (input.manual !== null && input.manual !== undefined && String(input.manual).trim() !== '') {+ const manual = String(input.manual).trim().toLowerCase()+ if (manual === 'none' || manual === 'off' || manual === 'false') {+ return { value: null, source: 'kv-disabled' }+ }+ if (HSA_OVERRIDE_VALUE_RE.test(manual)) return { value: manual, source: 'kv' }+ invalidManual = String(input.manual)+ }+ const extra = invalidManual !== undefined ? { invalidManual } : {}++ if (input.markerGfx !== null) {+ return { value: mapGfxToHsaOverride(input.markerGfx), source: 'marker', ...extra }+ }++ const existing = readHsaOverrideFromEnv(input.containerEnv)?.trim()+ if (existing && HSA_OVERRIDE_VALUE_RE.test(existing)) {+ return { value: existing, source: 'container', ...extra }+ }++ return { value: null, source: 'default', ...extra }+}diff --git a/admin/tests/unit/amd_hsa_override.spec.ts b/admin/tests/unit/amd_hsa_override.spec.tsindex c33c825e..69272cae 100644--- a/admin/tests/unit/amd_hsa_override.spec.ts+++ b/admin/tests/unit/amd_hsa_override.spec.ts@@ -1,7 +1,11 @@import * as assert from 'node:assert/strict'import { test } from 'node:test'-import { mapGfxToHsaOverride } from '../../app/utils/amd_hsa_override.js'+import {+ mapGfxToHsaOverride,+ pickAmdHsaOverride,+ readHsaOverrideFromEnv,+} from '../../app/utils/amd_hsa_override.js'test('gfx1103 (Phoenix 780M) coerces to 11.0.0 — the #1076 regression', () => {// Not on the bundled rocblas allowlist; without this ollama drops it to CPU.@@ -30,3 +34,58 @@ test('unknown / newer targets default to native discovery (no override)', () =>assert.equal(mapGfxToHsaOverride('gfx9999'), null)assert.equal(mapGfxToHsaOverride(''), null)})++const OVERRIDE_ENV = ['OLLAMA_NO_CLOUD=1', 'HSA_OVERRIDE_GFX_VERSION=11.0.0']++test('readHsaOverrideFromEnv reads the override or null', () => {+ assert.equal(readHsaOverrideFromEnv(OVERRIDE_ENV), '11.0.0')+ assert.equal(readHsaOverrideFromEnv(['OLLAMA_NO_CLOUD=1']), null)+ assert.equal(readHsaOverrideFromEnv(null), null)+})++test('pickAmdHsaOverride: a KV version wins over the marker and container', () => {+ assert.deepEqual(pickAmdHsaOverride({ manual: '10.3.0', markerGfx: 'gfx1103', containerEnv: OVERRIDE_ENV }), {+ value: '10.3.0',+ source: 'kv',+ })+})++test('pickAmdHsaOverride: KV none disables even a container override', () => {+ assert.deepEqual(pickAmdHsaOverride({ manual: 'none', markerGfx: null, containerEnv: OVERRIDE_ENV }), {+ value: null,+ source: 'kv-disabled',+ })+})++test('pickAmdHsaOverride: a marker is authoritative even when it maps to none', () => {+ assert.deepEqual(pickAmdHsaOverride({ manual: null, markerGfx: 'gfx1151', containerEnv: OVERRIDE_ENV }), {+ value: null,+ source: 'marker',+ })+})++test('pickAmdHsaOverride keeps the container override with no KV or marker (#1377)', () => {+ assert.deepEqual(pickAmdHsaOverride({ manual: null, markerGfx: null, containerEnv: OVERRIDE_ENV }), {+ value: '11.0.0',+ source: 'container',+ })+ assert.deepEqual(pickAmdHsaOverride({ manual: '', markerGfx: null, containerEnv: OVERRIDE_ENV }), {+ value: '11.0.0',+ source: 'container',+ })+})++test('pickAmdHsaOverride ignores a malformed container override', () => {+ assert.deepEqual(+ pickAmdHsaOverride({ manual: null, markerGfx: null, containerEnv: ['HSA_OVERRIDE_GFX_VERSION=gfx1103'] }),+ { value: null, source: 'default' }+ )+})++test('pickAmdHsaOverride skips an invalid KV value and reports it', () => {+ assert.deepEqual(pickAmdHsaOverride({ manual: 'bogus', markerGfx: null, containerEnv: OVERRIDE_ENV }), {+ value: '11.0.0',+ source: 'container',+ invalidManual: 'bogus',+ })+})diff --git a/admin/tests/unit/ollama_compute.spec.ts b/admin/tests/unit/ollama_compute.spec.tsindex d47e9758..23bad2b5 100644--- a/admin/tests/unit/ollama_compute.spec.ts+++ b/admin/tests/unit/ollama_compute.spec.ts@@ -228,5 +228,21 @@ test('diagnoseAmdCpuFallback reports the current override and omits unknown fielassert.deepEqual(diagnoseAmdCpuFallback(ROCM_CONTAINER, '', '11.0.0'), {amdReinstallWouldChange: false,currentHsaOverride: '11.0.0',+ suggestedHsaOverride: '11.0.0',+ })+})++test('diagnoseAmdCpuFallback on the #1377 box: keeps the hand-set override, flags the iGPU flag', () => {+ // Override set by hand, OLLAMA_IGPU_ENABLE missing. The resolver keeps the container's+ // override, so the only drift is the iGPU flag and a reinstall preserves 11.0.0.+ const container = {+ ...ROCM_CONTAINER,+ Config: { ...ROCM_CONTAINER.Config, Env: ['OLLAMA_NO_CLOUD=1', 'HSA_OVERRIDE_GFX_VERSION=11.0.0'] },+ }+ assert.deepEqual(diffAmdOllamaConfig(container, '11.0.0'), ['OLLAMA_IGPU_ENABLE=1 is not set'])+ assert.deepEqual(diagnoseAmdCpuFallback(container, '', '11.0.0'), {+ amdReinstallWouldChange: true,+ currentHsaOverride: '11.0.0',+ suggestedHsaOverride: '11.0.0',})})