{ "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": [ "# 🐝 Machine Learning in Elixir β€” Python Companion ## Skills - `hf_cli.md` – Hugging Face CLI usage - `hf_jobs.md` – Running workloads on HF Jobs - `training_trl.md` – TRL model training - `hf_dataset_viewer.md` – Dataset Viewer API - `gradio.md` – Gradio UI integration - *(Full catalog at https://skills.sh/huggingface/skills)* \n", "\n", "This notebook mirrors the [Livebook template](../ml_elixir_learning/ml_e2e_template.livemd)\n", "from *Machine Learning in Elixir* by Sean Moriarity, implemented in Python for\n", "**Google Colab** and **Kaggle** compatibility.\n", "\n", "| Elixir | Python | Purpose |\n", "|--------|--------|----------|\n", "| `Nx` | `numpy` | Numerical computing |\n", "| `Axon` | `torch` | Neural networks |\n", "| `Bumblebee` | `transformers` | Pre-trained models |\n", "| `Nx.Serving` | `pipeline()` | Batched inference |\n", "| `Kino` | `gradio` | Interactive UI |\n", "| `EXLA` | CUDA | GPU acceleration |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 0 β€” Install & Configure" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install -q transformers torch datasets accelerate gradio scikit-learn numpy matplotlib" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import torch\n", "from transformers import pipeline, AutoModel, AutoTokenizer, AutoModelForSequenceClassification\n", "from transformers import AutoModelForTokenClassification, AutoModelForCausalLM\n", "from transformers import CLIPProcessor, CLIPModel\n", "import gradio as gr\n", "from sklearn.metrics import accuracy_score, classification_report\n", "from sklearn.model_selection import train_test_split\n", "import matplotlib.pyplot as plt\n", "\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "print(f\"Device: {device}\")\n", "print(f\"PyTorch: {torch.__version__}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 β€” NumPy Foundations (Nx equivalent)\n", "\n", "The Elixir `Nx` library provides tensor operations. Python's `numpy` is the direct\n", "counterpart." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Tensors (Nx.tensor β†’ np.array) ---\n", "scalar = np.float64(3.14)\n", "vector = np.array([1.0, 2.0, 3.0])\n", "matrix = np.array([[1, 2, 3], [4, 5, 6]])\n", "\n", "print(f\"scalar shape={np.shape(scalar)} dtype={scalar.dtype}\")\n", "print(f\"vector shape={np.shape(vector)} dtype={vector.dtype}\")\n", "print(f\"matrix shape={np.shape(matrix)} dtype={matrix.dtype}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Operations (Nx.add β†’ np.add, etc.) ---\n", "a = np.array([1.0, 2.0, 3.0])\n", "b = np.array([10.0, 20.0, 30.0])\n", "\n", "print(f\"add: {a + b}\")\n", "print(f\"multiply: {a * b}\")\n", "print(f\"dot: {np.dot(a, b)}\")\n", "print(f\"sum: {np.sum(a)}\")\n", "print(f\"mean: {np.mean(a)}\")\n", "print(f\"std: {np.std(a)}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Automatic differentiation (Nx.Defn.grad β†’ torch.autograd) ---\n", "x = torch.tensor(3.0, requires_grad=True)\n", "f = x**3 + 2 * x**2 # f(x) = xΒ³ + 2xΒ²\n", "f.backward()\n", "print(f\"f(3) = {f.item()}\")\n", "print(f\"f'(3) = {x.grad.item()}\")\n", "print(f\"expected = 3*9 + 2*2*3 = {3*9 + 2*2*3}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 β€” Pre-trained NLP (Bumblebee equivalent)\n", "\n", "In Elixir: `Bumblebee.load_model({:hf, \"...\"})` + `Nx.Serving.run()`\n", "\n", "In Python: `transformers.pipeline()` is the equivalent one-liner." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.1 Fill-Mask (BERT)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Elixir: {:ok, model} = Bumblebee.load_model({:hf, \"google-bert/bert-base-uncased\"})\n", "# serving = Bumblebee.Text.fill_mask(model, tokenizer)\n", "# Nx.Serving.run(serving, \"Elixir is a [MASK] language.\")\n", "\n", "# Python equivalent:\n", "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 (DistilBERT)" ] }, { "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", " \"I love how functional programming simplifies ML pipelines.\",\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", "\n", "text = \"Sean Moriarity wrote Machine Learning in Elixir for Pragmatic Bookshelf. He lives in Austin, Texas.\"\n", "entities = ner(text)\n", "\n", "print(f\"Input: {text}\\n\")\n", "for e in entities:\n", " print(f\" {e['entity_group']:8s} {e['score']:.4f} {e['word']:30s} (pos {e['start']}-{e['end']})\")" ] }, { "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", "Bumblebee provides access to thousands of pre-trained models from\n", "the Hugging Face Hub directly in Livebook.\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 transformers import AutoModel\n", "import torch.nn.functional as F\n", "\n", "emb_tokenizer = AutoTokenizer.from_pretrained(\"sentence-transformers/all-MiniLM-L6-v2\")\n", "emb_model = AutoModel.from_pretrained(\"sentence-transformers/all-MiniLM-L6-v2\")\n", "\n", "def embed(texts):\n", " inputs = emb_tokenizer(texts, padding=True, truncation=True, return_tensors=\"pt\")\n", " with torch.no_grad():\n", " outputs = emb_model(**inputs)\n", " # Mean pooling\n", " mask = inputs[\"attention_mask\"].unsqueeze(-1)\n", " embeddings = (outputs.last_hidden_state * mask).sum(1) / mask.sum(1)\n", " return F.normalize(embeddings, p=2, dim=1)\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", " \"The weather forecast predicts rain tomorrow\",\n", "]\n", "\n", "embeddings = embed(sentences)\n", "\n", "query = \"How do I build neural networks in Elixir?\"\n", "query_emb = embed([query])\n", "\n", "similarities = F.cosine_similarity(query_emb, embeddings)\n", "ranked = similarities.argsort(descending=True)\n", "\n", "print(f'Query: \"{query}\"\\n')\n", "for idx in ranked:\n", " print(f\" {similarities[idx]:.4f} {sentences[idx]}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.6 Text Generation (GPT-2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text_gen = pipeline(\n", " \"text-generation\",\n", " model=\"openai-community/gpt2\",\n", " device=device,\n", ")\n", "\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 (Vision Transformer)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Elixir: Bumblebee.Vision.ImageClassification.image_classification(model, featurizer)\n", "# Python: pipeline(\"image-classification\")\n", "\n", "from PIL import Image\n", "import requests\n", "\n", "img_cls = pipeline(\"image-classification\", model=\"google/vit-base-patch16-224\")\n", "\n", "# Download sample image\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", "\n", "results = img_cls(image)\n", "print(f\"Image: {image.size}\")\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": [ "# Elixir: Bumblebee.Audio.speech_to_text(model, featurizer, tokenizer, generation_config)\n", "# Python: pipeline(\"automatic-speech-recognition\")\n", "\n", "asr = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-tiny\")\n", "\n", "# Sample audio from Hugging Face\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. On CPU this will be very slow." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Elixir: Bumblebee.Diffusion.StableDiffusion.text_to_image(...)\n", "# Python: diffusers library\n", "\n", "try:\n", " from diffusers import StableDiffusionPipeline\n", "\n", " sd_pipe = StableDiffusionPipeline.from_pretrained(\n", " \"CompVis/stable-diffusion-v1-4\",\n", " torch_dtype=torch.float16 if device == \"cuda\" else torch.float32,\n", " ).to(device)\n", "\n", " prompt = \"a photograph of a bee programming in elixir, highly detailed, 4k\"\n", " image = sd_pipe(prompt, num_inference_steps=20).images[0]\n", " display(image)\n", "except ImportError:\n", " print(\"Install diffusers: pip install diffusers\")\n", "except Exception as e:\n", " print(f\"Stable Diffusion error (GPU recommended): {e}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 β€” Custom Training (Axon equivalent)\n", "\n", "Train a classifier from scratch using PyTorch β€” mirrors the Axon Livebook section." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch.nn as nn\n", "from torch.utils.data import DataLoader, TensorDataset\n", "\n", "# --- Synthetic data (same as Livebook) ---\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", "\n", "# Normalize\n", "X = (X - X.mean(axis=0)) / X.std(axis=0)\n", "\n", "# One-hot\n", "Y = np.eye(n_classes)[labels_raw]\n", "\n", "# Split\n", "X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)\n", "\n", "# To tensors\n", "X_train_t = torch.FloatTensor(X_train)\n", "Y_train_t = torch.FloatTensor(Y_train)\n", "X_test_t = torch.FloatTensor(X_test)\n", "Y_test_t = torch.FloatTensor(Y_test)\n", "\n", "train_loader = DataLoader(TensorDataset(X_train_t, Y_train_t), batch_size=64, shuffle=True)\n", "test_loader = DataLoader(TensorDataset(X_test_t, Y_test_t), batch_size=64)\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": [ "# --- Model (mirrors Axon build) ---\n", "class MLP(nn.Module):\n", " def __init__(self):\n", " super().__init__()\n", " self.net = nn.Sequential(\n", " nn.Linear(n_features, 64),\n", " nn.ReLU(),\n", " nn.BatchNorm1d(64),\n", " nn.Dropout(0.2),\n", " nn.Linear(64, 32),\n", " nn.ReLU(),\n", " nn.BatchNorm1d(32),\n", " nn.Dropout(0.2),\n", " nn.Linear(32, n_classes),\n", " nn.Softmax(dim=1),\n", " )\n", "\n", " def forward(self, x):\n", " return self.net(x)\n", "\n", "model = MLP().to(device)\n", "print(model)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Training loop ---\n", "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n", "criterion = nn.CrossEntropyLoss()\n", "\n", "for epoch in range(30):\n", " model.train()\n", " epoch_loss = 0\n", " for xb, yb in train_loader:\n", " xb, yb = xb.to(device), yb.to(device)\n", " preds = model(xb)\n", " loss = criterion(preds, yb.argmax(dim=1))\n", " optimizer.zero_grad()\n", " loss.backward()\n", " optimizer.step()\n", " epoch_loss += loss.item()\n", "\n", " if (epoch + 1) % 10 == 0:\n", " model.eval()\n", " correct = 0\n", " with torch.no_grad():\n", " for xb, yb in test_loader:\n", " xb, yb = xb.to(device), yb.to(device)\n", " preds = model(xb)\n", " correct += (preds.argmax(1) == yb.argmax(1)).sum().item()\n", " acc = correct / len(X_test) * 100\n", " print(f\"Epoch {epoch+1:3d} loss={epoch_loss/len(train_loader):.4f} test_acc={acc:.1f}%\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Final evaluation ---\n", "model.eval()\n", "with torch.no_grad():\n", " all_preds = []\n", " all_true = []\n", " for xb, yb in test_loader:\n", " preds = model(xb.to(device)).argmax(1).cpu().numpy()\n", " all_preds.extend(preds)\n", " all_true.extend(yb.argmax(1).numpy())\n", "\n", "print(classification_report(all_true, all_preds, target_names=[f\"Class {i}\" for i in range(n_classes)]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Visualize ---\n", "fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n", "\n", "for cls in range(n_classes):\n", " mask = np.array(all_true) == cls\n", " axes[0].scatter(X_test[mask, 0], X_test[mask, 1], label=f\"Class {cls}\", alpha=0.6)\n", "axes[0].set_title(\"Actual\")\n", "axes[0].legend()\n", "\n", "for cls in range(n_classes):\n", " mask = np.array(all_preds) == cls\n", " axes[1].scatter(X_test[mask, 0], X_test[mask, 1], label=f\"Class {cls}\", alpha=0.6)\n", "axes[1].set_title(\"Predicted\")\n", "axes[1].legend()\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 β€” Interactive Gradio UI (Kino equivalent) ### 2.10 Model Export (ONNX / GGUF) **Export to ONNX** (requires `onnxruntime` and `torch.onnx`): ```python # Export the sentiment analysis model to ONNX import torch from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased-finetuned-sst-2-english") # Dummy input for tracing dummy_input = torch.tensor([[101, 2023, 2003, 1037, 2742, 102]]) torch.onnx.export(model, dummy_input, "sentiment.onnx", input_names=["input_ids"], output_names=["logits"], opset_version=12) print("ONNX model saved as sentiment.onnx") ``` **Convert to GGUF** (for llama.cpp style inference, works for decoder models like GPT-2): ```bash # Install gguf-converter if needed pip install gguf-converter # Convert the exported ONNX model gguf-converter --onnx sentiment.onnx --output sentiment.gguf ``` > **Note:** GGUF currently supports decoder‑only architectures. For encoder‑only models you may need to adapt the conversion script or use `onnxruntime` directly. --- ## 4 β€” Interactive Gradio UI (Kino equivalent)\n", "\n", "Gradio is the Python equivalent of Elixir's Kino for building interactive UIs\n", "that wrap ML models." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Sentiment Analysis UI ---\n", "def classify_sentiment(text):\n", " result = sentiment(text)[0]\n", " return {r[\"label\"]: r[\"score\"] for r in sentiment(text)}\n", "\n", "sentiment_ui = gr.Interface(\n", " fn=classify_sentiment,\n", " inputs=gr.Textbox(label=\"Enter text\", placeholder=\"Type something...\"),\n", " outputs=gr.Label(label=\"Sentiment\"),\n", " title=\"🐝 Sentiment Analysis β€” Bumblebee/Transformers\",\n", " description=\"Mirrors the Elixir Livebook sentiment section\",\n", ")\n", "sentiment_ui.launch(share=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Zero-Shot Classification UI ---\n", "def zero_shot(text, labels_str):\n", " labels = [l.strip() for l in labels_str.split(\",\")]\n", " result = zs_classifier(text, labels)\n", " return {l: s for l, s in zip(result[\"labels\"], result[\"scores\"]) }\n", "\n", "zs_ui = gr.Interface(\n", " fn=zero_shot,\n", " inputs=[\n", " gr.Textbox(label=\"Text\", lines=3,\n", " value=\"Elixir's BEAM provides fault-tolerant concurrent ML pipelines.\"),\n", " gr.Textbox(label=\"Labels (comma-separated)\",\n", " value=\"technology, sports, politics, science, finance\"),\n", " ],\n", " outputs=gr.Label(label=\"Classification\"),\n", " title=\"🐝 Zero-Shot Classification\",\n", ")\n", "zs_ui.launch(share=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# --- Text Generation UI ---\n", "def generate(prompt, max_tokens):\n", " output = text_gen(prompt, max_new_tokens=int(max_tokens), do_sample=True)\n", " return output[0][\"generated_text\"]\n", "\n", "gen_ui = gr.Interface(\n", " fn=generate,\n", " inputs=[\n", " gr.Textbox(label=\"Prompt\", value=\"Machine learning in Elixir is\"),\n", " gr.Slider(10, 100, value=50, step=1, label=\"Max tokens\"),\n", " ],\n", " outputs=gr.Textbox(label=\"Generated Text\", lines=5),\n", " title=\"🐝 GPT-2 Text Generation\",\n", ")\n", "gen_ui.launch(share=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 β€” Summary\n", "\n", "| Pipeline Stage | Elixir (Livebook) | Python (Colab/Kaggle) |\n", "|----------------|-------------------|----------------------|\n", "| Tensors | `Nx.tensor` | `np.array` |\n", "| Gradients | `Nx.Defn.grad` | `torch.autograd` |\n", "| GPU | `EXLA.Backend` | `torch.cuda` |\n", "| Pre-trained | `Bumblebee.load_model` | `pipeline()` |\n", "| Fill-Mask | `Bumblebee.Text.fill_mask` | `pipeline(\"fill-mask\")` |\n", "| Sentiment | `Bumblebee.Text.Classification` | `pipeline(\"sentiment-analysis\")` |\n", "| NER | `Bumblebee.Text.TokenClassification` | `pipeline(\"ner\")` |\n", "| Zero-Shot | `Bumblebee.Text.ZeroShotClassification` | `pipeline(\"zero-shot-classification\")` |\n", "| Text Gen | `Bumblebee.Text.generation` | `pipeline(\"text-generation\")` |\n", "| Embeddings | `Bumblebee.Text.TextEmbedding` | `sentence-transformers` |\n", "| Training | `Axon` + `Axon.Loop` | `torch.nn` + training loop |\n", "| Serving | `Nx.Serving` | `gradio.Interface` |\n", "| Interactive UI | `Kino` | `gradio` |\n", "\n", "### Deploy\n", "\n", "* **Colab**: Open this `.ipynb` directly\n", "* **Kaggle**: Upload as a new notebook\n", "* **HF Spaces**: Use the Gradio cells above + `sdk: gradio` in README.md" ] } ] }