okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Two GTX 1080s are a working PC: an 8 GB card starts Off only beside a bigger card, and a PC whose only NVIDIA cards are Pascal uses them on the CUDA 12 engine (#3655)0351ecb11

main
15.2 KiB277 linesraw
1/**
2 * Main / Helper / Off for every graphics card. The same rules as strata_control/gpu_roles.py (the Terminal, setup and the server); both run
3 * tests/data/gpu_roles_vectors.json.
4 *
5 *  - Main:   the card that runs the LAST stage of the layer split (the output head, the draft layer and the check of its guesses). Exactly one.
6 *  - Helper: holds a share of the model, so more of it fits on graphics cards instead of being read from the drive.
7 *  - Off:    Strata does not touch it.
8 *
9 * The engine takes the cards in stage order (`gpu: [helper, ..., main]`, `gpu_order: "as_given"`), so Main is the LAST one.
10 */
11export type Role = 'main' | 'helper' | 'off';
12export const ROLES: Role[] = ['main', 'helper', 'off'];
13export type Roles = Record<number, Role>;
14
15export interface RoleCard {
16  index: number;
17  name: string;
18  vram_gb: number;
19  /** SMs x clock (or the AMD equivalent): only the order between cards matters. */
20  speed?: number;
21  usable?: boolean;
22  problem?: string | null;
23  vendor?: string;
24  uma?: boolean;
25  integrated?: boolean;
26  unified_gb?: number;
27  /** PCI bus id when known: used to notice a renumbering. */
28  bus?: string;
29}
30
31export const OFF_AT_OR_BELOW_GB = 8;
32const SAME_SPEED = 1.05;
33const MEMORY_GUARD_SPEED = 0.5;
34const MIN_CARD_GB = 4;
35const SPLIT_CARD_OVERHEAD_GB = 2;
36export const CPU_ONLY_LINE = 'Performance is degraded on CPU only.';
37export const NO_CARD_LINE = 'This engine needs a graphics card to start. Turn one on.';
38
39const mem = (c: RoleCard) => Number(c.vram_gb) || 0;
40const speed = (c: RoleCard) => (typeof c.speed === 'number' && c.speed > 0 ? c.speed : 0);
41const shares = (c: RoleCard) => !!(c.integrated || c.uma || c.unified_gb || c.vendor === 'apple');
42const canRun = (c: RoleCard) => c.usable !== false;
43const rnd = (n: number) => Math.round(n);
44
45export function shortName(c: RoleCard): string {
46  let n = String(c.name || `GPU ${c.index + 1}`);
47  for (const junk of ['NVIDIA GeForce ', 'NVIDIA ', 'GeForce ', 'AMD Radeon ', 'AMD ', 'Intel(R) ', 'Intel ']) if (n.startsWith(junk)) { n = n.slice(junk.length); break; }
48  return n.trim();
49}
50/** The number the screens show: GPU 1 is card 0. */
51export const gpuLabel = (c: RoleCard) => `GPU ${c.index + 1}`;
52
53/** The cards shown as rows: every card the engine's make can name, in card order. */
54export function rows<T extends RoleCard>(cards: T[] | null | undefined, vendor?: string | null): T[] {
55  const list = cards ?? [];
56  const make = vendor || pickVendor(list);
57  const mine = make ? list.filter(c => !c.vendor || c.vendor === make) : list;
58  return [...mine].sort((a, b) => a.index - b.index);
59}
60function pickVendor(cards: RoleCard[]): string | null {
61  const makes = new Set(cards.filter(c => canRun(c) && c.vendor).map(c => c.vendor as string));
62  if (makes.size <= 1) return [...makes][0] ?? null;
63  return makes.has('nvidia') ? 'nvidia' : cards[0]?.vendor ?? null;
64}
65
66function eligible(cs: RoleCard[]): RoleCard[] {
67  const real = cs.filter(c => canRun(c) && !shares(c) && mem(c) >= MIN_CARD_GB);
68  return real.length ? real : cs.filter(canRun);
69}
70
71export type MainWhy = 'only' | 'faster' | 'same' | 'memory' | 'none';
72
73export function pickMain(cs: RoleCard[]): { main: RoleCard | null; why: MainWhy } {
74  const pool = eligible(cs);
75  if (!pool.length) return { main: null, why: 'none' };
76  if (pool.length === 1) return { main: pool[0], why: 'only' };
77  const top = Math.max(...pool.map(speed));
78  const group = top > 0 ? pool.filter(c => speed(c) * SAME_SPEED >= top) : [...pool];
79  const byMem = (a: RoleCard, b: RoleCard) => rnd(mem(b)) - rnd(mem(a)) || a.index - b.index;
80  let main = [...group].sort(byMem)[0];
81  let why: MainWhy = group.length === 1 ? 'faster' : 'same';
82  if (group.length > 1 && new Set(group.map(c => `${c.name}|${rnd(mem(c))}`)).size === 1) main = [...group].sort((a, b) => b.index - a.index)[0]; // identical cards: the HIGHEST number is Main
83  if (top <= 0 && new Set(pool.map(c => rnd(mem(c)))).size > 1) why = 'memory';
84  const bigger = pool.filter(c => rnd(mem(c)) > rnd(mem(main)) && (top <= 0 || speed(c) >= MEMORY_GUARD_SPEED * top));
85  if (bigger.length) { main = [...bigger].sort(byMem)[0]; why = 'memory'; }
86  return { main, why };
87}
88
89export type OffWhy = 'cannot_run' | 'igpu' | 'small' | 'helper';
90export interface Recommendation { roles: Roles; main: number | null; why: MainWhy; reasons: Record<number, MainWhy | OffWhy> }
91
92/** The best card is Main; every other card starts as Helper, EXCEPT a card with 8 GB or less when a bigger card is there (or it has under 4 GB), built-in graphics beside a real card, and a card the engine cannot run: those start Off. */
93export function recommend(cards: RoleCard[] | null | undefined, vendor?: string | null): Recommendation {
94  const cs = rows(cards, vendor);
95  const { main, why } = pickMain(cs);
96  const roles: Roles = {}, reasons: Recommendation['reasons'] = {};
97  // An 8 GB card is a poor Helper beside a bigger card, but a perfectly good one when 8 GB is all there is: two GTX 1080s are a working
98  // 16 GB pool (#3655). A card with 8 GB or less starts Off only when a bigger usable card is there, or when it is too small to help.
99  const hasBigger = cs.some(c => canRun(c) && !shares(c) && rnd(mem(c)) > OFF_AT_OR_BELOW_GB);
100  for (const c of cs) {
101    const i = c.index;
102    if (main && c === main) { roles[i] = 'main'; reasons[i] = why; }
103    else if (!canRun(c)) { roles[i] = 'off'; reasons[i] = 'cannot_run'; }
104    else if (shares(c) && main) { roles[i] = 'off'; reasons[i] = 'igpu'; }
105    else if (rnd(mem(c)) <= OFF_AT_OR_BELOW_GB && (hasBigger || mem(c) < MIN_CARD_GB)) { roles[i] = 'off'; reasons[i] = 'small'; }
106    else { roles[i] = 'helper'; reasons[i] = 'helper'; }
107  }
108  return { roles, main: main ? main.index : null, why, reasons };
109}
110
111const on = (roles: Roles) => Object.keys(roles).map(Number).filter(i => roles[i] !== 'off');
112const byNumber = (roles: Roles) => Object.keys(roles).map(Number).sort((a, b) => a - b);
113
114/** Exactly one Main among the cards that are on; a lone card that is on is Main. */
115export function normalize(roles: Roles, cards: RoleCard[]): Roles {
116  const cs = new Map(cards.map(c => [c.index, c]));
117  const out: Roles = {};
118  for (const i of byNumber(roles)) if (cs.has(i)) out[i] = ROLES.includes(roles[i]) ? roles[i] : 'off';
119  const onList = on(out), mains = onList.filter(i => out[i] === 'main');
120  if (onList.length && !mains.length) {
121    const best = [...onList].sort((a, b) => speed(cs.get(b)!) - speed(cs.get(a)!) || rnd(mem(cs.get(b)!)) - rnd(mem(cs.get(a)!)) || a - b)[0];
122    out[best] = 'main';
123  }
124  for (const extra of mains.slice(1)) out[extra] = 'helper';
125  if (onList.length === 1) out[onList[0]] = 'main';
126  return out;
127}
128
129export interface RoleChange { roles: Roles; note: string | null }
130
131/** One click: the new roles and a code for the quiet line (old_main_helper:<i>, promoted:<i>, only_main). */
132export function setRole(roles: Roles, cards: RoleCard[], idx: number, role: Role): RoleChange {
133  const cs = new Map(cards.map(c => [c.index, c]));
134  const out: Roles = { ...roles };
135  let note: string | null = null;
136  if (!cs.has(idx) || !ROLES.includes(role)) return { roles: out, note };
137  const ids = byNumber(out);
138  const fastest = (list: number[]) => [...list].sort((a, b) => speed(cs.get(b)!) - speed(cs.get(a)!) || a - b);
139  if (role === 'main') {
140    const old = ids.find(i => i !== idx && out[i] === 'main');
141    out[idx] = 'main';
142    if (old !== undefined) { out[old] = 'helper'; note = `old_main_helper:${old}`; }
143  } else if (role === 'helper') {
144    if (out[idx] === 'main') {
145      const others = fastest(ids.filter(i => i !== idx && out[i] === 'helper'));
146      if (!others.length) return { roles: out, note: 'only_main' };
147      out[idx] = 'helper'; out[others[0]] = 'main'; note = `promoted:${others[0]}`;
148    } else out[idx] = 'helper';
149  } else {
150    const wasMain = out[idx] === 'main';
151    out[idx] = 'off';
152    if (wasMain) {
153      const next = fastest(ids.filter(i => out[i] === 'helper'));
154      if (next.length) { out[next[0]] = 'main'; note = `promoted:${next[0]}`; }
155    }
156  }
157  const onList = on(out);
158  if (onList.length === 1) out[onList[0]] = 'main';
159  else if (onList.length && !onList.some(i => out[i] === 'main')) out[onList[0]] = 'main';
160  return { roles: out, note };
161}
162
163/** The engine's card list: Helpers (slowest first, ties by number), then the Main card LAST; Off cards left out. */
164export function order(roles: Roles, cards: RoleCard[]): number[] {
165  const cs = new Map(cards.map(c => [c.index, c]));
166  const r = normalize(roles, cards);
167  const helpers = byNumber(r).filter(i => r[i] === 'helper').sort((a, b) => speed(cs.get(a)!) - speed(cs.get(b)!) || a - b);
168  return [...helpers, ...byNumber(r).filter(i => r[i] === 'main')];
169}
170
171export interface RoleMirror { gpu_roles: Record<string, Role>; gpu: number | number[]; gpu_order?: 'as_given'; gpu_none?: true; gpu_cards: Record<string, string> }
172/** What a writer stores: "gpu_roles" plus the legacy mirror older engines and the Monitor read. Nothing on: "gpu": [] and "gpu_none": true. */
173export function mirror(roles: Roles, cards: RoleCard[]): RoleMirror {
174  const r = normalize(roles, cards), lst = order(r, cards);
175  const out: RoleMirror = { gpu_roles: Object.fromEntries(byNumber(r).map(i => [String(i), r[i]])), gpu: [], gpu_cards: {} };
176  if (lst.length) { out.gpu = lst.length === 1 ? lst[0] : lst; out.gpu_order = 'as_given'; } else out.gpu_none = true;
177  for (const c of cards) if (c.index in r) out.gpu_cards[String(c.index)] = [shortName(c), c.bus ?? ''].filter(Boolean).join('|');
178  return out;
179}
180
181/** Roles of an old "gpu" setting, for display: the LAST card of the engine's order is Main, earlier ones Helpers, unlisted cards Off. */
182export function fromLegacy(gpu: unknown, cards: RoleCard[], gpuOrder?: string | null): Roles {
183  const cs = new Map(cards.map(c => [c.index, c]));
184  let items: number[] = Array.isArray(gpu) ? gpu.map(Number) : gpu === null || gpu === undefined || gpu === '' ? [] : String(gpu).split(',').filter(x => x.trim() !== '').map(Number);
185  items = items.filter(i => cs.has(i));
186  if (!items.length) return { ...recommend(cards).roles };
187  if (items.length > 1 && gpuOrder !== 'as_given') {
188    const sp = items.map(i => speed(cs.get(i)!));
189    if (sp.every(x => x > 0) && Math.max(...sp) >= SAME_SPEED * Math.min(...sp)) items = [...items].sort((a, b) => speed(cs.get(a)!) - speed(cs.get(b)!));
190  }
191  const roles: Roles = {};
192  for (const c of cards) roles[c.index] = 'off';
193  for (const i of items.slice(0, -1)) roles[i] = 'helper';
194  roles[items[items.length - 1]] = 'main';
195  return roles;
196}
197
198export const sameRoles = (a: Roles, b: Roles) => { const ka = byNumber(a), kb = byNumber(b); return ka.length === kb.length && ka.every((k, n) => k === kb[n] && a[k] === b[k]); };
199
200export interface RoleWarning { code: 'igpu_main' | 'cannot_run' | 'low_memory' | 'cpu_only'; card: number | null; text: string; fix: { card: number; role: Role } | null }
201
202/** One short line each, only what a person could not know. Never blocking. */
203export function warnings(roles: Roles, cards: RoleCard[], opts: { spillGb?: number; engineRunsCpuOnly?: boolean } = {}): RoleWarning[] {
204  const cs = new Map(cards.map(c => [c.index, c]));
205  const out: RoleWarning[] = [];
206  for (const i of byNumber(roles)) {
207    const c = cs.get(i), role = roles[i];
208    if (!c || role === 'off') continue;
209    if (!canRun(c)) out.push({ code: 'cannot_run', card: i, text: `${shortName(c)} cannot run Strata.`, fix: { card: i, role: 'off' } });
210    else if (role === 'main' && shares(c) && cards.some(x => !shares(x) && canRun(x))) {
211      const real = cards.filter(x => !shares(x) && canRun(x)).sort((a, b) => speed(b) - speed(a) || mem(b) - mem(a) || a.index - b.index)[0];
212      out.push({ code: 'igpu_main', card: i, text: `${shortName(c)} is built-in graphics; it is slow as Main.`, fix: { card: real.index, role: 'main' } });
213    }
214  }
215  if (!on(roles).length) out.push({ code: 'cpu_only', card: null, text: opts.engineRunsCpuOnly ? CPU_ONLY_LINE : NO_CARD_LINE, fix: null });
216  else if ((opts.spillGb ?? 0) >= 1) out.push({ code: 'low_memory', card: null, text: `Not enough memory for this setup: about ${Math.round(opts.spillGb!)} GB is read from the drive.`, fix: null });
217  return out;
218}
219
220/** The graphics memory the cards that are on give for the model (an extra card costs its own dense layers); 0 when all are off. */
221export function vramOn(roles: Roles, cards: RoleCard[]): number {
222  const cs = new Map(cards.map(c => [c.index, c]));
223  const onCards = on(roles).map(i => cs.get(i)).filter((c): c is RoleCard => !!c && !shares(c));
224  return Math.max(0, onCards.reduce((n, c) => n + mem(c), 0) - SPLIT_CARD_OVERHEAD_GB * Math.max(0, onCards.length - 1));
225}
226
227export function noteText(code: string | null, cards: RoleCard[]): string {
228  if (!code) return '';
229  const [kind, arg] = code.split(':');
230  const c = arg !== undefined ? cards.find(x => x.index === Number(arg)) : undefined;
231  const name = c ? shortName(c) : 'That card';
232  if (kind === 'old_main_helper') return `${name} is now a Helper.`;
233  if (kind === 'promoted') return `${name} is now Main.`;
234  if (kind === 'only_main') return 'The only card that is on has to be Main.';
235  return '';
236}
237
238/** The one plain line above the cards. */
239export function sentence(cards: RoleCard[] | null | undefined, vendor?: string | null): string {
240  const cs = rows(cards, vendor), rec = recommend(cards, vendor);
241  if (rec.main === null) return 'No graphics card that Strata can use was found.';
242  const byi = new Map(cs.map(c => [c.index, c]));
243  const m = byi.get(rec.main)!;
244  if (cs.length === 1) return `Strata will use your ${shortName(m)}.`;
245  const why = { same: 'the cards are alike', memory: 'it has more memory', faster: 'it is faster', only: 'it is the only card', none: '' }[rec.why];
246  let s = `${shortName(m)} is Main: ${why}.`;
247  const helpers = byNumber(rec.roles).filter(i => rec.roles[i] === 'helper').map(i => shortName(byi.get(i)!));
248  if (helpers.length) s += ` ${helpers.join(' and ')} ${helpers.length > 1 ? 'help' : 'helps'}.`;
249  for (const i of byNumber(rec.roles)) if (rec.roles[i] === 'off') {
250    const code = rec.reasons[i], c = byi.get(i)!;
251    s += ` ${shortName(c)} starts Off: ${code === 'cannot_run' ? 'Strata cannot run it.' : code === 'igpu' ? 'built-in graphics.' : `${OFF_AT_OR_BELOW_GB} GB or less.`}`;
252  }
253  return s;
254}
255
256/** `Main: GPU 2 RTX 4070 Ti. Helper: GPU 1 RTX 3060.` */
257export function describe(roles: Roles, cards: RoleCard[]): string {
258  const cs = new Map(cards.map(c => [c.index, c]));
259  const parts: string[] = [];
260  for (const [role, word] of [['main', 'Main'], ['helper', 'Helper'], ['off', 'Off']] as const) {
261    const names = byNumber(roles).filter(i => roles[i] === role).map(i => (cs.has(i) ? `GPU ${i + 1} ${shortName(cs.get(i)!)}` : `GPU ${i + 1}`));
262    if (names.length) parts.push(`${word}: ${names.join(', ')}.`);
263  }
264  return parts.join(' ');
265}
266
267/** A saved "gpu_roles" object -> roles; null when it is not one. */
268export function parseSaved(value: unknown): Roles | null {
269  if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
270  const out: Roles = {};
271  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
272    if (!/^\d+$/.test(k.trim()) || !ROLES.includes(String(v).toLowerCase() as Role)) return null;
273    out[Number(k)] = String(v).toLowerCase() as Role;
274  }
275  if (!Object.keys(out).length || Object.values(out).filter(r => r === 'main').length > 1) return null;
276  return out;
277}