|
4 | 4 | "cell_type": "markdown", |
5 | 5 | "metadata": {}, |
6 | 6 | "source": [ |
7 | | - "# Oxideon Quickstart\n", |
| 7 | + "# Oxideon — Interactive Deep Learning & Scientific Computing Showcase\n", |
8 | 8 | "\n", |
9 | | - "Run **Oxideon** (`pip install oxideon`) directly in Google Colab or Jupyter:\n", |
10 | | - "- Zero-copy strided views & higher-order autograd (`create_graph=True`)\n", |
11 | | - "- Training a neural network with `AdamW` & `LayerNorm`\n", |
12 | | - "- Zero-copy NumPy / DLPack interop & Einops `rearrange`\n", |
13 | | - "- Quick CPU speed check vs PyTorch\n", |
| 9 | + "Run **Oxideon** (`pip install oxideon`) directly in Google Colab or Jupyter — backed by a pure-Rust tensor core with PyTorch-friendly Python APIs:\n", |
| 10 | + "1. **Zero-copy strided views**, `rearrange` (einops), and NHWC `channels_last` layout\n", |
| 11 | + "2. **Higher-order autograd** (`create_graph=True`: 1st, 2nd & 3rd derivatives) + differentiable `einsum`\n", |
| 12 | + "3. **Train a 2D Spiral Classifier** (`Linear` + `LayerNorm` + `AdamW`) with decision boundary & loss plots\n", |
| 13 | + "4. **CNN & Transformer building blocks** (`Conv2d`, `MultiheadAttention`)\n", |
| 14 | + "5. **Dynamic quantization** (`quantize_dynamic`) & **SafeTensors** export (`save_file` / `load_file`)\n", |
| 15 | + "6. **Scientific computing** (`linalg.qr`, `linalg.svd`, `fft.rfft`, `distributions.Normal`)\n", |
| 16 | + "7. **Zero-copy NumPy / PyTorch DLPack interop** & CPU micro-benchmarks\n", |
14 | 17 | "\n", |
15 | | - "Repo: https://github.com/voidstackloop/oxideon" |
| 18 | + "- **GitHub:** https://github.com/voidstackloop/oxideon\n", |
| 19 | + "- **Live WASM Browser Demo (no install):** https://voidstackloop.github.io/oxideon/" |
16 | 20 | ] |
17 | 21 | }, |
18 | 22 | { |
|
21 | 25 | "metadata": {}, |
22 | 26 | "outputs": [], |
23 | 27 | "source": [ |
24 | | - "!pip install -q oxideon" |
| 28 | + "!pip install -q oxideon\n", |
| 29 | + "import oxideon as ox\n", |
| 30 | + "import math, time, os, tempfile\n", |
| 31 | + "print(f\"Oxideon v{ox.__version__} ready!\")" |
| 32 | + ] |
| 33 | + }, |
| 34 | + { |
| 35 | + "cell_type": "markdown", |
| 36 | + "metadata": {}, |
| 37 | + "source": [ |
| 38 | + "## 1. Zero-Copy Strided Views, Einops `rearrange`, and `channels_last`" |
25 | 39 | ] |
26 | 40 | }, |
27 | 41 | { |
|
30 | 44 | "metadata": {}, |
31 | 45 | "outputs": [], |
32 | 46 | "source": [ |
33 | | - "import oxideon as ox\n", |
34 | | - "\n", |
35 | | - "# 1. Zero-copy strided views\n", |
36 | 47 | "x = ox.Tensor.arange(0.0, 24.0, 1.0).reshape([2, 3, 4])\n", |
37 | 48 | "v = x.transpose(0, 2)\n", |
38 | 49 | "assert v.shares_storage(x)\n", |
39 | | - "print(\"v shape:\", list(v.shape), \"shares_storage:\", v.shares_storage(x))\n", |
| 50 | + "print(\"Transposed view shape:\", list(v.shape), \"| shares_storage:\", v.shares_storage(x))\n", |
40 | 51 | "\n", |
41 | | - "# 2. Einops-style rearrange & channels_last\n", |
42 | 52 | "img = ox.randn([2, 8, 4, 4])\n", |
43 | 53 | "nhwc = img.rearrange(\"b c h w -> b h w c\")\n", |
44 | 54 | "cl = img.to_channels_last()\n", |
45 | | - "print(\"rearranged shape:\", list(nhwc.shape), \"is_channels_last:\", cl.is_channels_last())" |
| 55 | + "print(\"Rearranged NHWC shape:\", list(nhwc.shape), \"| is_channels_last:\", cl.is_channels_last())" |
| 56 | + ] |
| 57 | + }, |
| 58 | + { |
| 59 | + "cell_type": "markdown", |
| 60 | + "metadata": {}, |
| 61 | + "source": [ |
| 62 | + "## 2. Higher-Order Autograd (`create_graph=True`) & `einsum`" |
46 | 63 | ] |
47 | 64 | }, |
48 | 65 | { |
|
51 | 68 | "metadata": {}, |
52 | 69 | "outputs": [], |
53 | 70 | "source": [ |
54 | | - "# 3. Higher-order autograd (1st, 2nd, and 3rd derivatives)\n", |
| 71 | + "# Analytical 1st, 2nd, and 3rd derivatives of y = x^4 at x = 3\n", |
| 72 | + "# Expected: dy = 4*27 = 108, d2y = 12*9 = 108, d3y = 24*3 = 72\n", |
55 | 73 | "x = ox.Tensor.from_slice([3.0], [1], requires_grad=True)\n", |
56 | 74 | "y = x.powf(4.0)\n", |
57 | 75 | "dy = ox.grad([y], [x], create_graph=True)[0]\n", |
58 | 76 | "d2y = ox.grad([dy], [x], create_graph=True)[0]\n", |
59 | 77 | "d3y = ox.grad([d2y], [x])[0]\n", |
60 | | - "print(\"y=x^4 at x=3 -> dy:\", dy.to_list(), \"d2y:\", d2y.to_list(), \"d3y:\", d3y.to_list())" |
| 78 | + "print(f\"y=x^4 at x=3 -> dy={dy.to_list()}, d2y={d2y.to_list()}, d3y={d3y.to_list()}\")\n", |
| 79 | + "\n", |
| 80 | + "# Batched Einstein summation\n", |
| 81 | + "A = ox.Tensor.from_slice([1.0, 2.0, 3.0, 4.0], [2, 2])\n", |
| 82 | + "B = ox.Tensor.from_slice([2.0, 0.0, 1.0, 2.0], [2, 2])\n", |
| 83 | + "C = ox.einsum(\"ij,jk->ik\", A, B)\n", |
| 84 | + "print(\"einsum matmul [2,2]:\", C.to_list())" |
| 85 | + ] |
| 86 | + }, |
| 87 | + { |
| 88 | + "cell_type": "markdown", |
| 89 | + "metadata": {}, |
| 90 | + "source": [ |
| 91 | + "## 3. Train a Non-Linear 2D Spiral Classifier with `AdamW` & Plot Results" |
61 | 92 | ] |
62 | 93 | }, |
63 | 94 | { |
|
66 | 97 | "metadata": {}, |
67 | 98 | "outputs": [], |
68 | 99 | "source": [ |
69 | | - "# 4. Train a compact MLP with AdamW\n", |
70 | | - "class MLP(ox.nn.Module):\n", |
71 | | - " def __init__(self, d=64):\n", |
| 100 | + "import numpy as np\n", |
| 101 | + "\n", |
| 102 | + "def make_spiral(n_per_class=100, seed=42):\n", |
| 103 | + " rng = np.random.default_rng(seed)\n", |
| 104 | + " xs, ys = [], []\n", |
| 105 | + " for cls in (0, 1):\n", |
| 106 | + " t = np.linspace(0.05, 1.0, n_per_class)\n", |
| 107 | + " r = 0.85 * t + 0.05\n", |
| 108 | + " theta = 3.2 * t * math.pi + (math.pi if cls == 1 else 0.0) + rng.normal(0, 0.08, n_per_class)\n", |
| 109 | + " pts = np.stack([r * np.sin(theta), r * np.cos(theta)], axis=1)\n", |
| 110 | + " xs.append(pts.astype(np.float32))\n", |
| 111 | + " ys.append(np.full((n_per_class, 2), [1.0, 0.0] if cls == 0 else [0.0, 1.0], dtype=np.float32))\n", |
| 112 | + " return np.concatenate(xs, axis=0), np.concatenate(ys, axis=0)\n", |
| 113 | + "\n", |
| 114 | + "X_np, Y_np = make_spiral()\n", |
| 115 | + "X = ox.from_numpy(X_np)\n", |
| 116 | + "Y = ox.from_numpy(Y_np)\n", |
| 117 | + "y_cls = Y_np.argmax(axis=1)\n", |
| 118 | + "\n", |
| 119 | + "class SpiralNet(ox.nn.Module):\n", |
| 120 | + " def __init__(self, hid=32):\n", |
72 | 121 | " super().__init__()\n", |
73 | | - " self.fc1 = ox.nn.Linear(16, d)\n", |
74 | | - " self.ln = ox.nn.LayerNorm(d)\n", |
75 | | - " self.fc2 = ox.nn.Linear(d, 4)\n", |
| 122 | + " self.fc1 = ox.nn.Linear(2, hid)\n", |
| 123 | + " self.ln1 = ox.nn.LayerNorm(hid)\n", |
| 124 | + " self.fc2 = ox.nn.Linear(hid, hid)\n", |
| 125 | + " self.ln2 = ox.nn.LayerNorm(hid)\n", |
| 126 | + " self.out = ox.nn.Linear(hid, 2)\n", |
76 | 127 | "\n", |
77 | 128 | " def forward(self, x):\n", |
78 | | - " return self.fc2(self.ln(self.fc1(x)).gelu())\n", |
| 129 | + " h = self.ln1(self.fc1(x)).tanh()\n", |
| 130 | + " h = self.ln2(self.fc2(h)).tanh()\n", |
| 131 | + " return self.out(h)\n", |
79 | 132 | "\n", |
80 | | - "model = MLP()\n", |
81 | | - "opt = ox.optim.AdamW(model.parameters(), lr=1e-2)\n", |
82 | | - "xs = ox.randn([32, 16])\n", |
83 | | - "ys = ox.randn([32, 4])\n", |
| 133 | + "model = SpiralNet(32)\n", |
| 134 | + "opt = ox.optim.AdamW(model.parameters(), lr=0.03)\n", |
| 135 | + "losses, accs = [], []\n", |
84 | 136 | "\n", |
85 | | - "for step in range(40):\n", |
| 137 | + "for step in range(180):\n", |
86 | 138 | " opt.zero_grad()\n", |
87 | | - " pred = model(xs)\n", |
88 | | - " loss = ((pred - ys) * (pred - ys)).mean()\n", |
| 139 | + " probs = model(X).softmax(-1)\n", |
| 140 | + " loss = ((probs - Y) * (probs - Y)).mean()\n", |
89 | 141 | " loss.backward()\n", |
90 | 142 | " opt.step()\n", |
91 | | - " if step in (0, 19, 39):\n", |
92 | | - " print(f\"step {step:2d}: loss = {loss.item():.6f}\")" |
| 143 | + " acc = float((probs.numpy().argmax(axis=1) == y_cls).mean())\n", |
| 144 | + " losses.append(loss.item())\n", |
| 145 | + " accs.append(acc)\n", |
| 146 | + " if step in (0, 59, 119, 179):\n", |
| 147 | + " print(f\"step {step:3d}: mse_prob={losses[-1]:.5f} | accuracy={acc * 100:.1f}%\")\n", |
| 148 | + "\n", |
| 149 | + "try:\n", |
| 150 | + " import matplotlib.pyplot as plt\n", |
| 151 | + " fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.2))\n", |
| 152 | + " gx, gy = np.meshgrid(np.linspace(-1.1, 1.1, 80), np.linspace(-1.1, 1.1, 80))\n", |
| 153 | + " grid = np.stack([gx.ravel(), gy.ravel()], axis=1).astype(np.float32)\n", |
| 154 | + " gp = model(ox.from_numpy(grid)).softmax(-1).numpy()[:, 1].reshape(gx.shape)\n", |
| 155 | + " ax1.contourf(gx, gy, gp, levels=20, cmap=\"coolwarm\", alpha=0.75)\n", |
| 156 | + " ax1.scatter(X_np[:, 0], X_np[:, 1], c=y_cls, cmap=\"coolwarm\", edgecolors=\"k\", s=24)\n", |
| 157 | + " ax1.set_title(f\"Oxideon Spiral Boundary ({accs[-1]*100:.1f}% acc)\")\n", |
| 158 | + " ax2.plot(losses, label=\"Loss\", color=\"#10b981\")\n", |
| 159 | + " ax2.plot(accs, label=\"Accuracy\", color=\"#3b82f6\")\n", |
| 160 | + " ax2.set_title(\"Training Curve (AdamW)\")\n", |
| 161 | + " ax2.legend()\n", |
| 162 | + " plt.tight_layout()\n", |
| 163 | + " plt.show()\n", |
| 164 | + "except ImportError:\n", |
| 165 | + " print(\"Install matplotlib to render decision boundary & loss plots.\")" |
| 166 | + ] |
| 167 | + }, |
| 168 | + { |
| 169 | + "cell_type": "markdown", |
| 170 | + "metadata": {}, |
| 171 | + "source": [ |
| 172 | + "## 4. CNN (`Conv2d`), Transformer (`MultiheadAttention`), Quantization & SafeTensors" |
93 | 173 | ] |
94 | 174 | }, |
95 | 175 | { |
|
98 | 178 | "metadata": {}, |
99 | 179 | "outputs": [], |
100 | 180 | "source": [ |
101 | | - "# 5. Zero-copy NumPy / DLPack interop & quick CPU benchmark vs PyTorch\n", |
102 | | - "import time\n", |
| 181 | + "# Conv2d + MultiheadAttention\n", |
| 182 | + "conv = ox.nn.Conv2d(3, 16, kernel_size=3, padding=1)\n", |
| 183 | + "feat = conv(ox.randn([2, 3, 16, 16])).gelu()\n", |
| 184 | + "print(\"Conv2d output shape:\", list(feat.shape))\n", |
103 | 185 | "\n", |
| 186 | + "mha = ox.nn.MultiheadAttention(embed_dim=32, num_heads=4)\n", |
| 187 | + "tokens = ox.randn([2, 8, 32])\n", |
| 188 | + "attn_out, attn_weights = mha(tokens, tokens, tokens)\n", |
| 189 | + "print(\"MultiheadAttention output:\", list(attn_out.shape), \"| weights:\", list(attn_weights.shape))\n", |
| 190 | + "\n", |
| 191 | + "# Dynamic Quantization + SafeTensors save_file / load_file\n", |
| 192 | + "seq = ox.nn.Sequential(ox.nn.Linear(16, 64), ox.nn.Linear(64, 4))\n", |
| 193 | + "qseq = ox.quantize_dynamic(seq)\n", |
| 194 | + "q_out = qseq(ox.randn([4, 16]))\n", |
| 195 | + "print(\"Quantized Sequential output:\", list(q_out.shape))\n", |
| 196 | + "\n", |
| 197 | + "with tempfile.TemporaryDirectory() as tmpdir:\n", |
| 198 | + " ckpt_path = os.path.join(tmpdir, \"spiral_weights.safetensors\")\n", |
| 199 | + " ox.save_file({f\"p{i}\": p.detach() for i, p in enumerate(model.parameters())}, ckpt_path)\n", |
| 200 | + " reloaded = ox.load_file(ckpt_path)\n", |
| 201 | + " print(f\"Saved & reloaded {len(reloaded)} parameter tensors cleanly via SafeTensors.\")" |
| 202 | + ] |
| 203 | + }, |
| 204 | + { |
| 205 | + "cell_type": "markdown", |
| 206 | + "metadata": {}, |
| 207 | + "source": [ |
| 208 | + "## 5. Scientific Computing: Linear Algebra (`qr`, `svd`), `fft.rfft` & Distributions" |
| 209 | + ] |
| 210 | + }, |
| 211 | + { |
| 212 | + "cell_type": "code", |
| 213 | + "execution_count": null, |
| 214 | + "metadata": {}, |
| 215 | + "outputs": [], |
| 216 | + "source": [ |
| 217 | + "M = ox.Tensor.from_slice([3.0, 1.0, 1.0, 3.0], [2, 2])\n", |
| 218 | + "Q, R = ox.linalg.qr(M)\n", |
| 219 | + "U, S, Vt = ox.linalg.svd(M)\n", |
| 220 | + "print(\"QR shapes:\", list(Q.shape), list(R.shape), \"| singular values:\", [round(v, 4) for v in S.to_list()])\n", |
| 221 | + "\n", |
| 222 | + "sig = ox.Tensor.from_slice([math.sin(2 * math.pi * k / 16.0) for k in range(16)], [16])\n", |
| 223 | + "spec = ox.fft.rfft(sig)\n", |
| 224 | + "print(\"rfft spectrum shape:\", list(spec.shape))\n", |
| 225 | + "\n", |
| 226 | + "dist = ox.distributions.Normal(0.0, 1.0)\n", |
| 227 | + "samples = dist.sample([1000]).numpy()\n", |
| 228 | + "print(f\"Normal(0,1) 1k sample mean={samples.mean():.3f}, std={samples.std():.3f}\")" |
| 229 | + ] |
| 230 | + }, |
| 231 | + { |
| 232 | + "cell_type": "markdown", |
| 233 | + "metadata": {}, |
| 234 | + "source": [ |
| 235 | + "## 6. Zero-Copy NumPy / PyTorch DLPack Interop & CPU Speed Benchmark" |
| 236 | + ] |
| 237 | + }, |
| 238 | + { |
| 239 | + "cell_type": "code", |
| 240 | + "execution_count": null, |
| 241 | + "metadata": {}, |
| 242 | + "outputs": [], |
| 243 | + "source": [ |
104 | 244 | "x_np = ox.randn([32, 128, 768]).numpy()\n", |
105 | 245 | "xo = ox.from_numpy(x_np)\n", |
106 | 246 | "for _ in range(3):\n", |
107 | 247 | " _ = xo.softmax(-1)\n", |
108 | 248 | "t0 = time.perf_counter()\n", |
109 | | - "for _ in range(20):\n", |
| 249 | + "for _ in range(25):\n", |
110 | 250 | " _ = xo.softmax(-1)\n", |
111 | | - "ox_ms = (time.perf_counter() - t0) / 20 * 1000\n", |
| 251 | + "ox_ms = (time.perf_counter() - t0) / 25 * 1000\n", |
112 | 252 | "\n", |
113 | 253 | "try:\n", |
114 | 254 | " import torch\n", |
115 | | - " xt = torch.utils.dlpack.from_dlpack(xo)\n", |
| 255 | + " xt = torch.randn(32, 128, 768)\n", |
| 256 | + " xo_dl = ox.from_dlpack(xt)\n", |
| 257 | + " xt_rt = torch.utils.dlpack.from_dlpack(xo_dl)\n", |
| 258 | + " assert xt_rt.data_ptr() == xt.data_ptr()\n", |
116 | 259 | " for _ in range(3):\n", |
117 | 260 | " _ = torch.softmax(xt, -1)\n", |
118 | 261 | " t0 = time.perf_counter()\n", |
119 | | - " for _ in range(20):\n", |
| 262 | + " for _ in range(25):\n", |
120 | 263 | " _ = torch.softmax(xt, -1)\n", |
121 | | - " pt_ms = (time.perf_counter() - t0) / 20 * 1000\n", |
122 | | - " print(f\"softmax [32,128,768]: Oxideon={ox_ms:.2f} ms, PyTorch={pt_ms:.2f} ms\")\n", |
| 264 | + " pt_ms = (time.perf_counter() - t0) / 25 * 1000\n", |
| 265 | + " print(f\"Zero-copy DLPack verified! softmax [32,128,768]: Oxideon={ox_ms:.2f} ms, PyTorch={pt_ms:.2f} ms\")\n", |
123 | 266 | "except ImportError:\n", |
124 | 267 | " print(f\"softmax [32,128,768]: Oxideon={ox_ms:.2f} ms (install torch to compare)\")" |
125 | 268 | ] |
126 | 269 | } |
127 | 270 | ], |
128 | 271 | "metadata": { |
| 272 | + "colab": { |
| 273 | + "name": "Oxideon Quickstart & Showcase", |
| 274 | + "provenance": [] |
| 275 | + }, |
129 | 276 | "kernelspec": { |
130 | 277 | "display_name": "Python 3", |
131 | 278 | "language": "python", |
|
0 commit comments