File size: 9,219 Bytes
7e173d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// SPDX-License-Identifier: MIT
// drAIML WebGPU helper · the check. It asks this browser for a WebGPU adapter, describes the card, and proves it can
// compute by running one small shader and checking every value it returns. The extension popup and the plain web page
// (webgpu/extension/popup.html served by the drAIML Space) both use it, so the page works where no extension can be
// installed (Safari, phones).

export const VERSION = "0.1.0";

export function browserName() {
  const ua = navigator.userAgent;
  if (navigator.brave) return "brave";
  if (/Edg\//.test(ua)) return "edge";
  if (/OPR\//.test(ua)) return "opera";
  if (/Vivaldi/.test(ua)) return "vivaldi";
  if (/Firefox\//.test(ua)) return "firefox";
  if (/Chrome\//.test(ua)) return "chrome";
  if (/Safari\//.test(ua)) return "safari";
  return "other";
}

export function osName() {
  const p = ((navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || "").toLowerCase();
  const ua = navigator.userAgent;
  if (/android/i.test(ua)) return "android";
  if (/iphone|ipad|ipod/i.test(ua)) return "ios";
  if (p.includes("win")) return "windows";
  if (p.includes("mac")) return "macos";
  if (p.includes("cros") || /CrOS/.test(ua)) return "chromeos";
  if (p.includes("linux") || /Linux/.test(ua)) return "linux";
  return "other";
}

export const isChromium = (b) => ["chrome", "brave", "edge", "opera", "vivaldi"].includes(b);

async function infoOf(a) {
  let i = a.info;
  if (!i && a.requestAdapterInfo) { try { i = await a.requestAdapterInfo(); } catch { i = null; } }
  i = i || {};
  return { vendor: i.vendor || "", architecture: i.architecture || "", device: i.device || "", description: i.description || "",
           fallback: !!(i.isFallbackAdapter ?? a.isFallbackAdapter),
           features: [...(a.features || [])].sort(),
           limits: { maxBufferSize: a.limits.maxBufferSize, maxStorageBufferBindingSize: a.limits.maxStorageBufferBindingSize,
                     maxComputeWorkgroupSizeX: a.limits.maxComputeWorkgroupSizeX, maxComputeInvocationsPerWorkgroup: a.limits.maxComputeInvocationsPerWorkgroup } };
}

/** Run out[i] = in[i] * 3 + 1 over 65,536 values on the card and check every one. */
async function computeTest(adapter) {
  const t0 = performance.now();
  const device = await adapter.requestDevice();
  let lost = null; device.lost.then((l) => { lost = l.message || l.reason; });
  try {
    const n = 65536, bytes = n * 4;
    const input = new Uint32Array(n); for (let i = 0; i < n; i++) input[i] = i;
    const src = device.createBuffer({ size: bytes, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
    const dst = device.createBuffer({ size: bytes, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });
    const read = device.createBuffer({ size: bytes, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
    device.queue.writeBuffer(src, 0, input);
    const module = device.createShaderModule({ code: `
      @group(0) @binding(0) var<storage, read> a: array<u32>;
      @group(0) @binding(1) var<storage, read_write> b: array<u32>;
      @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {
        if (id.x < arrayLength(&a)) { b[id.x] = a[id.x] * 3u + 1u; }
      }` });
    const pipeline = device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" } });
    const bind = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
      { binding: 0, resource: { buffer: src } }, { binding: 1, resource: { buffer: dst } }] });
    const enc = device.createCommandEncoder(), pass = enc.beginComputePass();
    pass.setPipeline(pipeline); pass.setBindGroup(0, bind); pass.dispatchWorkgroups(n / 64); pass.end();
    enc.copyBufferToBuffer(dst, 0, read, 0, bytes);
    device.queue.submit([enc.finish()]);
    await read.mapAsync(GPUMapMode.READ);
    const out = new Uint32Array(read.getMappedRange().slice(0));
    read.unmap();
    let wrong = 0; for (let i = 0; i < n; i++) if (out[i] !== i * 3 + 1) wrong++;
    return { ok: wrong === 0 && !lost, values: n, wrong, ms: Math.round(performance.now() - t0), lost };
  } catch (e) {
    return { ok: false, error: String(e && e.message || e), lost, ms: Math.round(performance.now() - t0) };
  } finally { device.destroy(); }
}

/** The whole check. verdict: ready · software (works, but on the CPU) · broken · no-adapter · missing. */
export async function checkWebGPU() {
  const r = { version: VERSION, browser: browserName(), os: osName(), secure: window.isSecureContext, api: "gpu" in navigator,
              adapters: {}, card: null, compute: null, verdict: "missing", at: new Date().toISOString() };
  if (!r.api) return r;
  for (const power of ["low-power", "high-performance"]) {
    try { const a = await navigator.gpu.requestAdapter({ powerPreference: power }); r.adapters[power] = a ? await infoOf(a) : null; }
    catch (e) { r.adapters[power] = { error: String(e && e.message || e) }; }
  }
  let a = null;
  try { a = (await navigator.gpu.requestAdapter({ powerPreference: "low-power" })) || (await navigator.gpu.requestAdapter()); } catch { a = null; }
  if (!a) { r.verdict = "no-adapter"; return r; }
  r.card = await infoOf(a);
  r.compute = await computeTest(a);
  r.verdict = !r.compute.ok ? "broken" : r.card.fallback ? "software" : "ready";
  return r;
}

const FLAGS = (scheme) => ({
  unsafe: `${scheme}://flags/#enable-unsafe-webgpu`,
  vulkan: `${scheme}://flags/#enable-vulkan`,
  blocklist: `${scheme}://flags/#ignore-gpu-blocklist`,
  gpu: `${scheme}://gpu`,
});
export const scheme = (b) => ({ brave: "brave", edge: "edge", opera: "opera", vivaldi: "vivaldi" }[b] || "chrome");

/** What to do next, for this browser, system and verdict: [{text, link?, copy?}] steps. */
export function advice(r) {
  const b = r.browser, os = r.os, steps = [];
  if (r.verdict === "ready") {
    return { title: "WebGPU works here", summary: `Your ${label(r.card)} passed the compute test. drAIML can use it for Bonsai and you can lend it from the ❤️ Donate panel.`, steps };
  }
  if (!r.secure) steps.push({ text: "WebGPU needs a secure page (https or localhost). Open drAIML over https." });
  if (isChromium(b)) {
    const f = FLAGS(scheme(b));
    if (r.verdict === "software") steps.push({ text: "Only a software (CPU) adapter answered. Your real card is probably blocklisted: enable “Override software rendering list”, then relaunch.", link: f.blocklist });
    else if (r.verdict === "broken") steps.push({ text: "An adapter answered but the compute test failed. Update your graphics driver, then check the WebGPU lines on the GPU page.", link: f.gpu });
    else {
      steps.push({ text: "Enable “Unsafe WebGPU Support”. It switches WebGPU on where this browser has not yet turned it on by default.", link: f.unsafe });
      if (os === "linux") {
        steps.push({ text: "On Linux, also enable “Vulkan”. WebGPU runs on Vulkan there.", link: f.vulkan });
        steps.push({ text: "Make sure Vulkan drivers are installed (Debian/Ubuntu):", copy: "sudo apt install mesa-vulkan-drivers vulkan-tools && vulkaninfo --summary" });
      }
      steps.push({ text: "If it still finds no card, enable “Override software rendering list”.", link: f.blocklist });
    }
    steps.push({ text: "Relaunch the browser, then run this check again." });
    steps.push({ text: "Or let the installer set those flags for you (close the browser first):", copy: os === "windows"
      ? "powershell -ExecutionPolicy Bypass -File webgpu-enable.ps1" : "bash webgpu-enable.sh" });
  } else if (b === "firefox") {
    steps.push({ text: "Recent Firefox turns WebGPU on for Windows. Elsewhere, open about:config, set dom.webgpu.enabled to true, then restart Firefox.", copy: "about:config" });
    steps.push({ text: "Or let the installer add it to your Firefox profiles (close Firefox first):", copy: os === "windows"
      ? "powershell -ExecutionPolicy Bypass -File webgpu-enable.ps1 -Firefox" : "bash webgpu-enable.sh --firefox" });
  } else if (b === "safari") {
    steps.push({ text: "Safari 26 has WebGPU on. In older Safari: Develop → Feature Flags → WebGPU, then reload." });
  } else {
    steps.push({ text: "Use a recent Chrome, Edge, Brave or Firefox. WebGPU is not available in this browser." });
  }
  steps.push({ text: "Without WebGPU nothing breaks: drAIML runs Bonsai on your processor, just more slowly." });
  const title = { missing: "This browser has WebGPU switched off", "no-adapter": "WebGPU is on, but no graphics card answered",
                  software: "WebGPU only found a software adapter", broken: "WebGPU found a card, but it failed the test" }[r.verdict];
  return { title, summary: `${pretty(b)} on ${pretty(os)}.`, steps };
}

export const label = (c) => c ? [c.vendor, c.architecture, c.description].filter(Boolean).join(" · ") || "graphics card" : "graphics card";
const pretty = (s) => ({ chrome: "Chrome", brave: "Brave", edge: "Edge", opera: "Opera", vivaldi: "Vivaldi", firefox: "Firefox", safari: "Safari",
  linux: "Linux", windows: "Windows", macos: "macOS", chromeos: "ChromeOS", android: "Android", ios: "iOS" }[s] || s);