Ejecutando LLMs en el Navegador: WebLLM, Transformers.js y ONNX Runtime Web en 2026
技术架构
Los LLMs Ya No Necesitan Servidores
¿GPT-4 requiere APIs en la nube? Ese es el pensamiento de 2024. Para 2026, los modelos de 7B parámetros funcionan sin problemas en el navegador, y tus datos nunca salen de tu dispositivo.
Privacidad + Costo Cero + Sin Conexión = Las tres ventajas decisivas de la IA del lado del navegador
Línea de Tiempo de la Evolución de la IA en el Navegador
2023 Q4 WebLLM se lanza, Llama 2 a 2 tok/s en el navegador
2024 Q2 Transformers.js publicado, ecosistema de Hugging Face conectado
2024 Q4 Soporte completo de WebGPU, 5x aceleración en inferencia
2025 Q2 ONNX Runtime Web soporta WebGPU, nivel empresarial
2025 Q4 Avance en cuantización, modelos de 7B comprimidos a 3GB
2026 Q2 Gemma 3 4B alcanza 25 tok/s en el navegador — punto de inflexión de calidad
Tres Frameworks de un Vistazo
| Framework | Enfoque | Tecnología Central | Mejor Para |
|---|---|---|---|
| WebLLM | Inferencia LLM de alto rendimiento | WebGPU + MLCEngine | Chat, autocompletado de código |
| Transformers.js | Inferencia ML full-stack | ONNX + WASM/WebGPU | NLP, visión, audio |
| ONNX Runtime Web | Motor de inferencia empresarial | ONNX + WebGPU/WASM | Despliegue en producción |
WebLLM — El Rey del Rendimiento de los LLMs en el Navegador
Arquitectura
┌──────────────────────────────────────────────────┐
│ Capa de Aplicación │
│ Chat UI │ Autocompletado │ Resumen │ ... │
├──────────────────────────────────────────────────┤
│ Motor WebLLM │
│ ChatModule │ Pipeline │ Tokenizer │ Scheduler │
├──────────────────────────────────────────────────┤
│ MLCEngine (Optimización de Compilación) │
│ Model Compile │ Kernel Opt │ Quantization │
├──────────────────────────────────────────────────┤
│ Runtime WebGPU │
│ Compute Shader │ GPU Buffer │ Pipeline State │
└──────────────────────────────────────────────────┘
Inicio Rápido
import { CreateMLCEngine } from "@mlc-ai/web-llm";
const engine = await CreateMLCEngine("gemma-3-4b-it-q4f16_1-MLC", {
initProgressCallback: (progress) => {
console.log(`Loading: ${(progress.progress * 100).toFixed(1)}%`);
},
});
const reply = await engine.chat.completions.create({
messages: [
{ role: "system", content: "You are a helpful AI assistant." },
{ role: "user", content: "Write a quicksort in TypeScript" },
],
temperature: 0.7,
max_tokens: 1024,
stream: true,
});
for await (const chunk of reply) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
Modelos Soportados y Rendimiento (Junio 2026)
| Modelo | Parámetros | Tamaño Cuantizado | Velocidad (tok/s) | Primera Carga |
|---|---|---|---|---|
| Gemma 3 4B IT | 4B | 2.3GB | 25 | 8s |
| Phi-4 Mini | 3.8B | 2.1GB | 28 | 7s |
| Qwen2.5 3B | 3B | 1.8GB | 32 | 6s |
| SmolLM2 1.7B | 1.7B | 1.0GB | 45 | 4s |
| Qwen2.5 0.5B | 0.5B | 0.4GB | 85 | 2s |
Entorno de prueba: M3 MacBook Pro / Chrome 126 / WebGPU
Transformers.js — El Ecosistema de Hugging Face en el Navegador
Ventaja Central: El Ecosistema de Modelos Más Rico
import { pipeline } from "@xenova/transformers";
const classifier = await pipeline("text-classification", "Xenova/distilbert-base-uncased-finetuned-sst-2-english");
const result = await classifier("This browser AI is amazing!");
// [{ label: "POSITIVE", score: 0.9998 }]
Pipelines Soportados
| Pipeline | Caso de Uso | Modelo de Ejemplo |
|---|---|---|
| text-classification | Análisis de sentimiento | distilbert-sst2 |
| question-answering | Sistema de preguntas y respuestas | distilbert-qa |
| summarization | Resumen | distilbart-cnn |
| translation | Traducción | opus-mt-en-zh |
| image-classification | Clasificación de imágenes | vit-base-patch16 |
| automatic-speech-recognition | Reconocimiento de voz | whisper-tiny |
ONNX Runtime Web — Motor de Inferencia Empresarial
Uso Básico
import ort from "onnxruntime-web";
async function runInference(modelPath: string, input: Float32Array) {
const session = await ort.InferenceSession.create(modelPath, {
executionProviders: ["webgpu", "wasm"],
graphOptimizationLevel: "all",
});
const inputTensor = new ort.Tensor("float32", input, [1, input.length]);
const results = await session.run({ input: inputTensor });
return results.output.data;
}
Estrategia de Selección de Proveedor
function getBestProvider(): string {
if (navigator.gpu) return "webgpu";
if (document.createElement("canvas").getContext("webgl2")) return "webgl";
return "wasm";
}
Benchmarks de Rendimiento: Comparación Completa
Inferencia LLM (Gemma 3 4B, cuantización de 4 bits)
| Métrica | WebLLM | Transformers.js | ONNX Runtime Web |
|---|---|---|---|
| Velocidad (tok/s) | 25 | 18 | 22 |
| Primera Carga | 8s | 12s | 10s |
| Memoria | 3.2GB | 3.8GB | 3.5GB |
| Streaming | ✅ | ✅ | ❌ |
| Compatibilidad OpenAI API | ✅ | ❌ | ❌ |
Estrategias de Despliegue en Producción
Degradación Elegante
async function createEngineWithFallback() {
if (navigator.gpu) {
try { return await CreateMLCEngine("gemma-3-4b-it-q4f16_1-MLC"); }
catch (e) { console.warn("WebGPU failed, falling back to smaller model"); }
}
try { return await CreateMLCEngine("SmolLM2-1.7B-q4f16_1-MLC"); }
catch (e) { console.warn("Small model failed, falling back to API"); }
return new APIFallbackEngine({ endpoint: "/api/chat" });
}
Soporte Sin Conexión con Service Worker
const MODEL_CACHE = "ai-models-v1";
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(MODEL_CACHE).then((cache) =>
cache.addAll(["/models/smolm2-1.7b-q4.onnx", "/models/tokenizer.json"])
)
);
});
Matriz de Decisión
Tu necesidad?
├─ Chat / IA Conversacional → ✅ WebLLM
├─ IA Multimodal → ✅ Transformers.js
├─ Producción Empresarial → ✅ ONNX Runtime Web
├─ App Offline-First → ✅ WebLLM + Service Worker
└─ Prototipo Rápido → ✅ Transformers.js
Tendencias H2 2026
| Tendencia | Descripción |
|---|---|
| WebGPU Universal | Soporte en Safari 18+, sin más problemas de compatibilidad |
| MoE en el Navegador | Modelos dispersos de Mixtral ejecutándose en el navegador |
| Fine-tuning en Dispositivo | Pesos LoRA descargados, modelos personalizados sin servidor |
| API Web AI del W3C | Capacidades de IA nativas del navegador estandarizadas |
Resumen
- La IA del navegador pasó de "juguete" a "herramienta" — modelo de 4B a 25 tok/s es utilizable
- Tres frameworks, tres fortalezas — WebLLM rápido, Transformers.js completo, ONNX estable
- La privacidad es la característica decisiva — Los datos nunca salen del navegador, costo de servidor cero
- La estrategia de degradación es clave — WebGPU → modelo pequeño → API en la nube, disponibilidad garantizada
Si tu producto de IA todavía envía cada solicitud a la nube en 2026, no solo estás desperdiciando costos de servidor — estás perdiendo la protección de privacidad, el mayor diferenciador.
Prueba estas herramientas que se ejecutan en tu navegador — no requieren registro →
#WebLLM#Transformers.js#ONNX#WebGPU#浏览器AI#边缘推理#大模型#本地AI