22
33PyTorch compiler and WebGPU runtime, capable of running LLM inference
44
5- ## What is torch-webgpu?
5+ ## Use
66
7- torch-webgpu is an experimental WebGPU backend for PyTorch that allows you to :
7+ In Python :
88
9- - ** Run PyTorch on WebGPU** using ` device="webgpu" `
10- - ** Compile PyTorch models** with ` @torch.compile(backend="webgpu") `
11- - ** Run LLMs on WebGPU** - models like Llama 3.2B or Qwen 2.5 0.5B works today!
9+ ` from torch_webgpu import webgpu_backend `
10+
11+ And now you can use ` @torch.compile(backend=webgpu_backend) ` , ` device="webgpu" ` , ` to="webgpu" ` to run and compile PyTorch on a real WebGPU!
12+
13+ ## Installation
14+
15+ ``` bash
16+ pip install torch-webgpu
17+ ```
1218
1319## Why WebGPU?
1420
@@ -19,7 +25,7 @@ WebGPU is a modern graphics and compute API that:
1925- Provides a unified API across different GPU vendors
2026- I believe is the future of portable GPU computing
2127
22- ## Quick Example
28+ ## Example: Tensor on WebGPU
2329
2430``` python
2531import torch
@@ -31,18 +37,31 @@ y = x * 2
3137print (y) # tensor([2., 4., 6.], device='webgpu')
3238```
3339
34- ## Compile an LLM
40+ ## Example: Compile and run an LLM
3541
3642``` python
37- import torch
3843from transformers import AutoModelForCausalLM, AutoTokenizer
44+ import torch
3945from torch_webgpu.compiler.webgpu_compiler import webgpu_backend
4046
41- model = AutoModelForCausalLM.from_pretrained(" Qwen/Qwen2.5-0.5B-Instruct" )
47+ model = AutoModelForCausalLM.from_pretrained(
48+ " Qwen/Qwen2.5-0.5B-Instruct" , torch_dtype = torch.float32
49+ )
50+ tokenizer = AutoTokenizer.from_pretrained(" Qwen/Qwen2.5-0.5B-Instruct" )
51+ model.eval()
52+
4253compiled_model = torch.compile(model, backend = webgpu_backend)
4354
44- # Run inference on WebGPU!
45- outputs = compiled_model(input_ids)
55+ with torch.no_grad():
56+ inputs = tokenizer(" Hello, how are you?" , return_tensors = " pt" )
57+ input_ids = inputs[" input_ids" ]
58+ generated_ids = input_ids.clone()
59+ outputs = compiled_model(input_ids)
60+ for _ in range (10 ):
61+ outputs = compiled_model(generated_ids)
62+ next_token = outputs.logits[0 , - 1 ].argmax().unsqueeze(0 ).unsqueeze(0 )
63+ generated_ids = torch.cat([generated_ids, next_token], dim = 1 )
64+ print (tokenizer.decode(generated_ids[0 ], skip_special_tokens = True ))
4665```
4766
4867## Current Status
0 commit comments