Skip to content

Commit d8d105d

Browse files
committed
docs(colab,readme): expand Colab showcase notebook and enlarge browser/Colab CTA badges
1 parent 6c03ae3 commit d8d105d

2 files changed

Lines changed: 190 additions & 42 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66

77
**A fast, Hackable Deep Learning & Tensor Library in Rust — with a PyTorch-friendly Python API.**
88

9-
[![Browser demo](https://img.shields.io/badge/browser%20demo-run%20Oxideon%20in%20your%20browser-brightgreen.svg)](https://voidstackloop.github.io/oxideon/)
10-
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/voidstackloop/oxideon/blob/main/examples/oxideon_quickstart.ipynb)
9+
<a href="https://voidstackloop.github.io/oxideon/"><img src="https://img.shields.io/badge/▶_RUN_IN_YOUR_BROWSER-Live_WebAssembly_Demo-10b981?style=for-the-badge&logo=webassembly&logoColor=white" alt="Run Oxideon in your browser"></a>
10+
<a href="https://colab.research.google.com/github/voidstackloop/oxideon/blob/main/examples/oxideon_quickstart.ipynb"><img src="https://img.shields.io/badge/OPEN_IN_GOOGLE_COLAB-Interactive_Showcase_Notebook-F9AB00?style=for-the-badge&logo=googlecolab&logoColor=white" alt="Open In Google Colab"></a>
11+
1112
[![Portfolio](https://img.shields.io/badge/portfolio-voidstackloop-blueviolet.svg)](https://github.com/voidstackloop/portfolio)
1213

1314
[![Version](https://img.shields.io/badge/version-v0.1.0-blue.svg)](https://github.com/voidstackloop/oxideon/releases/tag/v0.1.0)

‎examples/oxideon_quickstart.ipynb‎

Lines changed: 187 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,19 @@
44
"cell_type": "markdown",
55
"metadata": {},
66
"source": [
7-
"# Oxideon Quickstart\n",
7+
"# Oxideon — Interactive Deep Learning & Scientific Computing Showcase\n",
88
"\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",
1417
"\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/"
1620
]
1721
},
1822
{
@@ -21,7 +25,17 @@
2125
"metadata": {},
2226
"outputs": [],
2327
"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`"
2539
]
2640
},
2741
{
@@ -30,19 +44,22 @@
3044
"metadata": {},
3145
"outputs": [],
3246
"source": [
33-
"import oxideon as ox\n",
34-
"\n",
35-
"# 1. Zero-copy strided views\n",
3647
"x = ox.Tensor.arange(0.0, 24.0, 1.0).reshape([2, 3, 4])\n",
3748
"v = x.transpose(0, 2)\n",
3849
"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",
4051
"\n",
41-
"# 2. Einops-style rearrange & channels_last\n",
4252
"img = ox.randn([2, 8, 4, 4])\n",
4353
"nhwc = img.rearrange(\"b c h w -> b h w c\")\n",
4454
"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`"
4663
]
4764
},
4865
{
@@ -51,13 +68,27 @@
5168
"metadata": {},
5269
"outputs": [],
5370
"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",
5573
"x = ox.Tensor.from_slice([3.0], [1], requires_grad=True)\n",
5674
"y = x.powf(4.0)\n",
5775
"dy = ox.grad([y], [x], create_graph=True)[0]\n",
5876
"d2y = ox.grad([dy], [x], create_graph=True)[0]\n",
5977
"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"
6192
]
6293
},
6394
{
@@ -66,30 +97,79 @@
6697
"metadata": {},
6798
"outputs": [],
6899
"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",
72121
" 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",
76127
"\n",
77128
" 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",
79132
"\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",
84136
"\n",
85-
"for step in range(40):\n",
137+
"for step in range(180):\n",
86138
" 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",
89141
" loss.backward()\n",
90142
" 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"
93173
]
94174
},
95175
{
@@ -98,34 +178,101 @@
98178
"metadata": {},
99179
"outputs": [],
100180
"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",
103185
"\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": [
104244
"x_np = ox.randn([32, 128, 768]).numpy()\n",
105245
"xo = ox.from_numpy(x_np)\n",
106246
"for _ in range(3):\n",
107247
" _ = xo.softmax(-1)\n",
108248
"t0 = time.perf_counter()\n",
109-
"for _ in range(20):\n",
249+
"for _ in range(25):\n",
110250
" _ = xo.softmax(-1)\n",
111-
"ox_ms = (time.perf_counter() - t0) / 20 * 1000\n",
251+
"ox_ms = (time.perf_counter() - t0) / 25 * 1000\n",
112252
"\n",
113253
"try:\n",
114254
" 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",
116259
" for _ in range(3):\n",
117260
" _ = torch.softmax(xt, -1)\n",
118261
" t0 = time.perf_counter()\n",
119-
" for _ in range(20):\n",
262+
" for _ in range(25):\n",
120263
" _ = 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",
123266
"except ImportError:\n",
124267
" print(f\"softmax [32,128,768]: Oxideon={ox_ms:.2f} ms (install torch to compare)\")"
125268
]
126269
}
127270
],
128271
"metadata": {
272+
"colab": {
273+
"name": "Oxideon Quickstart & Showcase",
274+
"provenance": []
275+
},
129276
"kernelspec": {
130277
"display_name": "Python 3",
131278
"language": "python",

0 commit comments

Comments
 (0)