{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "toc_visible": true, "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 🐝 ML in Elixir — JAX Companion\n", "\n", "This notebook mirrors the [Elixir Livebook template](../ml_e2e_template.livemd)\n", "from *Machine Learning in Elixir* by Sean Moriarity, implemented in **JAX**.\n", "\n", "JAX is Google's numerical computing library — the closest Python counterpart to Elixir's **Nx**.\n", "\n", "| Elixir (Nx/Axon) | JAX (Python) | Purpose |\n", "|-----------------|-------------|----------|\n", "| `Nx` | `jax.numpy` | Tensors, ops |\n", "| `Nx.Defn.grad` | `jax.grad` | Automatic differentiation |\n", "| `EXLA` | `jax.jit` | JIT compilation / GPU |\n", "| `Bumblebee` | `transformers` + `jax` | Pre-trained models |\n", "| `Axon` | `flax` | Neural networks |\n", "| `Nx.Serving` | `jax.lax.map` / `pmap` | Batched inference |\n", "| `Kino` | `ipywidgets` | Interactive UI |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 0 — Install & Configure" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -q jax[cuda12]==0.4.35 flax optax transformers datasets accelerate scikit-learn numpy matplotlib" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import jax\n", "import jax.numpy as jnp\n", "from jax import grad, jit, vmap, pmap\n", "import flax.linen as nn\n", "import optax\n", "from transformers import pipeline, AutoTokenizer, FlaxAutoModel\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.metrics import classification_report\n", "import matplotlib.pyplot as plt\n", "\n", "device = jax.devices()[0]\n", "print(f\"JAX version: {jax.__version__}\")\n", "print(f\"Device: {device}\")\n", "print(f\"Backend: {device.platform}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 — JAX Foundations (Nx equivalent)\n", "\n", "JAX provides NumPy-like API with automatic differentiation and JIT compilation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Tensors: Nx.tensor → jnp.array\n", "scalar = jnp.float64(3.14)\n", "vector = jnp.array([1.0, 2.0, 3.0])\n", "matrix = jnp.array([[1, 2, 3], [4, 5, 6]])\n", "\n", "print(f\"scalar shape: {scalar.shape}, dtype: {scalar.dtype}\")\n", "print(f\"vector shape: {vector.shape}, dtype: {vector.dtype}\")\n", "print(f\"matrix shape: {matrix.shape}, dtype: {matrix.dtype}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Operations: Nx.add/multiply/dot → jnp.add/... (same API!)\n", "a = jnp.array([1.0, 2.0, 3.0])\n", "b = jnp.array([10.0, 20.0, 30.0])\n", "\n", "print(f\"add: {a + b}\")\n", "print(f\"multiply: {a * b}\")\n", "print(f\"dot: {jnp.dot(a, b)}\")\n", "print(f\"sum: {jnp.sum(a)}\")\n", "print(f\"mean: {jnp.mean(a)}\")\n", "print(f\"std: {jnp.std(a)}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Automatic differentiation: Nx.Defn.grad → jax.grad\n", "def f(x):\n", " return x**3 + 2 * x**2 # f(x) = x³ + 2x²\n", "\n", "grad_f = grad(f) # Symbolic gradient\n", "\n", "x = 3.0\n", "print(f\"f(3) = {f(x)}\")\n", "print(f\"f'(3) = {grad_f(x)}\")\n", "print(f\"expected = 3*9 + 2*2*3 = {3*9 + 2*2*3}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# JIT compilation: Nx.Defn.jit → jax.jit\n", "@jit\n", "def fast_sigmoid(x):\n", " return 1 / (1 + jnp.exp(-x))\n", "\n", "input_arr = jnp.array([[-2.0, -1.0, 0.0, 1.0, 2.0]])\n", "result = fast_sigmoid(input_arr)\n", "print(f\"JIT compiled sigmoid: {result}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 — Pre-trained NLP (Bumblebee equivalent)\n", "\n", "In Elixir: `Bumblebee.load_model({:hf, \"...\"})`\n", "In Python/JAX: `transformers` + `flax` or `pipeline()`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.1 Fill-Mask (BERT)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fill_mask = pipeline(\"fill-mask\", model=\"google-bert/bert-base-uncased\")\n", "results = fill_mask(\"Elixir is a [MASK] language.\")\n", "for r in results:\n", " print(f\" {r['score']:.4f} {r['token_str']:15s} {r['sequence']}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.2 Sentiment Analysis" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sentiment = pipeline(\n", " \"sentiment-analysis\",\n", " model=\"distilbert/distilbert-base-uncased-finetuned-sst-2-english\"\n", ")\n", "\n", "texts = [\n", " \"Machine learning in Elixir is amazing!\",\n", " \"This tutorial is boring and confusing.\",\n", " \"The BEAM VM handles concurrent ML workloads well.\",\n", "]\n", "\n", "for text in texts:\n", " result = sentiment(text)[0]\n", " print(f\" {result['label']:8s} {result['score']:.4f} ← \\\"{text[:50]}\\\"\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.3 Named Entity Recognition" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ner = pipeline(\"ner\", model=\"dslim/bert-base-NER\", aggregation_strategy=\"simple\")\n", "text = \"Sean Moriarity wrote Machine Learning in Elixir for Pragmatic Bookshelf.\"\n", "entities = ner(text)\n", "for e in entities:\n", " print(f\" {e['entity_group']:8s} {e['score']:.4f} {e['word']}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.4 Zero-Shot Classification" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "zs_classifier = pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\n", "\n", "article = \"\"\"\n", "Nx brings numerical computing to the BEAM, enabling machine learning\n", "pipelines that leverage Elixir's concurrency and fault tolerance.\n", "\"\"\"\n", "\n", "labels = [\"technology\", \"sports\", \"politics\", \"science\", \"finance\"]\n", "result = zs_classifier(article, labels)\n", "\n", "for label, score in zip(result[\"labels\"], result[\"scores\"]):\n", " bar = \"█\" * int(score * 30)\n", " print(f\" {label:12s} {score:.4f} {bar}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.5 Sentence Embeddings & Similarity" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sentence_transformers import SentenceTransformer\n", "\n", "emb_model = SentenceTransformer(\"sentence-transformers/all-MiniLM-L6-v2\")\n", "\n", "sentences = [\n", " \"Nx provides numerical computing for Elixir\",\n", " \"Axon is a neural network library built on Nx\",\n", " \"Bumblebee connects Elixir to the Hugging Face Hub\",\n", " \"I enjoy cooking Italian food on weekends\",\n", "]\n", "\n", "embeddings = emb_model.encode(sentences)\n", "\n", "query = \"How do I build neural networks in Elixir?\"\n", "query_emb = emb_model.encode([query])\n", "\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "sims = cosine_similarity(query_emb, embeddings)[0]\n", "ranked = sorted(zip(sentences, sims), key=lambda x: -x[1])\n", "\n", "print(f'Query: \"{query}\"\\n')\n", "for sent, sim in ranked:\n", " print(f\" {sim:.4f} {sent}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.6 Text Generation (GPT-2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text_gen = pipeline(\"text-generation\", model=\"openai-community/gpt2\")\n", "prompt = \"Machine learning in Elixir is\"\n", "output = text_gen(prompt, max_new_tokens=50, num_return_sequences=1)\n", "print(output[0][\"generated_text\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.7 Image Classification (ViT)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from PIL import Image\n", "import requests\n", "\n", "img_cls = pipeline(\"image-classification\", model=\"google/vit-base-patch16-224\")\n", "img_url = \"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg\"\n", "image = Image.open(requests.get(img_url, stream=True).raw)\n", "results = img_cls(image)\n", "for r in results[:5]:\n", " print(f\" {r['score']:.4f} {r['label']}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.8 Speech-to-Text (Whisper)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "asr = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-tiny\")\n", "audio_url = \"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac\"\n", "result = asr(audio_url)\n", "print(f\"Transcription: {result['text']}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.9 Image Generation (Stable Diffusion)\n", "\n", "> Requires GPU. JAX version uses `diffusers` with JAX backend." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# JAX Stable Diffusion (using diffusers with JAX)\n", "try:\n", " from diffusers import StableDiffusionPipeline\n", " import torch as _torch\n", " \n", " # Note: diffusers primarily supports PyTorch, JAX version is experimental\n", " # For production JAX SD, use ` JaxDM` or similar\n", " sd_pipe = StableDiffusionPipeline.from_pretrained(\n", " \"CompVis/stable-diffusion-v1-4\",\n", " torch_dtype=_torch.float16 if _torch.cuda.is_available() else _torch.float32,\n", " )\n", " \n", " prompt = \"a bee programming in Elixir, highly detailed, 4k\"\n", " image = sd_pipe(prompt, num_inference_steps=20).images[0]\n", " display(image)\n", "except Exception as e:\n", " print(f\"SD requires GPU/memory: {e}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2.10 Model Export (ONNX / GGUF) **Export to ONNX (experimental for Flax models)** ```python # Install jax2onnx for conversion # pip install jax2onnx onnx # Example: Export the Flax MLP model to ONNX import jax2onnx import onnx # Assume `model` is the Flax model defined earlier and `params` are its trained parameters # Define a callable applying the model def apply_model(x): return model.apply(params, x, training=False) # Convert a dummy input shape to ONNX input_shape = (1, n_features) onnx_model = jax2onnx.convert(apply_model, input_shape, output_path="mlp.onnx") print("ONNX model saved as mlp.onnx") ``` **Convert to GGUF** (decoder‑only models, e.g., GPT‑2) ```bash pip install gguf-converter # Convert the ONNX model to GGUF gguf-converter --onnx mlp.onnx --output mlp.gguf ``` > **Note:** GGUF conversion currently targets decoder architectures. For encoder‑only models you may still use ONNX directly with `onnxruntime`. --- ## 3 — Custom Training with Flax (Axon equivalent)", "\n", "Flax is Google's neural network library for JAX — mirrors Axon's functional design." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Synthetic data (same as Livebook)\n", "import numpy as np\n", "np.random.seed(42)\n", "n_samples, n_features, n_classes = 2000, 4, 3\n", "\n", "centers = np.random.randn(n_classes, n_features) * 2\n", "labels_raw = np.random.randint(0, n_classes, n_samples)\n", "noise = np.random.randn(n_samples, n_features) * 0.4\n", "X = centers[labels_raw] + noise\n", "X = (X - X.mean(axis=0)) / X.std(axis=0)\n", "Y = np.eye(n_classes)[labels_raw]\n", "\n", "X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)\n", "\n", "# Convert to JAX arrays\n", "X_train_j = jnp.array(X_train)\n", "Y_train_j = jnp.array(Y_train)\n", "X_test_j = jnp.array(X_test)\n", "Y_test_j = jnp.array(Y_test)\n", "\n", "print(f\"Train: {len(X_train)} | Test: {len(X_test)} | Features: {n_features} | Classes: {n_classes}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Flax model (mirrors Axon build)\n", "class MLP(nn.Module):\n", " n_classes: int\n", " \n", " @nn.compact\n", " def __call__(self, x, training: bool = True):\n", " x = nn.Dense(64)(x)\n", " x = nn.relu(x)\n", " x = nn.BatchNorm(use_running_average=not training)(x)\n", " x = nn.Dropout(0.2, deterministic=not training)(x)\n", " \n", " x = nn.Dense(32)(x)\n", " x = nn.relu(x)\n", " x = nn.BatchNorm(use_running_average=not training)(x)\n", " x = nn.Dropout(0.2, deterministic=not training)(x)\n", " \n", " x = nn.Dense(self.n_classes)(x)\n", " x = nn.softmax(x, axis=-1)\n", " return x\n", "\n", "model = MLP(n_classes=n_classes)\n", "print(model)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Initialize parameters\n", "dummy_input = jnp.ones((1, n_features))\n", "variables = model.init(jax.random.key(42), dummy_input, training=False)\n", "params = variables[\"params\"]\n", "print(f\"Parameters initialized: {sum(p.size for p in jax.tree_util.tree_leaves(params))}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Training step function\n", "def cross_entropy_loss(logits, labels):\n", " return -jnp.mean(jnp.sum(labels * jnp.log(logits + 1e-8), axis=-1))\n", "\n", "@jit\n", "def train_step(params, batch):\n", " x, y = batch\n", " \n", " def loss_fn(p):\n", " logits = model.apply(p, x, training=True)\n", " return cross_entropy_loss(logits, y)\n", " \n", " loss, grads = jax.value_and_grad(loss_fn)(params)\n", " updates, opt_state = optimizer.update(grads, opt_state)\n", " new_params = optax.apply_updates(params, updates)\n", " return loss, new_params\n", "\n", "@jit \n", "def accuracy(params, x, y):\n", " logits = model.apply(params, x, training=False)\n", " preds = jnp.argmax(logits, axis=-1)\n", " true = jnp.argmax(y, axis=-1)\n", " return jnp.mean(preds == true)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Training loop\n", "optimizer = optax.adam(0.001)\n", "opt_state = optimizer.init(params)\n", "\n", "batch_size = 64\n", "epochs = 30\n", "\n", "for epoch in range(epochs):\n", " # Shuffle\n", " perm = jax.random.permutation(jax.random.key(epoch), len(X_train_j))\n", " X_shuffled = X_train_j[perm]\n", " Y_shuffled = Y_train_j[perm]\n", " \n", " epoch_loss = 0\n", " for i in range(0, len(X_train_j), batch_size):\n", " batch_x = X_shuffled[i:i+batch_size]\n", " batch_y = Y_shuffled[i:i+batch_size]\n", " loss, params = train_step(params, (batch_x, batch_y))\n", " epoch_loss += loss\n", " \n", " if (epoch + 1) % 10 == 0:\n", " acc = accuracy(params, X_test_j, Y_test_j)\n", " print(f\"Epoch {epoch+1:3d} loss={epoch_loss/len(X_train_j):.4f} acc={acc:.2%}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Final evaluation\n", "final_acc = accuracy(params, X_test_j, Y_test_j)\n", "print(f\"Final test accuracy: {final_acc:.2%}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Visualize\n", "logits = model.apply(params, X_test_j, training=False)\n", "preds = jnp.argmax(logits, axis=-1)\n", "true = jnp.argmax(Y_test_j, axis=-1)\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n", "for cls in range(n_classes):\n", " mask = true == cls\n", " axes[0].scatter(X_test[mask, 0], X_test[mask, 1], label=f\"Class {cls}\", alpha=0.6)\n", " mask2 = preds == cls\n", " axes[1].scatter(X_test[mask2, 0], X_test[mask2, 1], label=f\"Class {cls}\", alpha=0.6)\n", "axes[0].set_title(\"Actual\")\n", "axes[1].set_title(\"Predicted\")\n", "for ax in axes:\n", " ax.legend()\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 — Summary\n", "\n", "| Pipeline Stage | Elixir (Livebook) | JAX (This Notebook) |\n", "|---------------|-------------------|----------------------|\n", "| Tensors | `Nx.tensor` | `jnp.array` |\n", "| Gradients | `Nx.Defn.grad` | `jax.grad` |\n", "| JIT | `EXLA.Backend` | `jax.jit` |\n", "| Pre-trained | `Bumblebee` | `transformers` + `flax` |\n", "| Neural Net | `Axon` | `flax.linen` |\n", "| Optimizer | `Axon.Optimizers` | `optax` |\n", "| Training Loop | `Axon.Loop` | Custom (JAX) |\n", "\n", "### Deploy\n", "\n", "* **Colab**: Open this `.ipynb` directly\n", "* **Kaggle**: Upload as new notebook\n", "* **HF Spaces**: Use with `sdk: docker` (JAX requires GPU)" ] } ] }