{"id":13869,"date":"2025-01-22T23:27:54","date_gmt":"2025-01-22T22:27:54","guid":{"rendered":"https:\/\/www.palentino.es\/blog\/?p=13869"},"modified":"2025-01-22T23:32:51","modified_gmt":"2025-01-22T22:32:51","slug":"uso-de-ia-en-local-con-onnx-runtime-y-net","status":"publish","type":"post","link":"https:\/\/www.palentino.es\/blog\/uso-de-ia-en-local-con-onnx-runtime-y-net\/","title":{"rendered":"De la Nube al escritorio. Uso de IA en local con ONNX Runtime y .NET"},"content":{"rendered":"<p data-pm-slice=\"1 1 []\">Hoy en d\u00eda, la inteligencia artificial (<span style=\"color: #800080;\"><strong>IA<\/strong><\/span>) est\u00e1 al alcance de todos, y no siempre necesitas depender de Internet para aprovechar sus beneficios. En esta entrada, exploraremos c\u00f3mo usar <span style=\"color: #800080;\"><strong>ONNX Runtime<\/strong><\/span> para ejecutar modelos de IA en tu ordenador local con .NET. Esta opci\u00f3n es ligera, flexible y completamente gratuita.<\/p>\n<h3><span style=\"color: #320845;\"><strong>\u00bfQu\u00e9 es ONNX Runtime?<\/strong><\/span><\/h3>\n<p><strong>ONNX Runtime<\/strong> es una biblioteca optimizada que permite ejecutar modelos de IA en formato <strong>ONNX<\/strong> (Open Neural Network Exchange). Este formato es un est\u00e1ndar abierto que facilita la interoperabilidad entre diferentes plataformas y frameworks como TensorFlow y PyTorch.<\/p>\n<p>Con ONNX Runtime, puedes ejecutar modelos de IA localmente en tu CPU o GPU, sin necesidad de enviar datos a servidores externos. Esto es ideal para aplicaciones que requieren procesamiento r\u00e1pido, privacidad o independencia de la red.<\/p>\n<div style=\"width: 640px;\" class=\"wp-video\"><!--[if lt IE 9]><script>document.createElement('video');<\/script><![endif]-->\n<video class=\"wp-video-shortcode\" id=\"video-13869-1\" width=\"640\" height=\"360\" preload=\"metadata\" controls=\"controls\"><source type=\"video\/mp4\" src=\"https:\/\/palentino.es\/videos\/Nube-local-IA.mp4?_=1\" \/><a href=\"https:\/\/palentino.es\/videos\/Nube-local-IA.mp4\">https:\/\/palentino.es\/videos\/Nube-local-IA.mp4<\/a><\/video><\/div>\n<div><\/div>\n<p><!--more--><\/p>\n<h3><span style=\"color: #320845;\"><strong>\u00bfQu\u00e9 son los modelos ONNX?<\/strong><\/span><\/h3>\n<p>Un <strong>modelo<\/strong> es una representaci\u00f3n matem\u00e1tica de un sistema entrenado para realizar tareas espec\u00edficas, como clasificaci\u00f3n de im\u00e1genes, an\u00e1lisis de texto o detecci\u00f3n de objetos. Los modelos en formato <strong>ONNX<\/strong> se construyen entrenando redes neuronales en frameworks como TensorFlow o PyTorch, y luego se exportan al formato ONNX para su uso en diferentes entornos.<\/p>\n<p>Un modelo ONNX incluye:<\/p>\n<ol start=\"1\" data-spread=\"false\">\n<li><strong>Estructura del modelo:<\/strong> Representa la arquitectura de la red (capas, conexiones, etc.).<\/li>\n<li><strong>Pesos entrenados:<\/strong> Son los valores aprendidos durante el entrenamiento.<\/li>\n<li><strong>Entradas y salidas:<\/strong> Define los formatos de los datos que el modelo puede procesar.<\/li>\n<\/ol>\n<p>Ejemplo: Un modelo de clasificaci\u00f3n de im\u00e1genes puede tomar como entrada una imagen y devolver una etiqueta que indica la clase de objeto en la imagen.<\/p>\n<div>\n<hr \/>\n<\/div>\n<h3><strong>Ventajas de usar IA en local<\/strong><\/h3>\n<ol start=\"1\" data-spread=\"false\">\n<li><strong>Privacidad:<\/strong> Los datos no se env\u00edan a terceros.<\/li>\n<li><strong>Bajo costo:<\/strong> No necesitas pagar servicios en la nube.<\/li>\n<li><strong>Latencia baja:<\/strong> Procesamiento r\u00e1pido al no depender de Internet.<\/li>\n<li><strong>Control total:<\/strong> Puedes personalizar el uso de los modelos.<\/li>\n<\/ol>\n<div>\n<hr \/>\n<\/div>\n<h3><strong>Requisitos para empezar<\/strong><\/h3>\n<ol start=\"1\" data-spread=\"false\">\n<li><strong>Sistema operativo compatible:<\/strong> Windows, macOS o Linux.<\/li>\n<li><strong>.NET Framework o .NET Core:<\/strong> Para ejecutar c\u00f3digo en VB.NET.<\/li>\n<li><strong>ONNX Runtime:<\/strong> Desc\u00e1rgalo como paquete NuGet (Microsoft.ML.OnnxRuntime).<\/li>\n<li><strong>Modelo ONNX:<\/strong> Puedes descargar modelos pre-entrenados desde <a href=\"https:\/\/onnx.ai\/models\/\">ONNX Model Zoo<\/a>.<\/li>\n<\/ol>\n<div>\n<hr \/>\n<\/div>\n<h3><strong>Instalaci\u00f3n de ONNX Runtime<\/strong><\/h3>\n<ol start=\"1\" data-spread=\"false\">\n<li>Abre tu proyecto en <strong>Visual Studio<\/strong>.<\/li>\n<li>Ve al <strong>Administrador de paquetes NuGet<\/strong>.<\/li>\n<li>Busca e instala el paquete Microsoft.ML.OnnxRuntime.<\/li>\n<\/ol>\n<div>\n<hr \/>\n<\/div>\n<h3><strong>C\u00f3mo usar ONNX Runtime en VB.NET<\/strong><\/h3>\n<p>Aqu\u00ed tienes un ejemplo sencillo para ejecutar un modelo de IA y permitir que el usuario pase la pregunta como par\u00e1metro al ejecutar el programa:<\/p>\n<h4><strong>C\u00f3digo de ejemplo:<\/strong><\/h4>\n<pre>\n\n<div class=\"codecolorer-container text mac-classic\" style=\"overflow:auto;white-space:nowrap;width:635px;height:300px;\"><table cellspacing=\"0\" cellpadding=\"0\"><tbody><tr><td class=\"line-numbers\"><div>1<br \/>2<br \/>3<br \/>4<br \/>5<br \/>6<br \/>7<br \/>8<br \/>9<br \/>10<br \/>11<br \/>12<br \/>13<br \/>14<br \/>15<br \/>16<br \/>17<br \/>18<br \/>19<br \/>20<br \/>21<br \/>22<br \/>23<br \/>24<br \/>25<br \/>26<br \/>27<br \/>28<br \/>29<br \/>30<br \/>31<br \/>32<br \/>33<br \/>34<br \/>35<br \/>36<br \/>37<br \/>38<br \/>39<br \/><\/div><\/td><td><div class=\"text codecolorer\">Imports Microsoft.ML.OnnxRuntime<br \/>\nImports Microsoft.ML.OnnxRuntime.Tensors<br \/>\n<br \/>\nModule Program<br \/>\n&nbsp; &nbsp; Sub Main(args As String())<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; Dim modelPath As String = &quot;ruta_al_modelo.onnx&quot;<br \/>\n<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; ' Verificar si hay par\u00e1metros de entrada<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; If args.Length = 0 Then<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(&quot;Por favor, proporciona una pregunta como par\u00e1metro al ejecutar el programa.&quot;)<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Return<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; End If<br \/>\n<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; Dim userInput As String = args(0)<br \/>\n<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; ' Crear una sesi\u00f3n de inferencia<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; Using session As New InferenceSession(modelPath)<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(&quot;Modelo cargado exitosamente. Procesando entrada...&quot;)<br \/>\n<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' Crear entrada para el modelo (adaptar seg\u00fan el modelo utilizado)<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Dim inputTensor = New DenseTensor(Of Single)(ProcesarEntrada(userInput), New Integer() {1, userInput.Length})<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Dim inputs = New NamedOnnxValue() {NamedOnnxValue.CreateFromTensor(&quot;input&quot;, inputTensor)}<br \/>\n<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' Ejecutar el modelo<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Dim results = session.Run(inputs)<br \/>\n<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' Mostrar resultados<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; For Each result In results<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(&quot;Respuesta del modelo: &quot; &amp;amp; result.AsTensor(Of Single)().ToString())<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Next<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; End Using<br \/>\n&nbsp; &nbsp; End Sub<br \/>\n<br \/>\n&nbsp; &nbsp; ' Funci\u00f3n para procesar la entrada del usuario y convertirla a datos num\u00e9ricos<br \/>\n&nbsp; &nbsp; Private Function ProcesarEntrada(input As String) As Single()<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; ' Este es un ejemplo simple, adaptar seg\u00fan el modelo (por ejemplo, tokenizaci\u00f3n para texto)<br \/>\n&nbsp; &nbsp; &nbsp; &nbsp; Return input.Select(Function(c) Convert.ToSingle(Asc(c))).ToArray()<br \/>\n&nbsp; &nbsp; End Function<br \/>\nEnd Module<\/div><\/td><\/tr><\/tbody><\/table><\/div>\n\n<\/pre>\n<p><strong>En este ejemplo:<\/strong><\/p>\n<ul data-spread=\"false\">\n<li>El programa espera que el usuario pase una pregunta como argumento al ejecutar el archivo .<strong>exe<\/strong>.<\/li>\n<li>Por ejemplo, puedes ejecutar el programa desde la l\u00ednea de comandos as\u00ed:\n<pre><strong>MiPrograma.exe \"\u00bfCu\u00e1l es el clima hoy?\"\r\n<\/strong><\/pre>\n<\/li>\n<li>El programa procesa la pregunta, la env\u00eda al modelo y muestra la respuesta generada.<\/li>\n<\/ul>\n<div>\n<hr \/>\n<\/div>\n<h3><strong>Descarga de modelos<\/strong><\/h3>\n<p>Visita <a href=\"https:\/\/onnx.ai\/models\/\" target=\"_blank\" rel=\"noopener\">ONNX Model Zoo<\/a> para obtener modelos pre-entrenados. Algunos ejemplos populares incluyen:<\/p>\n<ul data-spread=\"false\">\n<li><strong>Clasificaci\u00f3n de im\u00e1genes:<\/strong> Modelos peque\u00f1os (\u00b15-10 MB).<\/li>\n<li><strong>Procesamiento de texto:<\/strong> Modelos como GPT-2 (\u00b1500 MB).<\/li>\n<li><strong>Visi\u00f3n por computadora:<\/strong> Modelos de detecci\u00f3n de objetos (\u00b11-2 GB).<\/li>\n<\/ul>\n<div>\n<hr \/>\n<\/div>\n<h3><strong>Consideraciones<\/strong><\/h3>\n<ul data-spread=\"false\">\n<li><strong>Requisitos de hardware:<\/strong> Para modelos avanzados, una GPU acelera el procesamiento.<\/li>\n<li><strong>Preprocesamiento:<\/strong> Aseg\u00farate de preparar las entradas seg\u00fan los requisitos del modelo.<\/li>\n<li><strong>Optimizaci\u00f3n:<\/strong> ONNX Runtime est\u00e1 optimizado para CPU y GPU, por lo que es eficiente incluso en m\u00e1quinas sin hardware de alto rendimiento.<\/li>\n<\/ul>\n<div><\/div>\n<h3><strong>Conclusi\u00f3n<\/strong><\/h3>\n<p>Usar IA en local con ONNX Runtime y .NET es una excelente alternativa para quienes buscan soluciones privadas, r\u00e1pidas y sin costo continuo. Adem\u00e1s, la flexibilidad del formato ONNX permite aprovechar modelos pre-entrenados de alta calidad para tareas como clasificaci\u00f3n, generaci\u00f3n de texto o detecci\u00f3n de objetos.<\/p>\n<p>\u00a1Prueba esta opci\u00f3n y lleva tus proyectos de IA al siguiente nivel!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hoy en d\u00eda, la inteligencia artificial (IA) est\u00e1 al alcance de todos, y no siempre necesitas depender de Internet para aprovechar sus beneficios. En esta entrada, exploraremos c\u00f3mo usar ONNX Runtime para ejecutar modelos de IA en tu ordenador local con .NET. Esta opci\u00f3n es ligera, flexible y completamente gratuita. \u00bfQu\u00e9 es ONNX Runtime? ONNX Runtime es una biblioteca optimizada que permite ejecutar modelos de IA en formato ONNX (Open Neural Network Exchange). Este formato es un est\u00e1ndar abierto que facilita la interoperabilidad entre diferentes plataformas y frameworks como TensorFlow y PyTorch. Con ONNX Runtime, puedes ejecutar modelos de IA localmente en tu CPU o GPU, sin necesidad de enviar datos a servidores externos. Esto es ideal para aplicaciones que requieren procesamiento r\u00e1pido, privacidad o independencia de la red.<\/p>\n","protected":false},"author":1,"featured_media":11292,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1415],"tags":[],"class_list":["post-13869","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-sin-categoria-es"],"_links":{"self":[{"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/posts\/13869","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/comments?post=13869"}],"version-history":[{"count":9,"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/posts\/13869\/revisions"}],"predecessor-version":[{"id":13878,"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/posts\/13869\/revisions\/13878"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/media\/11292"}],"wp:attachment":[{"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/media?parent=13869"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/categories?post=13869"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.palentino.es\/blog\/wp-json\/wp\/v2\/tags?post=13869"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}