Lightweight, private alternative to Colab. Run PyTorch & NumPy in browser with GPU acceleration (8.8x speedup). Fast, secure, runs locally.
npm install greed.js!logo



A powerful JavaScript library that enables seamless execution of Python code in web browsers with actual WebGPU-accelerated PyTorch support using compute shaders and intelligent worker-based parallel execution.
a = 1 in one cell, use it in the nextrun() callsclearState() method for manual state resetrun() or runPython() - both work identically``bash`
npm install greed.js
`bash`
yarn add greed.js
`html`
- ποΈ Modular Architecture: Clean separation of concerns with EventEmitter-based communication
- π Notebook-Style Execution: Variables persist between cells like Jupyter notebooks
- PyTorch in Browser: Full PyTorch polyfill with neural networks, tensors, and deep learning operations
- β‘ WebGPU Compute Shaders: True GPU acceleration with 50+ optimized WGSL compute shaders for tensor operations
- π― Intelligent Fallback: WebGPU β CPU β Worker execution strategy with automatic optimization
- Complete Neural Networks: Support for torch.nn.Module, layers, loss functions, and training
- Python in Browser: Execute Python code directly using Pyodide/WebAssembly
- π‘οΈ Enhanced Security: Advanced input validation and threat detection system
- π§ Smart Compute Strategy: Intelligent fallback between WebGPU β CPU β Worker execution
- π Memory Management: Automatic resource cleanup and memory pressure monitoring
- Dynamic Package Installation: Automatically install Python packages on-demand
- Simple API: Easy-to-use interface with comprehensive PyTorch compatibility
- π Production Ready: Comprehensive testing, security validation, and performance optimization
`html`
Greed.js v3.0 - Notebook-Style Execution
Greed.js v3.0 features a modular architecture designed for performance, maintainability, and extensibility:
``
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Greed Core β
β (Orchestration, Events, Public API) β
ββββββββββ¬βββββββββββββββββββββββββββββββββββββ¬ββββββββββββ
β β
ββββββΌβββββββββββ ββββββΌβββββββββββ
β RuntimeManagerβ βComputeStrategyβ
β - Pyodide β β - WebGPU β
β - Packages β β - CPU β
β - Execution β β - Workers β
ββββββ¬βββββββββββ ββββββ¬βββββββββββ
β β
ββββββΌβββββββββββ ββββββΌβββββββββββ
βMemoryManager β βSecurityValida-β
β - GC β βtor β
β - Monitoring β β - Validation β
β - Cleanup β β - Threat Det.β
βββββββββββββββββ βββββββββββββββββ
- Greed: Main orchestrator with EventEmitter-based communication
- RuntimeManager: Pyodide initialization, package management, Python execution
- ComputeStrategy: WebGPU/CPU/Worker compute orchestration with intelligent fallback
- WebGPUComputeEngine: Hardware-accelerated tensor operations using WebGPU compute shaders
- WebGPUTensor: PyTorch-compatible tensor implementation with GPU acceleration
- TensorBridge: Seamless interoperability between JavaScript and Python tensors
- MemoryManager: Advanced resource cleanup with automatic garbage collection
- SecurityValidator: Comprehensive input validation and threat detection
- EventEmitter: Base class providing event-driven inter-component communication
v3.0 introduces true notebook-style execution where Python variables persist between cells:
`javascript
const greed = new Greed();
await greed.initialize();
// Cell 1: Define data
await greed.run(
import torch
import torch.nn as nn
# Define model
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(10, 5)
def forward(self, x):
return self.fc(x)
model = SimpleNet()
print("Model created"));
// Cell 2: Use model from previous cell
await greed.run(
# Model is still available!
x = torch.randn(32, 10)
output = model(x)
print(f"Output shape: {output.shape}"));
// Cell 3: Continue training
await greed.run(
optimizer = torch.optim.Adam(model.parameters())
loss = output.mean()
loss.backward()
optimizer.step()
print("Training step complete"));
// Clear state when starting new session
await greed.clearState();
`
`javascript
const greed = new Greed({
// Core settings
enableWebGPU: true, // Enable WebGPU acceleration
enableWorkers: true, // Enable Web Workers
maxWorkers: 4, // Number of worker threads
// Security settings
strictSecurity: true, // Strict security validation
allowEval: false, // Block eval() in Python
allowFileSystem: false, // Block file system access
allowNetwork: false, // Block network access
// Performance settings
maxMemoryMB: 1024, // Max memory allocation
gcThreshold: 0.8, // GC trigger threshold
enableProfiling: true, // Performance profiling
// Runtime settings
pyodideIndexURL: 'https://cdn.jsdelivr.net/pyodide/v0.24.1/full/',
preloadPackages: ['numpy'], // Packages to preload
initTimeout: 30000 // Initialization timeout
});
`
#### await greed.initialize()
Initialize all components and establish PyTorch API.
`javascript`
await greed.initialize();
#### await greed.run(code, options) or await greed.runPython(code, options)
Execute Python code with notebook-style state persistence.
`javascript
const result = await greed.run(
import torch
x = torch.tensor([1, 2, 3])
x.sum().item(), {
captureOutput: true, // Capture print() output
timeout: 5000, // Execution timeout
globals: {}, // Additional globals
allowWarnings: false, // Allow security warnings
bypassSecurity: false // Bypass security validation
});
console.log(result.output); // Printed output
`
#### await greed.clearState()
Clear Python execution state (user variables). Preserves torch, numpy, and library imports.
`javascript`
await greed.clearState();
#### await greed.loadPackages(packages)
Load additional Python packages.
`javascript`
await greed.loadPackages(['pandas', 'matplotlib']);
#### greed.getStats()
Get comprehensive system statistics.
`javascript`
const stats = greed.getStats();
console.log('Memory usage:', stats.memory.memoryUsageMB);
console.log('Operations:', stats.operations);
console.log('Runtime status:', stats.runtime);
#### await greed.destroy()
Graceful shutdown and resource cleanup.
`javascript`
await greed.destroy();
`javascript
greed.on('init:complete', (data) => {
console.log('Initialization complete:', data.initTime, 'ms');
});
greed.on('operation:start', (data) => {
console.log('Executing code:', data.codeLength, 'bytes');
});
greed.on('operation:complete', (data) => {
console.log('Execution time:', data.executionTime, 'ms');
});
greed.on('operation:error', (data) => {
console.error('Execution error:', data.error);
});
greed.on('memory:warning', (data) => {
console.warn('Memory pressure:', data.memoryUsageMB, 'MB');
});
`
python
import torchTensor creation
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float)
y = torch.randn(2, 2)GPU acceleration
x_gpu = x.cuda() # Move to WebGPU
result = torch.mm(x_gpu, y.cuda()) # Matrix multiplication on GPUAll standard operations supported
z = x + y * 2.0 - torch.ones_like(x)
`$3
`python
import torch
import torch.nn as nnclass SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.relu(self.fc1(x))
return self.fc2(x)
Create and use model
model = SimpleNet()
x = torch.randn(32, 784) # Batch of 32 samples
output = model(x)Training with loss functions
criterion = nn.CrossEntropyLoss()
target = torch.randint(0, 10, (32,))
loss = criterion(output, target)
`$3
- Element-wise operations: +, -, *, / with smart GPU thresholds
- Matrix operations: torch.mm(), torch.matmul(), @ operator
- Reduction operations: torch.sum(), torch.mean(), torch.max()
- Neural network layers: nn.Linear, nn.ReLU, nn.CrossEntropyLoss
- Automatic fallback: Seamless CPU fallback for small tensors or when WebGPU unavailableπ Browser Support
| Feature | Chrome | Firefox | Safari | Edge |
|---------|--------|---------|--------|------|
| Pyodide/WebAssembly | β
57+ | β
52+ | β
11+ | β
16+ |
| WebGPU Acceleration | β
113+ | π Exp | π Exp | β
113+ |
| Web Workers | β
| β
| β
| β
|
| Notebook State Persistence | β
| β
| β
| β
|
π¨ Framework Integration
$3
`jsx
import { useState, useEffect } from 'react';
import Greed from 'greed.js';function PyTorchNotebook() {
const [greed, setGreed] = useState(null);
const [output, setOutput] = useState('');
useEffect(() => {
const init = async () => {
const instance = new Greed({ enableWebGPU: true });
await instance.initialize();
setGreed(instance);
};
init();
return () => greed?.destroy();
}, []);
const runCell = async (code) => {
if (!greed) return;
const result = await greed.run(code);
setOutput(result.output);
};
return (
{output}
);
}
`$3
`jsx
import dynamic from 'next/dynamic';// Disable SSR for Greed.js
const PyTorchRunner = dynamic(() => import('../components/PyTorchRunner'), {
ssr: false,
loading: () =>
Loading PyTorch...
});export default function HomePage() {
return ;
}
`π§ Development
`bash
Clone repository
git clone https://github.com/adityakhalkar/greed.git
cd greedInstall dependencies
npm installStart development server
npm run devBuild for production
npm run buildRun test suite
npm test
`π Project Structure
`
greed/
βββ src/
β βββ core/
β β βββ greed-v2.js # Main orchestrator
β β βββ runtime-manager.js # Pyodide runtime
β β βββ event-emitter.js # Event system
β βββ compute/
β β βββ compute-strategy.js # Compute orchestration
β β βββ webgpu/ # WebGPU implementation
β βββ utils/
β β βββ memory-manager.js # Memory management
β β βββ security-validator.js # Security validation
β βββ polyfills/
β βββ pytorch-runtime.js # PyTorch polyfill
βββ dist/ # Built files
βββ tests/ # Test suite
βββ examples/ # Usage examples
``We welcome contributions! Please see our Contributing Guide for details.
1. Bug Reports: Use GitHub Issues with detailed reproduction steps
2. Feature Requests: Propose new PyTorch operations or WebGPU optimizations
3. Pull Requests: Include tests and ensure all examples still work
This software is dual-licensed under AGPL v3.0 and commercial licenses.
For commercial licensing inquiries, contact khalkaraditya8@gmail.com
Complete licensing terms are available in the LICENSE file.
- Pyodide: Python-to-WebAssembly runtime
- WebGPU: GPU acceleration standard
- PyTorch: Deep learning framework inspiration
- Python Community: For the incredible ecosystem
---
Greed.js v3.0 - Bringing the power of PyTorch, GPU acceleration, and notebook-style execution to every web browser! π