File size: 25,748 Bytes
a554e78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
{
  "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"
      ]
    }
  ]
}