JS-Torch

A JavaScript library like PyTorch, built from scratch.

README

PyTorch in JavaScript


- JS-Torch is a Deep Learning JavaScript library built from scratch, to closely follow PyTorch's syntax.
- It contains a fully functional Tensor object, which can track gradients, Deep Learning Layers and functions, and an Automatic Differentiation engine.
- Feel free to try out the Web Demo!

Note: You can install the package locally with: npm install js-pytorch


Implemented Tensor Operations:


- Add
- Log
- Sum
- At

Implemented Deep Learning Layers:



1. Project Structure


- assets/ : Folder to store images and the Demo.
  - assets/demo/ : JS-Torch's Web Demo.
- src/ : Framework with JavaScript files.
  - src/tensor.ts: File with the Tensor class and all of the tensor Operations.
  - src/utils.ts: File with operations and helper functions.
  - src/layers.ts: Submodule of the framework. Contains full layers.
  - src/optim.ts: Submodule of the framework. Contains Adam Optimizer.
- tests/: Folder with unit tests. Contains test.ts.

2. Running it Yourself


Simple Autograd Example:


  1. ```typescript
  2. const { torch } = require("js-pytorch");

  3. // Instantiate Tensors:
  4. let x = torch.randn([8, 4, 5]);
  5. let w = torch.randn([8, 5, 4], (requires_grad = true));
  6. let b = torch.tensor([0.2, 0.5, 0.1, 0.0], (requires_grad = true));

  7. // Make calculations:
  8. let out = torch.matmul(x, w);
  9. out = torch.add(out, b);

  10. // Compute gradients on whole graph:
  11. out.backward();

  12. // Get gradients from specific Tensors:
  13. console.log(w.grad);
  14. console.log(b.grad);
  15. ```

Complex Autograd Example (Transformer):


  1. ```typescript
  2. const { torch } = require("js-pytorch");
  3. const nn = torch.nn;
  4. const optim = torch.optim;

  5. // Define training hyperparameters:
  6. const vocab_size = 52;
  7. const hidden_size = 32;
  8. const n_timesteps = 16;
  9. const n_heads = 4;
  10. const dropout_p = 0;
  11. const batch_size = 8;

  12. // Create Transformer decoder Module:
  13. class Transformer extends nn.Module {
  14.   constructor(vocab_size, hidden_size, n_timesteps, n_heads, dropout_p) {
  15.     super();
  16.     // Instantiate Transformer's Layers:
  17.     this.embed = new nn.Embedding(vocab_size, hidden_size);
  18.     this.pos_embed = new nn.PositionalEmbedding(n_timesteps, hidden_size);
  19.     this.b1 = new nn.Block(hidden_size, hidden_size, n_heads, n_timesteps,dropout_p);
  20.     this.b2 = new nn.Block(hidden_size, hidden_size, n_heads, n_timesteps,dropout_p);
  21.     this.ln = new nn.LayerNorm(hidden_size);
  22.     this.linear = new nn.Linear(hidden_size, vocab_size);
  23.   }

  24.   forward(x) {
  25.     let z;
  26.     z = torch.add(this.embed.forward(x), this.pos_embed.forward(x));
  27.     z = this.b1.forward(z);
  28.     z = this.b2.forward(z);
  29.     z = this.ln.forward(z);
  30.     z = this.linear.forward(z);
  31.     return z;
  32.   }
  33. }

  34. // Instantiate your custom nn.Module:
  35. const model = new Transformer(vocab_size, hidden_size, n_timesteps, n_heads, dropout_p);

  36. // Define loss function and optimizer:
  37. const loss_func = new nn.CrossEntropyLoss();
  38. const optimizer = new optim.Adam(model.parameters(), (lr = 5e-3), (reg = 0));

  39. // Instantiate sample input and output:
  40. let x = torch.randint(0, vocab_size, [batch_size, n_timesteps, 1]);
  41. let y = torch.randint(0, vocab_size, [batch_size, n_timesteps]);
  42. let loss;

  43. // Training Loop:
  44. for (let i = 0; i < 40; i++) {
  45.   // Forward pass through the Transformer:
  46.   let z = model.forward(x);

  47.   // Get loss:
  48.   loss = loss_func.forward(z, y);

  49.   // Backpropagate the loss using torch.tensor's backward() method:
  50.   loss.backward();

  51.   // Update the weights:
  52.   optimizer.step();

  53.   // Reset the gradients to zero after each training step:
  54.   optimizer.zero_grad();

  55.   // Print loss at every iteration:
  56.   console.log(`Iter ${i} - Loss ${loss.data[0].toFixed(4)}`)
  57. }
  58. ```

3. Distribution & Devtools


- Build for Distribution by running npm run build. CJS and ESM modules and index.d.ts will be output in the dist/ folder.
- Check the Code with ESLint at any time, running npm run lint.
- Improve Code Formatting with prettier, running npm run prettier.
- Performance Benchmarks are also included in the tests/benchmarks/ directory. Run all benchmarks with npm run bench and save new benchmarks with npm run bench:update.


4. Results


- The models implemented in the unit tests all converged to near-zero losses.
- Run them with npm test!
- This package is not as optimized as PyTorch yet, but I tried making it more interpretable. Efficiency improvements are incoming!
- Hope you enjoy!