""" ML in Elixir — End-to-Edge Template (marimo edition) A reactive Python notebook mirroring the Elixir Livebook template. Built on the marimo reactive notebook framework. ## 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)* Run: marimo edit ml_e2e_marimo.py # Interactive editor marimo run ml_e2e_marimo.py # App mode (no code visible) python ml_e2e_marimo.py # Script mode (terminal output) Deploy: - Hugging Face Spaces (sdk: marimo) - Anywhere Python runs (pip install marimo) """ import marimo __generated_with = "0.19.10" app = marimo.App(width="medium") # ═══════════════════════════════════════════════════════════════════ # 0 — Imports & Setup # ═══════════════════════════════════════════════════════════════════ @app.cell def _(): import marimo as mo return (mo,) @app.cell(hide_code=True) def _(mo): mo.md( r""" # 🐝 Machine Learning in Elixir — marimo Edition This reactive notebook mirrors the **Elixir Livebook template** from *Machine Learning in Elixir* by Sean Moriarity. | Elixir Livebook | This Notebook | Purpose | |-----------------|---------------|----------| | `Nx` | `numpy` | Numerical computing | | `Axon` | `torch` | Neural networks | | `Bumblebee` | `transformers` | Pre-trained models | | `Nx.Serving` | `pipeline()` | Batched inference | | `Kino` | `marimo.ui` | Reactive interactive UI | | `EXLA` | CUDA | GPU acceleration | """ ) return @app.cell def _(): import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, TensorDataset from transformers import ( pipeline, AutoTokenizer, AutoModel, ) from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report import matplotlib.pyplot as plt device = "cuda" if torch.cuda.is_available() else "cpu" mo.md(f"**Device:** `{device}` | **PyTorch:** `{torch.__version__}`") return ( AutoModel, AutoTokenizer, DataLoader, F, TensorDataset, classification_report, device, mo, nn, np, pipeline, plt, torch, train_test_split, ) # ═══════════════════════════════════════════════════════════════════ # 1 — NumPy Foundations (Nx equivalent) # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ## 1 — NumPy Foundations Elixir's `Nx` provides tensors, broadcasting, and automatic differentiation. Python's `numpy` + `torch.autograd` are the direct counterparts. """ ) return @app.cell def _(np): # Tensors: Nx.tensor(...) → np.array(...) scalar = np.float64(3.14) vector = np.array([1.0, 2.0, 3.0]) matrix = np.array([[1, 2, 3], [4, 5, 6]]) tensor_info = ( f"| Type | Shape | Dtype |\n|------|-------|-------|\n" f"| scalar | `{np.shape(scalar)}` | `{scalar.dtype}` |\n" f"| vector | `{np.shape(vector)}` | `{vector.dtype}` |\n" f"| matrix | `{np.shape(matrix)}` | `{matrix.dtype}` |" ) tensor_info return matrix, vector @app.cell def _(np, vector): # Operations: Nx.add/multiply/dot → +/*/np.dot a = np.array([1.0, 2.0, 3.0]) b = np.array([10.0, 20.0, 30.0]) ops_results = { "add": a + b, "multiply": a * b, "dot": np.dot(a, b), "sum": np.sum(a), "mean": np.mean(a), "std": np.std(a), } ops_results return @app.cell def _(mo, torch): # Automatic differentiation: Nx.Defn.grad → torch.autograd x = torch.tensor(3.0, requires_grad=True) f = x**3 + 2 * x**2 # f(x) = x³ + 2x² f.backward() mo.md( f""" **Automatic differentiation** (gradients for training): | | Value | |---|---| | f(3) | `{f.item()}` | | f'(3) | `{x.grad.item()}` | | Expected (3·9 + 2·2·3) | `{3 * 9 + 2 * 2 * 3}` | """ ) return @app.cell def _(mo, np): # Broadcasting: Nx broadcasts automatically, so does numpy mat = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) row = np.array([10.0, 20.0, 30.0]) broadcast_result = mat + row mo.md(f"**Broadcasting** — add row vector to matrix:\n```\n{broadcast_result}\n```") return # ═══════════════════════════════════════════════════════════════════ # 2 — Pre-trained NLP (Bumblebee equivalent) # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ## 2 — Pre-trained NLP (Bumblebee → transformers) In Elixir: `Bumblebee.load_model({:hf, "..."})` + `Nx.Serving.run()` In Python: `transformers.pipeline()` is the one-liner equivalent. """ ) return # --- 2.1 Fill-Mask --- @app.cell def _(mo, pipeline): mo.md("### 2.1 Fill-Mask (BERT)") fill_mask = pipeline("fill-mask", model="google-bert/bert-base-uncased") return (fill_mask,) @app.cell def _(fill_mask, mo): mask_text = mo.ui.text( label="Text with [MASK]", value="Elixir is a [MASK] language." ) mask_text return (mask_text,) @app.cell def _(fill_mask, mask_text, mo): mask_results = [] if "[MASK]" in mask_text.value: raw = fill_mask(mask_text.value) mask_results = [ { "score": round(r["score"], 4), "token": r["token_str"], "sequence": r["sequence"], } for r in raw ] mo.ui.table(mask_results) if mask_results else mo.md( "Enter text with **[MASK]** above." ) return # --- 2.2 Sentiment --- @app.cell def _(mo, pipeline): mo.md("### 2.2 Sentiment Analysis (DistilBERT)") sentiment = pipeline( "sentiment-analysis", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", ) return (sentiment,) @app.cell def _(mo, sentiment): sentiment_input = mo.ui.text( label="Text", value="Machine learning in Elixir is amazing!", ) sentiment_input return (sentiment_input,) @app.cell def _(mo, sentiment, sentiment_input): if sentiment_input.value.strip(): result = sentiment(sentiment_input.value)[0] emoji = "😊" if result["label"] == "POSITIVE" else "😞" mo.md(f"### {emoji} **{result['label']}** ({result['score']:.4f})") else: mo.md("Enter text above.") return # --- 2.3 NER --- @app.cell def _(mo, pipeline): mo.md("### 2.3 Named Entity Recognition (BERT-NER)") ner = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple") return (ner,) @app.cell def _(mo, ner): ner_input = mo.ui.text_area( label="Text", value="Sean Moriarity wrote Machine Learning in Elixir for Pragmatic Bookshelf. He lives in Austin, Texas.", ) ner_input return (ner_input,) @app.cell def _(mo, ner, ner_input): if ner_input.value.strip(): entities = ner(ner_input.value) rows = [ { "Entity": e["word"], "Type": e["entity_group"], "Score": round(e["score"], 4), } for e in entities ] mo.ui.table(rows) if rows else mo.md("No entities found.") else: mo.md("Enter text above.") return # --- 2.4 Zero-Shot --- @app.cell def _(mo, pipeline): mo.md("### 2.4 Zero-Shot Classification") zs = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") return (zs,) @app.cell def _(mo, zs): zs_text = mo.ui.text_area( label="Text", value="Nx brings numerical computing to the BEAM, enabling machine learning pipelines.", ) zs_labels = mo.ui.text( label="Labels (comma-separated)", value="technology, sports, politics, science, finance", ) mo.vstack([zs_text, zs_labels]) return zs_labels, zs_text @app.cell def _(mo, zs, zs_labels, zs_text): if zs_text.value.strip() and zs_labels.value.strip(): labels = [l.strip() for l in zs_labels.value.split(",") if l.strip()] result = zs(zs_text.value, labels) rows = [ {"Label": l, "Score": round(s, 4)} for l, s in zip(result["labels"], result["scores"]) ] mo.ui.table(rows) else: mo.md("Enter text and labels above.") return # --- 2.5 Embeddings --- @app.cell def _(AutoModel, AutoTokenizer, mo): mo.md("### 2.5 Sentence Embeddings & Similarity") emb_tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") emb_model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2") return emb_model, emb_tok @app.cell def _(F, emb_model, emb_tok, mo, torch): def embed_texts(texts): inputs = emb_tok(texts, padding=True, truncation=True, return_tensors="pt") with torch.no_grad(): out = emb_model(**inputs) mask = inputs["attention_mask"].unsqueeze(-1) embs = (out.last_hidden_state * mask).sum(1) / mask.sum(1) return F.normalize(embs, p=2, dim=1) emb_a = mo.ui.text( label="Text A", value="Nx provides numerical computing for Elixir" ) emb_b = mo.ui.text( label="Text B", value="Axon is a neural network library built on Nx" ) mo.vstack([emb_a, emb_b]) return emb_a, emb_b, embed_texts @app.cell def _(emb_a, emb_b, embed_texts, mo): if emb_a.value.strip() and emb_b.value.strip(): embs = embed_texts([emb_a.value, emb_b.value]) import torch.nn.functional as _F score = _F.cosine_similarity(embs[0:1], embs[1:2]).item() mo.md(f"**Cosine Similarity:** `{score:.6f}`") else: mo.md("Enter both texts above.") return # --- 2.6 Text Generation --- @app.cell def _(mo, pipeline): mo.md("### 2.6 Text Generation (GPT-2)") text_gen = pipeline("text-generation", model="openai-community/gpt2") return (text_gen,) @app.cell def _(mo): gen_prompt = mo.ui.text(label="Prompt", value="Machine learning in Elixir is") gen_tokens = mo.ui.slider(start=10, stop=100, value=50, label="Max tokens") gen_temp = mo.ui.slider( start=0.1, stop=2.0, value=0.7, step=0.1, label="Temperature" ) mo.vstack([gen_prompt, gen_tokens, gen_temp]) return gen_prompt, gen_temp, gen_tokens @app.cell def _(gen_prompt, gen_temp, gen_tokens, mo, text_gen): if gen_prompt.value.strip(): output = text_gen( gen_prompt.value, max_new_tokens=gen_tokens.value, temperature=gen_temp.value, do_sample=True, ) generated = output[0]["generated_text"] mo.md(f"```\n{generated}\n```") else: mo.md("Enter a prompt above.") return # ═══════════════════════════════════════════════════════════════════ # 2.7 — Image Classification (ViT) # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ### 2.7 Image Classification (Vision Transformer) Elixir: `Bumblebee.Vision.ImageClassification.image_classification(model, featurizer)` Python: `pipeline("image-classification")` """ ) return @app.cell def _(mo, pipeline): img_cls = pipeline("image-classification", model="google/vit-base-patch16-224") img_upload = mo.ui.file( label="Upload image", filetypes=[".jpg", ".jpeg", ".png", ".webp"], multiple=False, ) img_upload return img_cls, img_upload @app.cell def _(img_cls, img_upload, mo): if img_upload.value: import io from PIL import Image file_info = img_upload.value[0] img = Image.open(io.BytesIO(file_info.contents)).convert("RGB") results = img_cls(img) rows = [{"Label": r["label"], "Score": round(r["score"], 4)} for r in results] mo.vstack([mo.md("**Results:**"), mo.ui.table(rows)]) else: mo.md("Upload an image above to classify.") return # ═══════════════════════════════════════════════════════════════════ # 2.8 — Audio / Speech-to-Text (Whisper) # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ### 2.8 Speech-to-Text (Whisper) Elixir: `Bumblebee.Audio.speech_to_text(model, featurizer, tokenizer, generation_config)` Python: `pipeline("automatic-speech-recognition")` """ ) return @app.cell def _(mo, pipeline): asr = pipeline("automatic-speech-recognition", model="openai/whisper-tiny") audio_upload = mo.ui.file( label="Upload audio (WAV/FLAC/MP3)", filetypes=[".wav", ".flac", ".mp3", ".m4a"], multiple=False, ) audio_upload return asr, audio_upload @app.cell def _(asr, audio_upload, mo): if audio_upload.value: import io import tempfile import os file_info = audio_upload.value[0] suffix = os.path.splitext(file_info.name)[1] or ".wav" with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: tmp.write(file_info.contents) tmp_path = tmp.name result = asr(tmp_path) os.unlink(tmp_path) mo.md(f"**Transcription:**\n\n> {result['text']}") else: mo.md("Upload an audio file above to transcribe.") return # ═══════════════════════════════════════════════════════════════════ # 2.9 — Image Generation (Stable Diffusion) # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ### 2.9 Image Generation (Stable Diffusion) Elixir: `Bumblebee.Diffusion.StableDiffusion.text_to_image(...)` Python: `diffusers` library > Requires GPU with 4GB+ VRAM. Falls back to CPU (very slow). """ ) return @app.cell def _(mo): sd_prompt = mo.ui.text( label="Prompt", value="a photograph of a bee programming in elixir, 4k" ) sd_negative = mo.ui.text(label="Negative prompt", value="blurry, ugly, low quality") sd_steps = mo.ui.slider(start=5, stop=50, value=20, label="Steps") sd_btn = mo.ui.button(label="Generate Image") mo.vstack([sd_prompt, sd_negative, sd_steps, sd_btn]) return sd_btn, sd_negative, sd_prompt, sd_steps @app.cell def _(mo, sd_btn, sd_negative, sd_prompt, sd_steps): if sd_btn.value and sd_prompt.value.strip(): try: from diffusers import StableDiffusionPipeline import torch as _torch device_sd = "cuda" if _torch.cuda.is_available() else "cpu" sd_pipe = StableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", torch_dtype=_torch.float16 if device_sd == "cuda" else _torch.float32, ).to(device_sd) image = sd_pipe( prompt=sd_prompt.value, negative_prompt=sd_negative.value or None, num_inference_steps=sd_steps.value, ).images[0] mo.image(image, caption=sd_prompt.value) except Exception as e: mo.md(f"⚠️ Stable Diffusion requires `diffusers` + GPU: `{e}`") else: mo.md("Enter a prompt and click Generate.") return # ═══════════════════════════════════════════════════════════════════ # 3 — Custom Training (Axon equivalent) # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ## 3 — Custom Training (Axon → PyTorch) Build and train a neural network from scratch — mirrors the Axon section of the Livebook template. """ ) return @app.cell def _(np, train_test_split): # Synthetic data (same as Livebook) np.random.seed(42) n_samples, n_features, n_classes = 2000, 4, 3 centers = np.random.randn(n_classes, n_features) * 2 labels_raw = np.random.randint(0, n_classes, n_samples) noise = np.random.randn(n_samples, n_features) * 0.4 X = centers[labels_raw] + noise X = (X - X.mean(axis=0)) / X.std(axis=0) Y = np.eye(n_classes)[labels_raw] X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size=0.2, random_state=42 ) f"Train: {len(X_train)} | Test: {len(X_test)} | Features: {n_features} | Classes: {n_classes}" return X_test, X_train, Y_test, Y_train, n_classes, n_features @app.cell def _(DataLoader, TensorDataset, X_test, X_train, Y_test, Y_train, device, torch): # Prepare PyTorch data loaders train_loader = DataLoader( TensorDataset( torch.FloatTensor(X_train).to(device), torch.FloatTensor(Y_train).to(device), ), batch_size=64, shuffle=True, ) test_loader = DataLoader( TensorDataset( torch.FloatTensor(X_test).to(device), torch.FloatTensor(Y_test).to(device), ), batch_size=64, ) return test_loader, train_loader @app.cell def _(device, mo, n_classes, n_features, nn): # Model definition (mirrors Axon build) class MLP(nn.Module): def __init__(self): super().__init__() self.net = nn.Sequential( nn.Linear(n_features, 64), nn.ReLU(), nn.BatchNorm1d(64), nn.Dropout(0.2), nn.Linear(64, 32), nn.ReLU(), nn.BatchNorm1d(32), nn.Dropout(0.2), nn.Linear(32, n_classes), nn.Softmax(dim=1), ) def forward(self, x): return self.net(x) model = MLP().to(device) param_count = sum(p.numel() for p in model.parameters()) mo.md(f"**Model:** {param_count:,} parameters\n```\n{model}\n```") return (model,) @app.cell def _(mo, model, torch, train_loader): # Training loop optimizer = torch.optim.Adam(model.parameters(), lr=0.001) criterion = nn.CrossEntropyLoss() epochs = 30 epoch_losses = [] for epoch in range(epochs): model.train() running_loss = 0.0 for xb, yb in train_loader: preds = model(xb) loss = criterion(preds, yb.argmax(dim=1)) optimizer.zero_grad() loss.backward() optimizer.step() running_loss += loss.item() epoch_losses.append(running_loss / len(train_loader)) mo.md(f"**Training complete!** Final loss: `{epoch_losses[-1]:.4f}`") return epoch_losses, model @app.cell def _(epoch_losses, mo, plt): # Plot training loss fig, ax = plt.subplots(figsize=(6, 3)) ax.plot(epoch_losses, linewidth=2, color="#7c3aed") ax.set_xlabel("Epoch") ax.set_ylabel("Loss") ax.set_title("Training Loss") ax.grid(True, alpha=0.3) plt.tight_layout() mo.mpl.interactive(fig) return @app.cell def _(X_test, Y_test, classification_report, device, model, mo, torch): # Evaluation model.eval() all_preds, all_true = [], [] with torch.no_grad(): for i in range(0, len(X_test), 64): xb = torch.FloatTensor(X_test[i : i + 64]).to(device) preds = model(xb).argmax(1).cpu().numpy() all_preds.extend(preds) all_true.extend(Y_test[i : i + 64].argmax(1)) report = classification_report( all_true, all_preds, target_names=[f"Class {i}" for i in range(3)] ) mo.md(f"```\n{report}\n```") return all_preds, all_true @app.cell def _(X_test, all_preds, all_true, mo, plt): # Visualize predictions fig, axes = plt.subplots(1, 2, figsize=(10, 4)) for cls in range(3): mask = [t == cls for t in all_true] axes[0].scatter( X_test[mask, 0], X_test[mask, 1], label=f"Class {cls}", alpha=0.6, s=15 ) mask2 = [p == cls for p in all_preds] axes[1].scatter( X_test[mask2, 0], X_test[mask2, 1], label=f"Class {cls}", alpha=0.6, s=15 ) axes[0].set_title("Actual") axes[1].set_title("Predicted") for ax in axes: ax.legend() ax.grid(True, alpha=0.3) plt.tight_layout() mo.mpl.interactive(fig) return # ═══════════════════════════════════════════════════════════════════ # 4 — Interactive Playground # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ## 4 — Interactive Playground marimo UI elements are **reactive** — change an input and all dependent cells re-run automatically. This mirrors how `Kino` works in Elixir Livebook. """ ) return @app.cell def _(mo, np, torch): # Interactive custom prediction def predict_custom(features, model_ref): x = torch.FloatTensor([features]).to(device) model_ref.eval() with torch.no_grad(): probs = model_ref(x).cpu().numpy()[0] return probs f1 = mo.ui.slider(start=-3.0, stop=3.0, value=0.0, step=0.1, label="Feature 1") f2 = mo.ui.slider(start=-3.0, stop=3.0, value=0.0, step=0.1, label="Feature 2") f3 = mo.ui.slider(start=-3.0, stop=3.0, value=0.0, step=0.1, label="Feature 3") f4 = mo.ui.slider(start=-3.0, stop=3.0, value=0.0, step=0.1, label="Feature 4") mo.vstack([f1, f2, f3, f4]) return f1, f2, f3, f4, predict_custom @app.cell def _(f1, f2, f3, f4, model, mo, predict_custom): features = [f1.value, f2.value, f3.value, f4.value] probs = predict_custom(features, model) pred_class = int(probs.argmax()) confidence = float(probs[pred_class]) prob_bars = "\n".join( [f"- **Class {i}**: `{p:.4f}` {'█' * int(p * 30)}" for i, p in enumerate(probs)] ) mo.md( f""" ### Prediction: Class {pred_class} ({confidence:.1%} confidence) {prob_bars} """ ) return # ═══════════════════════════════════════════════════════════════════ # 5 — Summary # ═══════════════════════════════════════════════════════════════════ @app.cell(hide_code=True) def _(mo): mo.md( r""" ## 5 — Summary | Pipeline Stage | Elixir (Livebook) | This Notebook (marimo) | |----------------|-------------------|------------------------| | Tensors | `Nx.tensor` | `np.array` | | Gradients | `Nx.Defn.grad` | `torch.autograd` | | GPU | `EXLA.Backend` | `torch.cuda` | | Pre-trained | `Bumblebee.load_model` | `pipeline()` | | Fill-Mask | `Bumblebee.Text.fill_mask` | `pipeline("fill-mask")` | | Sentiment | `Bumblebee.Text.Classification` | `pipeline("sentiment-analysis")` | | NER | `Bumblebee.Text.TokenClassification` | `pipeline("ner")` | | Zero-Shot | `Bumblebee.Text.ZeroShotClassification` | `pipeline("zero-shot-classification")` | | Text Gen | `Bumblebee.Text.generation` | `pipeline("text-generation")` | | Embeddings | `Bumblebee.Text.TextEmbedding` | `sentence-transformers` | | Training | `Axon` + `Axon.Loop` | `torch.nn` + training loop | | UI | `Kino` | `marimo.ui` (reactive) | ### Deploy This Notebook ```bash # Edit interactively marimo edit ml_e2e_marimo.py # Run as app (hide code) marimo run ml_e2e_marimo.py # Run as script python ml_e2e_marimo.py # Convert to/from Jupyter marimo convert ml_e2e_marimo.py -o notebook.ipynb marimo convert notebook.ipynb -o from_jupyter.py ``` ### Resources * [marimo docs](https://docs.marimo.io) * [Bumblebee docs](https://hexdocs.pm/bumblebee) * [Nx docs](https://hexdocs.pm/nx) * [Hugging Face Hub](https://huggingface.co/models) * _Machine Learning in Elixir_ — Sean Moriarity, Pragmatic Bookshelf """ ) return @app.cell def _(mo, pipeline, device): # Export sentiment model to ONNX (requires torch) import torch # Load the sentiment pipeline (use same model as earlier) sentiment_pipe = pipeline( "sentiment-analysis", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", ) torch_model = sentiment_pipe.model dummy_input = torch.randint(0, 30522, (1, 128)).to(device) # example token IDs torch.onnx.export( torch_model, dummy_input, "sentiment.onnx", input_names=["input_ids"], output_names=["logits"], opset_version=12, dynamic_axes={"input_ids": {0: "batch", 1: "seq"}}, ) mo.md("✅ Exported sentiment model to `sentiment.onnx`") mo.md( """ Convert to GGUF (decoder‑only models) with: ```bash pip install gguf-converter gguf-converter --onnx sentiment.onnx --output sentiment.gguf ``` """ ) return if __name__ == "__main__": app.run()