Spaces:
Running
Running
Download packages/runtime/src/device.ts from leventkoldas/botpsy-0.8b-web: direct link, hf CLI and curl.
- Browser
- Download file 7.85 kB
-
https://huggingface.co/spaces/leventkoldas/botpsy-0.8b-web/resolve/main/packages/runtime/src/device.ts
- Command line
-
hf download hf://spaces/leventkoldas/botpsy-0.8b-web/packages/runtime/src/device.ts
-
curl -L -o device.ts https://huggingface.co/spaces/leventkoldas/botpsy-0.8b-web/resolve/main/packages/runtime/src/device.ts
7.85 kB
| import type { AdapterReport, DeviceCapabilities } from '@botpsy/protocol'; | |
| export interface AdmissionOptions { | |
| powerPreference?: GPUPowerPreference; | |
| allowSoftwareAdapter?: boolean; | |
| diagnostic?: boolean; | |
| } | |
| export const REQUIRED_GPU_FEATURES = ['shader-f16', 'subgroups', 'subgroup-size-control'] as const; | |
| export const REQUIRED_WGSL_FEATURES = [ | |
| 'immediate_address_space', | |
| 'buffer_view', | |
| 'subgroup_id', | |
| 'subgroup_uniformity', | |
| ] as const; | |
| export function adapterReport(adapter: GPUAdapter): AdapterReport { | |
| const info = adapter.info; | |
| return { | |
| vendor: info?.vendor ?? '', | |
| architecture: info?.architecture ?? '', | |
| device: info?.device ?? '', | |
| description: info?.description ?? '', | |
| subgroupMinSize: (info as unknown as { subgroupMinSize?: number })?.subgroupMinSize ?? 0, | |
| subgroupMaxSize: (info as unknown as { subgroupMaxSize?: number })?.subgroupMaxSize ?? 0, | |
| isFallbackAdapter: 'isFallbackAdapter' in adapter ? Boolean(adapter.isFallbackAdapter) : false, | |
| }; | |
| } | |
| export async function probeCapabilities(): Promise<{ | |
| capabilities: DeviceCapabilities; | |
| adapter: GPUAdapter | null; | |
| missing: string[]; | |
| }> { | |
| const missing: string[] = []; | |
| if (!('gpu' in navigator) || !navigator.gpu) { | |
| return { | |
| capabilities: emptyCapabilities(), | |
| adapter: null, | |
| missing: ['WebGPU'], | |
| }; | |
| } | |
| const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); | |
| if (!adapter) { | |
| return { capabilities: emptyCapabilities(), adapter: null, missing: ['hardware WebGPU adapter'] }; | |
| } | |
| const features = [...adapter.features]; | |
| for (const feature of REQUIRED_GPU_FEATURES) { | |
| if (!adapter.features.has(feature)) missing.push(`feature:${feature}`); | |
| } | |
| const wgsl = [...navigator.gpu.wgslLanguageFeatures]; | |
| for (const feature of REQUIRED_WGSL_FEATURES) { | |
| if (!navigator.gpu.wgslLanguageFeatures.has(feature)) missing.push(`wgsl:${feature}`); | |
| } | |
| if (!globalThis.isSecureContext) missing.push('secure-context'); | |
| const limits: Record<string, number> = {}; | |
| for (const key of [ | |
| 'maxStorageBufferBindingSize', | |
| 'maxBufferSize', | |
| 'maxComputeWorkgroupStorageSize', | |
| 'maxComputeInvocationsPerWorkgroup', | |
| 'maxComputeWorkgroupSizeX', | |
| 'maxStorageBuffersPerShaderStage', | |
| 'maxImmediateSize', | |
| 'minSubgroupSize', | |
| 'maxSubgroupSize', | |
| ] as const) { | |
| const value = (adapter.limits as unknown as Record<string, number>)[key]; | |
| if (typeof value === 'number') limits[key] = value; | |
| } | |
| let quota: { quota: number; usage: number } | null = null; | |
| try { | |
| if (navigator.storage?.estimate) { | |
| const estimate = await navigator.storage.estimate(); | |
| quota = { quota: estimate.quota ?? 0, usage: estimate.usage ?? 0 }; | |
| } | |
| } catch { | |
| quota = null; | |
| } | |
| const capabilities: DeviceCapabilities = { | |
| webgpu: true, | |
| secureContext: globalThis.isSecureContext, | |
| crossOriginIsolated: globalThis.crossOriginIsolated, | |
| adapter: adapterReport(adapter), | |
| features, | |
| wgslLanguageFeatures: wgsl, | |
| limits, | |
| timestampQuery: adapter.features.has('timestamp-query'), | |
| subgroups: adapter.features.has('subgroups'), | |
| subgroupSizeControl: adapter.features.has('subgroup-size-control'), | |
| immediateAddressSpace: navigator.gpu.wgslLanguageFeatures.has('immediate_address_space'), | |
| bufferView: navigator.gpu.wgslLanguageFeatures.has('buffer_view'), | |
| subgroupUniformity: navigator.gpu.wgslLanguageFeatures.has('subgroup_uniformity'), | |
| subgroupId: navigator.gpu.wgslLanguageFeatures.has('subgroup_id'), | |
| shaderF16: adapter.features.has('shader-f16'), | |
| opfs: typeof navigator.storage?.getDirectory === 'function', | |
| indexedDb: typeof indexedDB !== 'undefined', | |
| sharedArrayBuffer: typeof SharedArrayBuffer !== 'undefined', | |
| webLocks: typeof navigator.locks !== 'undefined', | |
| broadcastChannel: typeof BroadcastChannel !== 'undefined', | |
| serviceWorker: 'serviceWorker' in navigator, | |
| screenWakeLock: 'wakeLock' in navigator, | |
| deviceMemoryGiB: | |
| typeof (navigator as unknown as { deviceMemory?: number }).deviceMemory === 'number' | |
| ? (navigator as unknown as { deviceMemory: number }).deviceMemory | |
| : null, | |
| storageQuotaBytes: quota?.quota ?? null, | |
| storageUsageBytes: quota?.usage ?? null, | |
| }; | |
| return { capabilities, adapter, missing }; | |
| } | |
| function emptyCapabilities(): DeviceCapabilities { | |
| return { | |
| webgpu: false, | |
| secureContext: globalThis.isSecureContext ?? false, | |
| crossOriginIsolated: globalThis.crossOriginIsolated ?? false, | |
| adapter: null, | |
| features: [], | |
| wgslLanguageFeatures: [], | |
| limits: {}, | |
| timestampQuery: false, | |
| subgroups: false, | |
| subgroupSizeControl: false, | |
| immediateAddressSpace: false, | |
| bufferView: false, | |
| subgroupUniformity: false, | |
| subgroupId: false, | |
| shaderF16: false, | |
| opfs: false, | |
| indexedDb: false, | |
| sharedArrayBuffer: false, | |
| webLocks: false, | |
| broadcastChannel: false, | |
| serviceWorker: false, | |
| screenWakeLock: false, | |
| deviceMemoryGiB: null, | |
| storageQuotaBytes: null, | |
| storageUsageBytes: null, | |
| }; | |
| } | |
| export async function requestEngineDevice( | |
| adapter: GPUAdapter, | |
| options: AdmissionOptions = {}, | |
| ): Promise<{ device: GPUDevice; subgroupSize: number; limits: Record<string, number> }> { | |
| const requiredFeatures: GPUFeatureName[] = []; | |
| for (const feature of REQUIRED_GPU_FEATURES) { | |
| if (adapter.features.has(feature)) requiredFeatures.push(feature as GPUFeatureName); | |
| } | |
| if (adapter.features.has('timestamp-query')) requiredFeatures.push('timestamp-query' as GPUFeatureName); | |
| const requiredLimits: Record<string, number> = { | |
| maxStorageBuffersPerShaderStage: Math.min(8, adapter.limits.maxStorageBuffersPerShaderStage), | |
| maxStorageBufferBindingSize: Math.min(64 * 1024 * 1024, adapter.limits.maxStorageBufferBindingSize), | |
| maxBufferSize: Math.min(64 * 1024 * 1024, adapter.limits.maxBufferSize), | |
| maxComputeWorkgroupStorageSize: Math.min(16384, adapter.limits.maxComputeWorkgroupStorageSize), | |
| maxComputeInvocationsPerWorkgroup: Math.min(256, adapter.limits.maxComputeInvocationsPerWorkgroup), | |
| maxComputeWorkgroupSizeX: Math.min(256, adapter.limits.maxComputeWorkgroupSizeX), | |
| }; | |
| if ('maxImmediateSize' in adapter.limits) requiredLimits.maxImmediateSize = 64; | |
| const device = await adapter.requestDevice({ | |
| requiredFeatures, | |
| requiredLimits: requiredLimits as Record<string, number>, | |
| label: 'BotPsy inference device', | |
| }); | |
| const subgroupSize = await probeSubgroupSize(device); | |
| if (subgroupSize < 16 && !options.diagnostic && !options.allowSoftwareAdapter) { | |
| device.destroy(); | |
| throw new Error(`subgroup width ${subgroupSize} is not a qualified hardware target`); | |
| } | |
| const limits: Record<string, number> = {}; | |
| for (const key of Object.keys(requiredLimits)) { | |
| const value = (device.limits as unknown as Record<string, number>)[key]; | |
| if (typeof value === 'number') limits[key] = value; | |
| } | |
| return { device, subgroupSize, limits }; | |
| } | |
| async function probeSubgroupSize(device: GPUDevice): Promise<number> { | |
| const candidates = [32, 16, 64, 8, 4, 128]; | |
| for (const size of candidates) { | |
| if (size > device.limits.maxComputeWorkgroupSizeX) continue; | |
| const code = `enable subgroups; | |
| enable subgroup_size_control; | |
| @compute @workgroup_size(${Math.max(size, 32)}) @subgroup_size(${size}) | |
| fn main(@builtin(local_invocation_index) local: u32, @builtin(subgroup_invocation_id) lane: u32) { | |
| let v = subgroupAdd(f32(lane)); | |
| if (local == 0u && v < 0.0) { return; } | |
| } | |
| `; | |
| const module = device.createShaderModule({ code }); | |
| try { | |
| await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main' } }); | |
| return size; | |
| } catch { | |
| // Try the next qualified width. | |
| } | |
| } | |
| throw new Error('no compilable subgroup width'); | |
| } | |