rustorch 0.6.26

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
Documentation
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Integrazione CoreML di RusTorch - Binding Python\n",
    "\n",
    "Questo notebook dimostra come utilizzare la funzionalità CoreML di RusTorch tramite i binding Python."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configurazione e Importazioni"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Importare i binding Python di RusTorch\n",
    "try:\n",
    "    import rustorch\n",
    "    print(f\"✅ Versione RusTorch: {rustorch.__version__}\")\n",
    "    print(f\"📝 Descrizione: {rustorch.__description__}\")\n",
    "    print(f\"👥 Autore: {rustorch.__author__}\")\n",
    "except ImportError as e:\n",
    "    print(f\"❌ Importazione di RusTorch fallita: {e}\")\n",
    "    print(\"Si prega di compilare con maturin develop\")\n",
    "    exit(1)\n",
    "\n",
    "import numpy as np\n",
    "import platform\n",
    "\n",
    "print(f\"🖥️ Piattaforma: {platform.system()} {platform.release()}\")\n",
    "print(f\"🐍 Versione Python: {platform.python_version()}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Verificare la Disponibilità di CoreML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Verificare la funzionalità CoreML\n",
    "try:\n",
    "    # Verificare se CoreML è disponibile\n",
    "    coreml_available = rustorch.is_coreml_available()\n",
    "    print(f\"🍎 CoreML disponibile: {coreml_available}\")\n",
    "    \n",
    "    if coreml_available:\n",
    "        print(\"🎉 CoreML è disponibile!\")\n",
    "        \n",
    "        # Ottenere informazioni sul dispositivo\n",
    "        device_info = rustorch.get_coreml_device_info()\n",
    "        print(\"📱 Informazioni dispositivo CoreML:\")\n",
    "        print(device_info)\n",
    "    else:\n",
    "        print(\"⚠️ CoreML non è disponibile\")\n",
    "        if platform.system() != \"Darwin\":\n",
    "            print(\"CoreML è disponibile solo su macOS\")\n",
    "        else:\n",
    "            print(\"Le funzionalità CoreML potrebbero non essere abilitate\")\n",
    "            \n",
    "except AttributeError:\n",
    "    print(\"❌ Funzioni CoreML non trovate\")\n",
    "    print(\"Potrebbe non essere compilato con funzionalità CoreML\")\n",
    "    coreml_available = False\n",
    "except Exception as e:\n",
    "    print(f\"❌ Errore nella verifica di CoreML: {e}\")\n",
    "    coreml_available = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creazione Dispositivo CoreML e Operazioni"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if coreml_available:\n",
    "    try:\n",
    "        # Creare dispositivo CoreML\n",
    "        device = rustorch.CoreMLDevice(device_id=0)\n",
    "        print(f\"🖥️ Dispositivo CoreML creato: {device}\")\n",
    "        \n",
    "        # Ottenere informazioni sul dispositivo\n",
    "        print(f\"🆔 ID dispositivo: {device.device_id()}\")\n",
    "        print(f\"✅ Disponibile: {device.is_available()}\")\n",
    "        print(f\"💾 Limite memoria: {device.memory_limit()} byte\")\n",
    "        print(f\"🧮 Limite unità di calcolo: {device.compute_units_limit()}\")\n",
    "        print(f\"📚 Dimensione cache modello: {device.model_cache_size()}\")\n",
    "        \n",
    "        # Pulizia cache\n",
    "        device.cleanup_cache()\n",
    "        print(\"🧹 Cache pulita\")\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Errore operazione dispositivo CoreML: {e}\")\n",
    "else:\n",
    "    print(\"⚠️ Saltando operazioni dispositivo poiché CoreML non è disponibile\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configurazione Backend CoreML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if coreml_available:\n",
    "    try:\n",
    "        # Creare configurazione backend CoreML\n",
    "        config = rustorch.CoreMLBackendConfig(\n",
    "            enable_caching=True,\n",
    "            max_cache_size=200,\n",
    "            enable_profiling=True,\n",
    "            auto_fallback=True\n",
    "        )\n",
    "        print(f\"⚙️ Configurazione backend: {config}\")\n",
    "        \n",
    "        # Verificare e modificare valori di configurazione\n",
    "        print(f\"📊 Abilita caching: {config.enable_caching}\")\n",
    "        print(f\"🗂️ Dimensione max cache: {config.max_cache_size}\")\n",
    "        print(f\"📈 Abilita profiling: {config.enable_profiling}\")\n",
    "        print(f\"🔄 Fallback automatico: {config.auto_fallback}\")\n",
    "        \n",
    "        # Modificare configurazione\n",
    "        config.enable_profiling = False\n",
    "        config.max_cache_size = 150\n",
    "        print(f\"\\n🔧 Configurazione aggiornata: {config}\")\n",
    "        \n",
    "        # Creare backend CoreML\n",
    "        backend = rustorch.CoreMLBackend(config)\n",
    "        print(f\"🚀 Backend CoreML: {backend}\")\n",
    "        print(f\"✅ Backend disponibile: {backend.is_available()}\")\n",
    "        \n",
    "        # Ottenere statistiche backend\n",
    "        stats = backend.get_stats()\n",
    "        print(f\"📊 Statistiche backend: {stats}\")\n",
    "        print(f\"   Operazioni totali: {stats.total_operations}\")\n",
    "        print(f\"   Hit cache: {stats.cache_hits}\")\n",
    "        print(f\"   Miss cache: {stats.cache_misses}\")\n",
    "        print(f\"   Operazioni fallback: {stats.fallback_operations}\")\n",
    "        print(f\"   Tasso hit cache: {stats.cache_hit_rate():.2%}\")\n",
    "        print(f\"   Tasso fallback: {stats.fallback_rate():.2%}\")\n",
    "        print(f\"   Tempo esecuzione medio: {stats.average_execution_time_ms:.2f}ms\")\n",
    "        \n",
    "        # Pulizia cache\n",
    "        backend.cleanup_cache()\n",
    "        print(\"\\n🧹 Cache backend pulita\")\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Errore operazione backend CoreML: {e}\")\n",
    "else:\n",
    "    print(\"⚠️ Saltando operazioni backend poiché CoreML non è disponibile\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Operazioni Tensore di Base (CPU)\n",
    "\n",
    "Per confrontare con CoreML, eseguiamo prima operazioni di base su CPU."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    # Creazione e operazioni tensore di base\n",
    "    print(\"🧮 Operazioni tensore di base (CPU)\")\n",
    "    \n",
    "    # Creare tensori da array NumPy (interfaccia semplificata)\n",
    "    data_a = np.random.randn(2, 3).astype(np.float32)\n",
    "    data_b = np.random.randn(3, 2).astype(np.float32)\n",
    "    \n",
    "    print(f\"📐 Forma matrice A: {data_a.shape}\")\n",
    "    print(f\"📐 Forma matrice B: {data_b.shape}\")\n",
    "    \n",
    "    # Moltiplicazione matrici con NumPy (per confronto)\n",
    "    numpy_result = np.matmul(data_a, data_b)\n",
    "    print(f\"✅ Forma risultato matmul NumPy: {numpy_result.shape}\")\n",
    "    print(f\"📊 Risultato (primi elementi): {numpy_result.flatten()[:4]}\")\n",
    "    \n",
    "    print(\"\\n🚀 Operazioni CPU completate\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"❌ Errore operazione tensore: {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulazione Confronto Prestazioni"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def benchmark_matrix_operations():\n",
    "    \"\"\"Confrontare prestazioni con diverse dimensioni matrici\"\"\"\n",
    "    \n",
    "    sizes = [(64, 64), (128, 128), (256, 256), (512, 512)]\n",
    "    \n",
    "    print(\"🏁 Confronto prestazioni:\")\n",
    "    print(\"Dimensione\\t\\tTempo CPU (ms)\\tCoreML Atteso (ms)\")\n",
    "    print(\"-\" * 58)\n",
    "    \n",
    "    for size in sizes:\n",
    "        # Misurare tempo esecuzione CPU\n",
    "        a = np.random.randn(*size).astype(np.float32)\n",
    "        b = np.random.randn(size[1], size[0]).astype(np.float32)\n",
    "        \n",
    "        start_time = time.time()\n",
    "        result = np.matmul(a, b)\n",
    "        cpu_time = (time.time() - start_time) * 1000\n",
    "        \n",
    "        # Tempo CoreML atteso (ipotetico)\n",
    "        # Nell'implementazione reale, usare misurazioni reali dal backend CoreML\n",
    "        expected_coreml_time = cpu_time * 0.6  # Assunzione: CoreML è 40% più veloce\n",
    "        \n",
    "        print(f\"{size[0]}x{size[1]}\\t\\t{cpu_time:.2f}\\t\\t{expected_coreml_time:.2f}\")\n",
    "\n",
    "benchmark_matrix_operations()\n",
    "\n",
    "print(\"\\n📝 Nota: I tempi CoreML sono ipotetici. I valori reali dipendono dall'implementazione specifica.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulazione Selezione Dispositivo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def simulate_device_selection():\n",
    "    \"\"\"Simulare selezione intelligente dispositivo\"\"\"\n",
    "    \n",
    "    operations = [\n",
    "        (\"Moltiplicazione matrice piccola\", (16, 16), \"CPU\"),\n",
    "        (\"Moltiplicazione matrice media\", (128, 128), \"Metal GPU\"),\n",
    "        (\"Moltiplicazione matrice grande\", (512, 512), \"CoreML\" if coreml_available else \"Metal GPU\"),\n",
    "        (\"Funzione attivazione\", (32, 64, 128, 128), \"Metal GPU\"),\n",
    "        (\"Convoluzione piccola\", (1, 3, 32, 32), \"CPU\"),\n",
    "        (\"Convoluzione grande\", (16, 64, 224, 224), \"CoreML\" if coreml_available else \"Metal GPU\"),\n",
    "        (\"Operazioni numeri complessi\", (128, 128), \"Metal GPU\"),  # CoreML non supportato\n",
    "        (\"Distribuzione statistica\", (1000,), \"CPU\"),  # CoreML non supportato\n",
    "    ]\n",
    "    \n",
    "    print(\"🎯 Simulazione selezione intelligente dispositivo:\")\n",
    "    print(\"Operazione\\t\\t\\tForma Tensore\\t\\tDispositivo Selezionato\")\n",
    "    print(\"-\" * 78)\n",
    "    \n",
    "    for name, shape, device in operations:\n",
    "        shape_str = \"x\".join(map(str, shape))\n",
    "        print(f\"{name:<31}\\t{shape_str:<15}\\t{device}\")\n",
    "    \n",
    "    print(\"\\n📝 Logica selezione:\")\n",
    "    print(\"  • Operazioni piccole: CPU (evitare overhead)\")\n",
    "    print(\"  • Operazioni medie: Metal GPU (bilanciato)\")\n",
    "    print(\"  • Operazioni grandi: CoreML (ottimizzato)\")\n",
    "    print(\"  • Operazioni non supportate: fallback GPU/CPU\")\n",
    "\n",
    "simulate_device_selection()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Esempio Pratico: Strato Semplice Rete Neurale"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def simulate_neural_network_layer():\n",
    "    \"\"\"Simulare strato rete neurale\"\"\"\n",
    "    \n",
    "    print(\"🧠 Simulazione strato rete neurale:\")\n",
    "    \n",
    "    # Dimensione batch e configurazione strato\n",
    "    batch_size = 32\n",
    "    input_features = 784  # 28x28 MNIST\n",
    "    hidden_features = 256\n",
    "    output_features = 10  # 10 classi\n",
    "    \n",
    "    print(f\"📊 Dimensione batch: {batch_size}\")\n",
    "    print(f\"🔢 Feature input: {input_features}\")\n",
    "    print(f\"🧮 Feature nascoste: {hidden_features}\")\n",
    "    print(f\"🎯 Feature output: {output_features}\")\n",
    "    \n",
    "    # Simulazione forward pass\n",
    "    steps = [\n",
    "        (\"Input → Nascosto\", f\"({batch_size}, {input_features}) @ ({input_features}, {hidden_features})\", \"CoreML\" if coreml_available else \"Metal\"),\n",
    "        (\"Attivazione ReLU\", f\"({batch_size}, {hidden_features})\", \"Metal\"),\n",
    "        (\"Nascosto → Output\", f\"({batch_size}, {hidden_features}) @ ({hidden_features}, {output_features})\", \"CoreML\" if coreml_available else \"Metal\"),\n",
    "        (\"Softmax\", f\"({batch_size}, {output_features})\", \"CPU\"),\n",
    "    ]\n",
    "    \n",
    "    print(\"\\n🔄 Simulazione forward pass:\")\n",
    "    total_time = 0\n",
    "    \n",
    "    for step, shape, device in steps:\n",
    "        # Tempo esecuzione virtuale (ms)\n",
    "        if device == \"CoreML\":\n",
    "            time_ms = np.random.uniform(0.5, 2.0)\n",
    "        elif device == \"Metal\":\n",
    "            time_ms = np.random.uniform(1.0, 3.0)\n",
    "        else:  # CPU\n",
    "            time_ms = np.random.uniform(0.2, 1.0)\n",
    "        \n",
    "        total_time += time_ms\n",
    "        print(f\"  {step:<15} {shape:<30} {device:<8} {time_ms:.2f}ms\")\n",
    "    \n",
    "    print(f\"\\n⏱️ Tempo totale forward pass: {total_time:.2f}ms\")\n",
    "    print(f\"🚀 Throughput stimato: {1000/total_time:.0f} batch/secondo\")\n",
    "\n",
    "simulate_neural_network_layer()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Riepilogo e Prossimi Passi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"📋 Riepilogo Integrazione CoreML RusTorch:\")\n",
    "print()\n",
    "print(\"✅ Elementi completati:\")\n",
    "print(\"  • Configurazione ambiente Jupyter\")\n",
    "print(\"  • Creazione kernel Rust e binding Python\")\n",
    "print(\"  • Verifica disponibilità CoreML\")\n",
    "print(\"  • Gestione dispositivi e configurazione\")\n",
    "print(\"  • Statistiche e profiling backend\")\n",
    "print(\"  • Selezione intelligente dispositivo\")\n",
    "print()\n",
    "print(\"🚧 Sviluppo futuro:\")\n",
    "print(\"  • Implementazione reale operazioni CoreML\")\n",
    "print(\"  • Benchmarking prestazioni\")\n",
    "print(\"  • Più funzioni attivazione e tipi strato\")\n",
    "print(\"  • Miglioramenti gestione errori\")\n",
    "print(\"  • Ottimizzazione memoria\")\n",
    "print()\n",
    "print(\"🎯 Prossimi passi raccomandati:\")\n",
    "print(\"  1. Caricare e testare modelli CoreML reali\")\n",
    "print(\"  2. Confrontare prestazioni Metal e CoreML\")\n",
    "print(\"  3. Testare con workflow deep learning reali\")\n",
    "print(\"  4. Valutare in ambiente produzione\")\n",
    "\n",
    "if coreml_available:\n",
    "    print(\"\\n🎉 Congratulazioni! CoreML è disponibile e tutte le funzionalità possono essere testate.\")\n",
    "else:\n",
    "    print(\"\\n⚠️ CoreML non è disponibile, ma le funzionalità di base stanno funzionando.\")\n",
    "    print(\"   Raccomandiamo di compilare con funzionalità CoreML abilitate su macOS.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}