• Stars
    star
    488
  • Rank 87,087 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 1 year ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tensor computation with WebGPU acceleration

webgpu-torch

Tensor computation and autograd with WebGPU acceleration inspired by pytorch.

npm version

Homepage: https://praeclarum.org/webgpu-torch

Installation

Webgpu-torch has no dependencies so you can just include it in your web page.

<script src="https://cdn.jsdelivr.net/npm/webgpu-torch@latest/torch.js"></script>

You can also include it using npm:

npm i webgpu-torch

Usage

If you want to use WebGPU tensors, you must first initialize the library with:

if (!await torch.initWebGPUAsync()) {
    console.warn(`WebGPU is not supported.`);
}

It's an async function and will really do want to await it before doing anything else. All it does is query the navigator object for a valid GPUDevice. Sadly, that's an async operation.

GPU Accelerated Tensors

// Create a tensor
const a = torch.tensor([[1, 2, 3], [4, 5, 6]]);

// Create another tensor
const b = torch.tensor([[7, 8, 9], [10, 11, 12]]);

// Add them
const c = a.add(b);

Tensors use WebGPU memory (GPUBuffers) to store their data. When we want to read values from the tensor we have to map it to the CPU address space. This can be accomplished at a low level with await a.storage.mapReadAsync() or at a high level with await a.toArrayAsync(). Most functions in this library present a synchronous interface, but they are all asynchronous under the hood. Mapping the data to the CPU address space is the only visibly asynchronous operation in the library.

const floatArray = await c.toArrayAsync();
console.log(floatArray);

Autograd Support

Math is fun, but it's even more fun when you do it backwards.

// Create a tensor
const a = torch.tensor({data: [[1, 2, 3], [4, 5, 6]], requiresGrad: true});

// Create another tensor
const b = torch.tensor({data: [[7, 8, 9], [10, 11, 12]], requiresGrad: true});

// Add them
const c = a.add(b);

// Differentiate them
c.backward();

After this code executes, there will be gradient tensor values in a.grad, b.grad, and c.grad.

API

Although this library was inspired by pytorch, it is not a clone and was written from scratch. Its API surface is therefore not 100% compatible with pytorch, but I prioritize making it as similar as possible.

Fundamental Types

  • Device is an abstraction over CPUs and GPUs allowing you to specify where tensors are allocated and executed.
  • Dtype is the data type of tensors and are specified as strings. Currently only "float32" is supported.
  • Shape is an array of integers that specifies the size of each dimension of a tensor. For example, [32, 3, 128, 256] would be 32 batched 256x128 RGB images.
  • Tensor is a multi-dimensional array of data. It has a device, a dtype, a shape, and storage properties. It can be created in a variety of ways.
    • Directly with torch.tensor(array) or new torch.Tensor(array)
    • From factory functions like torch.zeros(shape) or torch.ones(shape)
    • From operations like a.add(b) or a.mm(b)
    • From a gradient calculation like a.add(b).backward()
  • AutoFunction is the base class for all autograd functions. It has a forward method that computes the output tensor and a backward method that computes the gradients of the inputs. They live in the torch.functions object. Functions should be called using their apply method.
  • Kernel is basic operation that can be executed on the GPU.

Tensor Operations

You have your basic unary operations like abs that can be called from a global function or on the tensor directly:

const a = torch.tensor([[-1, 2, -3], [4, -5, 6]]);
const abs = torch.abs(a);
const abs2 = a.abs();

Your binary operations like add can be called in the same way:

const b = torch.tensor([[7, -8, 9], [-10, 11, -12]]);
const sum = torch.add(a, b);
const sum2 = a.add(b);

I'm working on documenting the full list. For now, checkout the file op_table.ts for a list of most of the operations.

TODO

Here are the big components of the library:

  • GPU Tensors
  • GPU Kernels
  • Autograd Functions
  • Datatypes beyond float32
  • Optimizers (SGD and Adam)
  • Modules
  • Save and restore (ONNX, safetensors)

In terms of supported operations, there's still a bit of work to be done:

  • Basic math
  • Convolution
  • Indexing
  • Broadcasting
  • Reductions
  • Imaging

Acknowledgements

I want to thank the Torch7 Lua environment for getting me into neural networks.

I want to thank the pytorch team for inspiring me.

I want to thank the webgpu teams at all the browser vendors for making this possible.

More Repositories

1

sqlite-net

Simple, powerful, cross-platform SQLite client and ORM for .NET
C#
3,753
star
2

Ooui

A small cross-platform UI library that brings the simplicity of native UI development to the web
C#
1,616
star
3

Netjs

Compile .NET assemblies to TypeScript and JavaScript
C#
955
star
4

NGraphics

NGraphics is a cross platform library for rendering vector graphics on .NET. It provides a unified API for both immediate and retained mode graphics using high quality native renderers.
C#
696
star
5

FuGetGallery

An alternative web UI for browsing nuget packages
C#
672
star
6

Continuous

Continuous IDE Addin enables live coding from Xamarin Studio and Visual Studio
C#
268
star
7

CLanguage

C parser, compiler, and interpreter for .NET
C#
252
star
8

Bind

A small but powerful C# library for data binding
C#
205
star
9

