File size: 27,980 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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
"""
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()