rustorch 0.6.29

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": [
    "# Intégration CoreML de RusTorch - Liaisons Python\n",
    "\n",
    "Ce notebook démontre comment utiliser la fonctionnalité CoreML de RusTorch via les liaisons Python."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configuration et Importations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Importer les liaisons Python de RusTorch\n",
    "try:\n",
    "    import rustorch\n",
    "    print(f\"✅ Version de RusTorch : {rustorch.__version__}\")\n",
    "    print(f\"📝 Description : {rustorch.__description__}\")\n",
    "    print(f\"👥 Auteur : {rustorch.__author__}\")\n",
    "except ImportError as e:\n",
    "    print(f\"❌ Échec de l'importation de RusTorch : {e}\")\n",
    "    print(\"Veuillez construire avec maturin develop\")\n",
    "    exit(1)\n",
    "\n",
    "import numpy as np\n",
    "import platform\n",
    "\n",
    "print(f\"🖥️ Plateforme : {platform.system()} {platform.release()}\")\n",
    "print(f\"🐍 Version Python : {platform.python_version()}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Vérifier la Disponibilité de CoreML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Vérifier la fonctionnalité CoreML\n",
    "try:\n",
    "    # Vérifier si CoreML est disponible\n",
    "    coreml_available = rustorch.is_coreml_available()\n",
    "    print(f\"🍎 CoreML disponible : {coreml_available}\")\n",
    "    \n",
    "    if coreml_available:\n",
    "        print(\"🎉 CoreML est disponible !\")\n",
    "        \n",
    "        # Obtenir les informations du périphérique\n",
    "        device_info = rustorch.get_coreml_device_info()\n",
    "        print(\"📱 Informations du périphérique CoreML :\")\n",
    "        print(device_info)\n",
    "    else:\n",
    "        print(\"⚠️ CoreML n'est pas disponible\")\n",
    "        if platform.system() != \"Darwin\":\n",
    "            print(\"CoreML n'est disponible que sur macOS\")\n",
    "        else:\n",
    "            print(\"Les fonctionnalités CoreML peuvent ne pas être activées\")\n",
    "            \n",
    "except AttributeError:\n",
    "    print(\"❌ Fonctions CoreML non trouvées\")\n",
    "    print(\"Peut ne pas être construit avec les fonctionnalités CoreML\")\n",
    "    coreml_available = False\n",
    "except Exception as e:\n",
    "    print(f\"❌ Erreur lors de la vérification de CoreML : {e}\")\n",
    "    coreml_available = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Création de Périphérique CoreML et Opérations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if coreml_available:\n",
    "    try:\n",
    "        # Créer un périphérique CoreML\n",
    "        device = rustorch.CoreMLDevice(device_id=0)\n",
    "        print(f\"🖥️ Périphérique CoreML créé : {device}\")\n",
    "        \n",
    "        # Obtenir les informations du périphérique\n",
    "        print(f\"🆔 ID du périphérique : {device.device_id()}\")\n",
    "        print(f\"✅ Disponible : {device.is_available()}\")\n",
    "        print(f\"💾 Limite de mémoire : {device.memory_limit()} octets\")\n",
    "        print(f\"🧮 Limite des unités de calcul : {device.compute_units_limit()}\")\n",
    "        print(f\"📚 Taille du cache du modèle : {device.model_cache_size()}\")\n",
    "        \n",
    "        # Nettoyage du cache\n",
    "        device.cleanup_cache()\n",
    "        print(\"🧹 Cache nettoyé\")\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Erreur d'opération du périphérique CoreML : {e}\")\n",
    "else:\n",
    "    print(\"⚠️ Saut des opérations du périphérique car CoreML n'est pas disponible\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configuration du Backend CoreML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if coreml_available:\n",
    "    try:\n",
    "        # Créer la configuration du 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\"⚙️ Configuration du backend : {config}\")\n",
    "        \n",
    "        # Vérifier et modifier les valeurs de configuration\n",
    "        print(f\"📊 Activer la mise en cache : {config.enable_caching}\")\n",
    "        print(f\"🗂️ Taille maximale du cache : {config.max_cache_size}\")\n",
    "        print(f\"📈 Activer le profilage : {config.enable_profiling}\")\n",
    "        print(f\"🔄 Basculement automatique : {config.auto_fallback}\")\n",
    "        \n",
    "        # Modifier la configuration\n",
    "        config.enable_profiling = False\n",
    "        config.max_cache_size = 150\n",
    "        print(f\"\\n🔧 Configuration mise à jour : {config}\")\n",
    "        \n",
    "        # Créer le backend CoreML\n",
    "        backend = rustorch.CoreMLBackend(config)\n",
    "        print(f\"🚀 Backend CoreML : {backend}\")\n",
    "        print(f\"✅ Backend disponible : {backend.is_available()}\")\n",
    "        \n",
    "        # Obtenir les statistiques du backend\n",
    "        stats = backend.get_stats()\n",
    "        print(f\"📊 Statistiques du backend : {stats}\")\n",
    "        print(f\"   Opérations totales : {stats.total_operations}\")\n",
    "        print(f\"   Succès du cache : {stats.cache_hits}\")\n",
    "        print(f\"   Échecs du cache : {stats.cache_misses}\")\n",
    "        print(f\"   Opérations de basculement : {stats.fallback_operations}\")\n",
    "        print(f\"   Taux de succès du cache : {stats.cache_hit_rate():.2%}\")\n",
    "        print(f\"   Taux de basculement : {stats.fallback_rate():.2%}\")\n",
    "        print(f\"   Temps d'exécution moyen : {stats.average_execution_time_ms:.2f}ms\")\n",
    "        \n",
    "        # Nettoyage du cache\n",
    "        backend.cleanup_cache()\n",
    "        print(\"\\n🧹 Cache du backend nettoyé\")\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Erreur d'opération du backend CoreML : {e}\")\n",
    "else:\n",
    "    print(\"⚠️ Saut des opérations du backend car CoreML n'est pas disponible\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Opérations de Tenseurs de Base (CPU)\n",
    "\n",
    "Pour comparer avec CoreML, effectuons d'abord des opérations de base sur CPU."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    # Création et opérations de tenseurs de base\n",
    "    print(\"🧮 Opérations de tenseurs de base (CPU)\")\n",
    "    \n",
    "    # Créer des tenseurs à partir de tableaux NumPy (interface simplifiée)\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\"📐 Forme de la matrice A : {data_a.shape}\")\n",
    "    print(f\"📐 Forme de la matrice B : {data_b.shape}\")\n",
    "    \n",
    "    # Multiplication de matrices avec NumPy (pour comparaison)\n",
    "    numpy_result = np.matmul(data_a, data_b)\n",
    "    print(f\"✅ Forme du résultat matmul NumPy : {numpy_result.shape}\")\n",
    "    print(f\"📊 Résultat (premiers éléments) : {numpy_result.flatten()[:4]}\")\n",
    "    \n",
    "    print(\"\\n🚀 Opérations CPU terminées\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"❌ Erreur d'opération de tenseur : {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation de Comparaison de Performance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def benchmark_matrix_operations():\n",
    "    \"\"\"Comparer les performances avec différentes tailles de matrices\"\"\"\n",
    "    \n",
    "    sizes = [(64, 64), (128, 128), (256, 256), (512, 512)]\n",
    "    \n",
    "    print(\"🏁 Comparaison de performance :\")\n",
    "    print(\"Taille\\t\\tTemps CPU (ms)\\tCoreML Attendu (ms)\")\n",
    "    print(\"-\" * 56)\n",
    "    \n",
    "    for size in sizes:\n",
    "        # Mesurer le temps d'exécution 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",
    "        # Temps CoreML attendu (hypothétique)\n",
    "        # Dans l'implémentation réelle, utiliser les mesures réelles du backend CoreML\n",
    "        expected_coreml_time = cpu_time * 0.6  # Hypothèse : CoreML est 40% plus rapide\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📝 Note : Les temps CoreML sont hypothétiques. Les valeurs réelles dépendent de l'implémentation spécifique.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation de Sélection de Périphérique"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def simulate_device_selection():\n",
    "    \"\"\"Simuler la sélection intelligente de périphérique\"\"\"\n",
    "    \n",
    "    operations = [\n",
    "        (\"Multiplication de matrice petite\", (16, 16), \"CPU\"),\n",
    "        (\"Multiplication de matrice moyenne\", (128, 128), \"GPU Metal\"),\n",
    "        (\"Multiplication de matrice grande\", (512, 512), \"CoreML\" if coreml_available else \"GPU Metal\"),\n",
    "        (\"Fonction d'activation\", (32, 64, 128, 128), \"GPU Metal\"),\n",
    "        (\"Petite convolution\", (1, 3, 32, 32), \"CPU\"),\n",
    "        (\"Grande convolution\", (16, 64, 224, 224), \"CoreML\" if coreml_available else \"GPU Metal\"),\n",
    "        (\"Opérations de nombres complexes\", (128, 128), \"GPU Metal\"),  # CoreML non supporté\n",
    "        (\"Distribution statistique\", (1000,), \"CPU\"),  # CoreML non supporté\n",
    "    ]\n",
    "    \n",
    "    print(\"🎯 Simulation de sélection intelligente de périphérique :\")\n",
    "    print(\"Opération\\t\\t\\tForme du Tenseur\\t\\tPériphérique Sélectionné\")\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📝 Logique de sélection :\")\n",
    "    print(\"  • Petites opérations : CPU (éviter la surcharge)\")\n",
    "    print(\"  • Opérations moyennes : GPU Metal (équilibré)\")\n",
    "    print(\"  • Grandes opérations : CoreML (optimisé)\")\n",
    "    print(\"  • Opérations non supportées : basculement GPU/CPU\")\n",
    "\n",
    "simulate_device_selection()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exemple Pratique : Couche Simple de Réseau Neuronal"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def simulate_neural_network_layer():\n",
    "    \"\"\"Simuler une couche de réseau neuronal\"\"\"\n",
    "    \n",
    "    print(\"🧠 Simulation de couche de réseau neuronal :\")\n",
    "    \n",
    "    # Taille du lot et configuration de la couche\n",
    "    batch_size = 32\n",
    "    input_features = 784  # 28x28 MNIST\n",
    "    hidden_features = 256\n",
    "    output_features = 10  # 10 classes\n",
    "    \n",
    "    print(f\"📊 Taille du lot : {batch_size}\")\n",
    "    print(f\"🔢 Caractéristiques d'entrée : {input_features}\")\n",
    "    print(f\"🧮 Caractéristiques cachées : {hidden_features}\")\n",
    "    print(f\"🎯 Caractéristiques de sortie : {output_features}\")\n",
    "    \n",
    "    # Simulation de passe avant\n",
    "    steps = [\n",
    "        (\"Entrée → Cachée\", f\"({batch_size}, {input_features}) @ ({input_features}, {hidden_features})\", \"CoreML\" if coreml_available else \"Metal\"),\n",
    "        (\"Activation ReLU\", f\"({batch_size}, {hidden_features})\", \"Metal\"),\n",
    "        (\"Cachée → Sortie\", 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🔄 Simulation de passe avant :\")\n",
    "    total_time = 0\n",
    "    \n",
    "    for step, shape, device in steps:\n",
    "        # Temps d'exécution virtuel (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⏱️ Temps total de la passe avant : {total_time:.2f}ms\")\n",
    "    print(f\"🚀 Débit estimé : {1000/total_time:.0f} lots/seconde\")\n",
    "\n",
    "simulate_neural_network_layer()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Résumé et Prochaines Étapes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"📋 Résumé de l'Intégration CoreML RusTorch :\")\n",
    "print()\n",
    "print(\"✅ Éléments terminés :\")\n",
    "print(\"  • Configuration de l'environnement Jupyter\")\n",
    "print(\"  • Création du noyau Rust et des liaisons Python\")\n",
    "print(\"  • Vérification de la disponibilité CoreML\")\n",
    "print(\"  • Gestion des périphériques et configuration\")\n",
    "print(\"  • Statistiques et profilage du backend\")\n",
    "print(\"  • Sélection intelligente de périphérique\")\n",
    "print()\n",
    "print(\"🚧 Développement futur :\")\n",
    "print(\"  • Implémentation réelle des opérations CoreML\")\n",
    "print(\"  • Évaluation comparative des performances\")\n",
    "print(\"  • Plus de fonctions d'activation et de types de couches\")\n",
    "print(\"  • Améliorations de la gestion des erreurs\")\n",
    "print(\"  • Optimisation de la mémoire\")\n",
    "print()\n",
    "print(\"🎯 Prochaines étapes recommandées :\")\n",
    "print(\"  1. Charger et tester de vrais modèles CoreML\")\n",
    "print(\"  2. Comparer les performances Metal et CoreML\")\n",
    "print(\"  3. Tester avec de vrais flux de travail d'apprentissage profond\")\n",
    "print(\"  4. Évaluer en environnement de production\")\n",
    "\n",
    "if coreml_available:\n",
    "    print(\"\\n🎉 Félicitations ! CoreML est disponible et toutes les fonctionnalités peuvent être testées.\")\n",
    "else:\n",
    "    print(\"\\n⚠️ CoreML n'est pas disponible, mais les fonctionnalités de base fonctionnent.\")\n",
    "    print(\"   Nous recommandons de construire avec les fonctionnalités CoreML activées sur 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
}