CrossGraphics

Cross-platform Graphics Library for .NET
C#
194
star
10

transformers-js

Browser-compatible JS library for running language models
JavaScript
178
star
11

ImmutableUI

Immutable objects that mirror popular object oriented UIs
C#
115
star
12

ListDiff

C#
113
star
13

Iril

Compiles LLVM IR (bytecode) or C to .NET Assemblies
LLVM
94
star
14

web-transformers

Transformer neural networks in the browser
TypeScript
89
star
15

Praeclarum.MacCatalyst

Convert your Xamarin.iOS apps to Mac Catalyst apps by adding this nuget.
C#
63
star
16

Csg

Solid modeling library for .NET
C#
62
star
17

AskGPT

Ask ChatGPT questions from the command line.
C#
58
star
18

SwiftSharp

Swift compiler for .NET
HTML
52
star
19

Gone

GO compiler for .NET
F#
42
star
20

HotDogOrNot

A minimal Xamarin CoreML app to detect hotdogs
C#
40
star
21

lcars

LCARS Reader - the coolest iPad news reader not on the App Store
C#
36
star
22

CSharpInteractive

C# Interactive is a REPL for C# in Xamarin Studio
C#
30
star
23

QuickTest

C#
28
star
24

Praeclarum

My general purpose library
C#
28
star
25

GooglePlus

GooglePlus API Documentation and .NET Implementation
C#
27
star
26

MetalTensors

.NET Neural Network training library using Apple's Metal Performance Shaders
C#
26
star
27

runcs

The C# compiler hosted in a web app
C#
26
star
28

odata

OData Browser for the iPhone
C#
26
star
29

CSharpToSwift

Converts your C# projects to Swift
C#
23
star
30

StopCrashing

Script to detect possible sources of crashes in Xamarin apps
F#
21
star
31

FunctionalMeetup

Example code for Frank Krueger's Functional Mobile Apps talk at NDC Oslo 2016
F#
19
star
32

EasyLayout

EasyLayout makes writing auto layout code in Xamarin.iOS easier.
C#
18
star
33

SdfKit

.NET library to convert signed distance functions (SDFs) into triangle meshes and 3D renders
C#
17
star
34

OouiChat

Chat room web app built using Xamarin.Forms, ASP.NET, and Ooui
C#
16
star
35

MarriageClock

An IoT thing in the shape of heart that tells you how long you've been married
C++
13
star
36

ThreeDO

C#
13
star
37

Ur

Game of Ur using Blazor
C#
13
star
38

CircuitTranslations

Language support for iCircuit
F#
13
star
39

ARDemo

Xamarin Evolve 2014 Augmented Reality Demo
C#
12
star
40

fuget

C#
10
star
41

caulker

3D Map for MonoTouch
C#
10
star
42

praeclarum.github.io

Frank A. Krueger's blog
HTML
10
star
43

WebGlobe

3D Globe Screensaver Written in WebGPU
JavaScript
9
star
44

BuildLight

Show IDE build status using an IoT device
C#
8
star
45

NMusic

Library and demo app for composing music and playing it on iOS
C#
8
star
46

Demo11

iOS 11 Demo Code Presented at the Seattle Mobile .NET Meetup
C#
8
star
47

JavaScriptLanguage

Resharper add-in that decompiles to JavaScript.
C#
8
star
48

circuitpython-net

CircuitPython compiled to run on .NET
C#
8
star
49

CuneiformTranslators

Neural network trained to translate from ancient languages to modern languages
Jupyter Notebook
8
star
50

ukf

Unscented Kalman Filter Library
7
star
51

ClrTools

Tools for .NET Developers
C#
7
star
52

ImageRecognizer

Uses Metal Performance Shaders on iOS 13+ to train a neural network to recognize shapes
C#
7
star
53

rt

My Pet Raytracer in C#
C#
6
star
54

Monospace11

Demo code from Frank Krueger's talk at Monospace
C#
6
star
55

rouse

Declarative RESTful server
C#
5
star
56

NEcho

Amazon Echo ("Alexa") ASP.NET Core Web Service
C#
5
star
57

html5

C#
5
star
58

NeuralScanner

C++
4
star
59

Fom

F#
4
star
60

VectorPerf

Measures the performance of different vector types in .NET
C#
4
star
61

Knossus

Quick and easy web apps
C#
4
star
62

WasmAloneLab

HTML
4
star
63

ColmapSharp

COLMAP builds and bindings for .NET
C++
4
star
64

UIDays

Cataloging the release dates of various UI frameworks
4
star
65

HomeAI

C#
4
star
66

SubMark1Sim

F# Code to visualize a submarine control simulation
F#
3
star
67

AppleNative.Templates

F#
3
star
68

dotnet-tree-sitter

.NET bindings to the Tree-sitter parsing library
Makefile
3
star
69

Lilui

The lilest cross platform UI library for .NET
C#
3
star
70

BuildBoard

Display build status on an LED matrix
C++
2
star
71

nerf-py

Python
1
star
72

VacuumMold

C#
1
star
73

PythonRepl

Python REPL for iOS using Xamarin and IronPython
C#
1
star
74

Armina

Programming language cross compilation tools
C#
1
star