GPU Context
Understanding GPU context management in Tiny-DL-Inference.
Overview
The GPUContext class is the foundation of Tiny-DL-Inference. It manages WebGPU device initialization, buffer allocation, and command submission.
Basic Usage
Initialization
typescript
import { GPUContext } from 'tiny-dl-inference';
const context = new GPUContext();
await context.initialize();1
2
3
4
2
3
4
Configuration Options
typescript
interface GPUContextConfig {
powerPreference?: 'low-power' | 'high-performance';
forceFallbackAdapter?: boolean;
}
await context.initialize({
powerPreference: 'high-performance'
});1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Resource Management
Buffer Creation
typescript
const buffer = context.createBuffer({
size: 1024,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
});1
2
3
4
2
3
4
Deferred Destruction
Prevents use-after-free by delaying buffer destruction until GPU work completes:
typescript
// Queue buffer for destruction after GPU finishes
context.deferDestroy(tempBuffer);
// Wait for all GPU work to complete
await context.sync();
// Now deferred buffers are actually destroyed1
2
3
4
5
6
2
3
4
5
6
Command Submission
Creating Commands
typescript
const encoder = context.createCommandEncoder();
// Encode compute passes
const pass = encoder.beginComputePass();
// ... dispatch compute operations
pass.end();
// Submit to GPU
const commandBuffer = encoder.finish();
context.submit([commandBuffer]);1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Synchronization
typescript
// Wait for all submitted work to complete
await context.sync();1
2
2
Memory Management
Buffer Lifecycle
Create → Use → Destroy
│ │ │
│ │ └── deferDestroy() queues for after GPU work
│ └────────── encode commands, submit to queue
└───────────────── GPUContext.createBuffer()1
2
3
4
5
2
3
4
5
Best Practices
- Use deferred destruction for temporary buffers
- Minimize sync calls - they block the CPU
- Reuse buffers when possible instead of creating new ones
Error Handling
Common Errors
| Error | Cause | Solution |
|---|---|---|
WebGPUNotSupportedError | Browser lacks WebGPU | Use modern browser |
DeviceInitializationError | GPU init failed | Check drivers |
Example
typescript
try {
const context = new GPUContext();
await context.initialize();
} catch (error) {
if (error instanceof WebGPUNotSupportedError) {
console.log('Please use a WebGPU-compatible browser');
} else if (error instanceof DeviceInitializationError) {
console.log('GPU initialization failed:', error.message);
}
}1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
API Reference
See the GPUContext API Reference for complete documentation.