El problema que nadie nombra The Problem Nobody Names
Cuando un LLM genera código, no piensa en bytes. Piensa en tokens. Y cada token tiene un precio: en dinero, en latencia, y en límite de contexto. When an LLM generates code, it doesn't think in bytes. It thinks in tokens. And every token has a price: in money, in latency, and in context window limits.
Python es hermoso para los humanos. Para un modelo, es verboso. Cada def, cada return, cada self, cada dos puntos al final de un for — son tokens que no aportan semántica adicional más allá de lo que el modelo ya infiere del contexto.
Python is beautiful for humans. For a model, it's verbose. Every def, every return, every self, every colon at the end of a for — they're tokens that add no extra semantics beyond what the model already infers from context.
Y esto importa más hoy que nunca. En 2026, el código no lo escribe un humano una vez. Lo lee un agente, lo razona, lo edita, lo escribe de vuelta, lo ejecuta, lee el output, y repite. El mismo código pasa por el contexto decenas de veces por tarea. And this matters more today than ever. In 2026, code isn't written once by a human. An agent reads it, reasons about it, edits it, writes it back, executes it, reads the output, and repeats. The same code passes through the context dozens of times per task.
Una reducción del 25% en verbosidad no es un ahorro del 25% en costo. Es un ahorro compuesto en cada vuelta del loop agéntico. A 25% reduction in verbosity isn't a 25% cost saving. It's a compounded saving across every turn of the agentic loop.
Kern es una propuesta de lenguaje de programación compacto que transpila a Python — y de vuelta a Python — pensado específicamente para este escenario: código generado, leído y editado por modelos de lenguaje, no por humanos. Kern is a proposed compact programming language that transpiles to Python — and back — designed specifically for this scenario: code generated, read, and edited by language models, not by humans.
Quién ya intentó resolverlo Who Already Tried to Solve This
Esta no es una pregunta nueva. Antes de hablar de Kern, hay que reconocer el trabajo previo — porque diferenciarse del arte existente es parte del rigor. This isn't a new question. Before talking about Kern, we need to acknowledge the prior work — because differentiating from the existing art is part of the rigor.
SimPy — ISSTA 2024
El trabajo más cercano a esta idea. SimPy define un subconjunto simplificado de Python — AST-compatible — con keywords abreviadas y sintaxis más compacta. Reporta reducciones de ~20-30% en tokens contra Python estándar, evaluado en HumanEval. The closest work to this idea. SimPy defines a simplified, AST-compatible subset of Python — with abbreviated keywords and more compact syntax. It reports ~20-30% token reductions versus standard Python, evaluated on HumanEval.
Lo que no resuelve: Para que un LLM genere SimPy de forma confiable, necesitas fine-tuning. Los modelos base defaulean a Python. Y no hay implementación de producción — sigue siendo un artefacto de investigación. What it doesn't solve: For an LLM to reliably generate SimPy, you need fine-tuning. Base models default to Python. And there's no production implementation — it remains a research artifact.
Token Sugar — Diciembre 2025
Un enfoque filosóficamente diferente, publicado apenas en diciembre pasado. En lugar de definir un lenguaje nuevo, Token Sugar propone una capa de "azúcar sintáctico" sobre Python: abreviaciones estructuradas que expanden de vuelta a Python estándar. A philosophically different approach, published just this past December. Instead of defining a new language, Token Sugar proposes a layer of "syntactic sugar" on top of Python: structured abbreviations that expand back to standard Python.
La idea clave: los LLMs ya conocen Python profundamente. Mejor enseñarles un sistema de abreviaciones consistente que un lenguaje nuevo. Con pocos ejemplos en el prompt, el modelo aprende a usarlas — no se necesita fine-tuning. Ahorro estimado: ~15-25%. The key insight: LLMs already know Python deeply. Better to teach them a consistent abbreviation system than a new language. With few-shot examples in the prompt, the model learns to use them — no fine-tuning needed. Estimated savings: ~15-25%.
Lo que no resuelve: Las reglas de Sugar deben definirse y mantenerse manualmente. Nuevos patrones no se comprimen automáticamente. Y ninguno de los dos proyectos — ni SimPy ni Token Sugar — fue diseñado teniendo en cuenta el tokenizador real. What it doesn't solve: Sugar rules must be manually defined and maintained. Novel patterns aren't automatically compressed. And neither project — SimPy nor Token Sugar — was designed with the actual tokenizer in mind.
Lo que ya sabemos sobre lenguajes y tokens What We Already Know About Languages and Tokens
Martin Alderson publicó un análisis comparando lenguajes de programación por eficiencia de tokens con tokenizadores modernos de LLMs. El hallazgo más contraintuitivo: algunos lenguajes que parecen cortos en caracteres (como C con aritmética de punteros) son ineficientes en tokens, porque símbolos como ->, *, & se fragmentan en el vocabulario BPE.
Martin Alderson published an analysis comparing programming languages by token efficiency with modern LLM tokenizers. The most counterintuitive finding: some languages that look short in characters (like C with pointer arithmetic) are inefficient in tokens, because symbols like ->, *, & fragment in the BPE vocabulary.
Python está en un punto medio ventajoso: sus keywords más comunes (def, return, import, for) suelen ser tokens unitarios en cl100k_base. Pero su sintaxis aún carga overhead innecesario para el LLM.
Python sits at an advantageous middle ground: its most common keywords (def, return, import, for) tend to be single tokens in cl100k_base. But its syntax still carries unnecessary overhead for the LLM.
| ProyectoProject | EnfoqueApproach | Ahorro tokensToken savings | Round-tripRound-trip | LLM nativoLLM-native | ProducciónProduction |
|---|---|---|---|---|---|
| SimPy | Lenguaje nuevo mínimoNew minimal language | ~20-30% | ParcialPartial | Fine-tuning requeridoFine-tuning required | No |
| Token Sugar | Macros sobre PythonMacros on Python | ~15-25% | Sí | Few-shotFew-shot | No |
| LLMLingua | Compresión de promptsPrompt compression | 50-75% | No | Sí | Sí |
| KERN | DSL que transpila a PythonDSL that transpiles to Python | Medido: ~50% global (hasta 70.8% en HumanEval)Measured: ~50% global (up to 70.8% on HumanEval) | Garantizado (AST)Guaranteed (AST) | Tokenizer-aware desde diseñoTokenizer-aware by design | En progresoIn progress |
Qué propone Kern What Kern Proposes
Kern no es un lenguaje nuevo que hay que aprender desde cero. Es una representación compacta de Python — con gramática formal, determinista y reversible. Kern isn't a new language you need to learn from scratch. It's a compact representation of Python — with a formal, deterministic, and reversible grammar.
Cualquier programa Python tiene exactamente una representación Kern. Cualquier programa Kern tiene exactamente un programa Python equivalente. El compilador inverso garantiza fidelidad semántica total a nivel de AST. Any Python program has exactly one Kern representation. Any Kern program has exactly one equivalent Python program. The inverse compiler guarantees total semantic fidelity at the AST level.
def add(a, b):
return a + b
result = [x**2 for x in range(10)
if x % 2 == 0]
class Node:
def __init__(self, val):
self.val = val
fn add(a,b)=a+b
result=[x**2 for x in range(10) if x%2==0]
cls Node{fn __init__(self,val){self.val=val}}
La sintaxis no es aleatoria. Cada decisión se valida contra el tokenizador real — cl100k_base de OpenAI, o200k_base de GPT-4o — para asegurar que el ahorro ocurre en tokens, no solo en caracteres. Es la pieza que SimPy y Token Sugar no hicieron.
The syntax isn't arbitrary. Every decision is validated against the actual tokenizer — OpenAI's cl100k_base, GPT-4o's o200k_base — to ensure savings happen in tokens, not just characters. That's the piece SimPy and Token Sugar didn't do.
Por qué transpila a Python y no es un lenguaje standalone Why It Transpiles to Python Instead of Being Standalone
Aquí está la decisión de arquitectura más importante: Kern no es un lenguaje independiente. Todo programa Kern compila a Python válido. Esto no es una limitación — es la estrategia. Here's the most important architectural decision: Kern is not a standalone language. Every Kern program compiles to valid Python. This isn't a limitation — it's the strategy.
Un lenguaje nuevo tiene el problema del arranque en frío: los LLMs no lo conocen, no hay librerías, no hay linters, no hay nada. Transpilando a Python, Kern hereda todo el ecosistema Python — pytest, mypy, black, pip — sin modificarlo. A new language has the cold-start problem: LLMs don't know it, there are no libraries, no linters, nothing. By transpiling to Python, Kern inherits the entire Python ecosystem — pytest, mypy, black, pip — without modifying it.
El flujo agéntico con Kern: el agente recibe código en Kern (compacto, menos tokens), razona y edita en Kern, el transpilador convierte a Python para ejecución, el output vuelve al agente en Kern. Cada vuelta del loop cuesta menos. The agentic flow with Kern: the agent receives code in Kern (compact, fewer tokens), reasons and edits in Kern, the transpiler converts to Python for execution, output returns to the agent in Kern. Each loop turn costs less.
Por qué ahora Why Now
SimPy es de 2024. Token Sugar salió en diciembre de 2025. El campo existe pero no tiene una implementación de producción, no tiene round-trip garantizado, y ninguno fue diseñado pensando en los loops agénticos modernos — Cursor, Claude Code, Devin, Copilot Workspace. SimPy is from 2024. Token Sugar came out in December 2025. The field exists but has no production implementation, no guaranteed round-trip, and neither was designed with modern agentic loops in mind — Cursor, Claude Code, Devin, Copilot Workspace.
Y hay algo más: las ventanas de contexto crecieron (128K → 1M tokens en algunos modelos), pero el costo sigue siendo lineal con los tokens. Más contexto disponible no significa tokens gratuitos. En entornos agénticos de alta frecuencia, la eficiencia de tokens es la diferencia entre un sistema rentable y uno que quema presupuesto. And there's something else: context windows grew (128K → 1M tokens in some models), but cost remains linear with tokens. More context available doesn't mean free tokens. In high-frequency agentic environments, token efficiency is the difference between a profitable system and one that burns budget.
El loop que se alimenta a sí mismo The Loop That Feeds Itself
Hay una pieza de la propuesta que va más allá de la eficiencia de tokens. Es la parte que hace que Kern sea diferente en un sentido más profundo: el lenguaje genera su propio modelo. There's one piece of this proposal that goes beyond token efficiency. It's what makes Kern different in a deeper sense: the language generates its own model.
La mayoría de los lenguajes de programación especializados tienen el problema del arranque frío: antes de que un LLM pueda generarlos, necesitas miles de ejemplos escritos a mano. Y escribir ejemplos a mano no escala. Most specialized programming languages have the cold-start problem: before an LLM can generate them, you need thousands of hand-written examples. And hand-writing examples doesn't scale.
Kern no tiene ese problema. El transpilador convierte cualquier programa Python a Kern de forma automática, determinista y sin intervención humana. Eso significa que cualquier repositorio de código Python del mundo es, automáticamente, datos de entrenamiento Kern. GitHub, HumanEval, MBPP, StarCoderData — millones de ejemplos disponibles desde el día uno, sin anotar un solo par a mano. Kern doesn't have that problem. The transpiler converts any Python program to Kern automatically, deterministically, and without human intervention. That means any Python codebase in the world is automatically Kern training data. GitHub, HumanEval, MBPP, StarCoderData — millions of examples available from day one, without hand-labeling a single pair.
La asimetría clave: para crear datos de entrenamiento en Kern no necesitas expertos en Kern. Solo necesitas el transpilador. Y el transpilador existe desde antes que el modelo. The key asymmetry: to create Kern training data you don't need Kern experts. You only need the transpiler. And the transpiler exists before the model does.
El loop de bootstrap The Bootstrap Loop
Pero la parte interesante viene después. Una vez que el modelo aprende a generar Kern de forma nativa, empieza a producir código Kern a partir de enunciados en lenguaje natural. Ese código puede: But the interesting part comes after. Once the model learns to generate Kern natively, it starts producing Kern code from natural language specs. That code can:
- Transpilarse a Python y ejecutarse con los tests existentes para verificar correcciónBe transpiled to Python and run against existing tests to verify correctness
- Los ejemplos que pasen los tests se añaden al dataset de entrenamientoExamples that pass the tests get added to the training dataset
- El modelo se re-entrena (o se hace fine-tuning incremental) con esos nuevos ejemplosThe model is retrained (or incrementally fine-tuned) with those new examples
- El modelo mejorado genera Kern más correcto y más compacto en la siguiente iteraciónThe improved model generates more correct and more compact Kern in the next iteration
Python (GitHub, HumanEval, MBPP)
|
v transpilador automático
Dataset Kern (millones de pares Python ↔ Kern)
|
v fine-tuning con QLoRA
LLM que genera Kern nativo
|
v genera código desde enunciados
Kern code nuevo
|
v compilador inverso + test runner
¿Pasa los tests?
/ \
Sí No
| |
v descarte
nuevo dato
al dataset
|
v
re-entrena → (loop)
El resultado es un sistema donde el lenguaje y el modelo co-evolucionan. No es un proceso manual — es un pipeline automático. Cada iteración del loop produce un modelo más capaz de generar código correcto en Kern, que a su vez produce más datos de entrenamiento válidos, que mejoran el siguiente modelo. The result is a system where the language and the model co-evolve. This isn't a manual process — it's an automated pipeline. Each loop iteration produces a model more capable of generating correct Kern code, which in turn produces more valid training data, which improves the next model.
Por qué Kern puede hacer esto y otros lenguajes no Why Kern Can Do This and Others Can't
La condición necesaria para que este loop funcione es que el lenguaje sea verificable. Todo programa Kern puede convertirse a Python y ejecutarse. No necesitas un intérprete Kern nuevo, no necesitas librerías especiales — el ecosistema Python entero sirve como verificador. The necessary condition for this loop to work is that the language be verifiable. Every Kern program can be converted to Python and executed. You don't need a new Kern interpreter, no special libraries — the entire Python ecosystem serves as the verifier.
Y hay algo más: la transpilación es determinista. El mismo Python siempre produce el mismo Kern. Eso significa que los datos de entrenamiento no tienen ruido — no hay dos formas "igual de correctas" de representar el mismo programa. El modelo aprende una sola forma canónica, lo que hace el aprendizaje más estable y el output más predecible. And there's something else: the transpilation is deterministic. The same Python always produces the same Kern. That means training data has no noise — there are no two "equally correct" ways to represent the same program. The model learns one canonical form, making learning more stable and output more predictable.
La premisa del paper: si un LLM fine-tuned en Kern logra un Pass@1 comparable al del modelo base en Python — usando menos tokens por generación — entonces existe evidencia de que un lenguaje más compacto puede sustituir a Python en contextos agénticos sin pérdida de capacidad. Eso es lo que hay que demostrar. The paper premise: if a Kern fine-tuned LLM achieves Pass@1 comparable to the Python base model — using fewer tokens per generation — then there's evidence that a more compact language can substitute Python in agentic contexts without capability loss. That's what needs to be demonstrated.
Estado actual Current Status
La gramática v0.2 está completa y validada, pero eso ya no es lo más importante. Desde el 3 de marzo de 2026, Kern ya tiene pipeline completo Python → Kern → Python funcionando sobre benchmarks reales.
Grammar v0.2 is complete and validated, but that's no longer the main point. As of March 3, 2026, Kern already has a full Python → Kern → Python pipeline running on real benchmarks.
Actualización de implementación: transpilador y compilador inverso ya están construidos, con round-trip y validación funcional completos en HumanEval. Implementation update: both the transpiler and inverse compiler are now built, with complete round-trip and functional validation on HumanEval.
Resultados de benchmark (3 mar 2026, actualizado) Benchmark Results (Mar 3, 2026, updated)
| EscenarioScenario | Python tokensPython tokens | Kern tokensKern tokens | ReducciónReduction |
|---|---|---|---|
| Gramática v0.2 (24 ejemplos sintéticos)Grammar v0.2 (24 synthetic samples) | 464 | 349 | −24.8% |
| HumanEval completo (164) · cl100k_baseFull HumanEval (164) · cl100k_base | 30368 | 8873 | −70.8% |
| MBPP train (374) · cl100k_baseMBPP train (374) · cl100k_base | 21202 | 16786 | −20.8% |
| HumanEval + MBPP train (538) · cl100k_baseHumanEval + MBPP train (538) · cl100k_base | 51570 | 25659 | −50.2% |
Benchmark multi-tokenizer (538 casos válidos) Multi-tokenizer Benchmark (538 valid cases)
| TokenizerTokenizer | HumanEvalHumanEval | MBPP trainMBPP train | Global (538)Global (538) |
|---|---|---|---|
cl100k_base |
−70.78% | −20.83% | −50.24% |
o200k_base |
−70.58% | −20.31% | −49.87% |
| LLaMA tokenizer (TinyLlama proxy)LLaMA tokenizer (TinyLlama proxy) | −69.77% | −24.57% | −50.09% |
codegen_350m_mono |
−67.13% | −23.31% | −47.48% |
Correctitud del pipeline (3 mar 2026) Pipeline Correctness (Mar 3, 2026)
| MétricaMetric | ResultadoResult | ObjetivoTarget | EstadoStatus |
|---|---|---|---|
| Transpilación Python → KernPython → Kern transpilation | 164/164 | 100% | PASS |
| Compilación Kern → PythonKern → Python compilation | 164/164 | 100% | PASS |
| Parseo Python de salidaOutput Python parseability | 164/164 | 100% | PASS |
| Equivalencia AST (normalizada)AST equivalence (normalized) | 164/164 | ≥ 90% | PASS |
Validación funcional HumanEval check(entry_point)HumanEval functional validation check(entry_point) |
164/164 | ≥ 90% | PASS |
Conclusión de esta fase: el pipeline ya está cerrado y validado. En 538 casos reales (HumanEval + MBPP train), Kern mantiene reducción de tokens cercana al 50% en promedio global y sin romper compilación ni correctitud funcional en HumanEval. Phase conclusion: the pipeline is now closed and validated. Across 538 real cases (HumanEval + MBPP train), Kern sustains close to 50% global token reduction without breaking compilation or HumanEval functional correctness.
Afirmación del benchmark actual: en todos los datasets y tokenizers evaluados, Kern supera a SimPy y Token Sugar en robustez (parse/correctitud) y eficiencia de tokens dentro del mismo protocolo de evaluación. Current benchmark claim: across all evaluated datasets and tokenizers, Kern outperforms SimPy and Token Sugar on robustness (parse/correctness) and token efficiency under the same evaluation protocol.
Update de dataset para fine-tuning (5 mar 2026) Fine-Tuning Dataset Update (Mar 5, 2026)
Ya está construido el primer corpus grande para entrenamiento de modelo: 20,000 pares Python → Kern generados automáticamente desde CodeSearchNet (Python), con pipeline de validación activo (Python → Kern → Python + ast.parse).
The first large model-training corpus is now ready: 20,000 Python → Kern pairs automatically generated from CodeSearchNet (Python), with active validation pipeline (Python → Kern → Python + ast.parse).
| MétricaMetric | ResultadoResult |
|---|---|
| Dataset origenSource dataset | code_search_net/python |
| Registros escaneadosRows scanned | 21,825 |
| Ejemplos aceptadosAccepted examples | 20,000 |
| Keep rateKeep rate | 91.64% |
| Split train/validTrain/valid split | 19,000 / 1,000 |
| Formato de salidaOutput format | pares JSONL + chat JSONL para Qwen SFTpairs JSONL + chat JSONL for Qwen SFT |
Implementado: script de generación a gran escala prepare_finetune_dataset_csn.py. Salida base en data/finetune_csn20k/ dentro del repo Kern.
Implemented: large-scale dataset builder script prepare_finetune_dataset_csn.py. Base output lives in data/finetune_csn20k/ inside the Kern repo.
Update de entrenamiento QLoRA en Colab T4 (5 mar 2026) QLoRA Training Update on Colab T4 (Mar 5, 2026)
El primer run de entrenamiento ya terminó correctamente en Colab GPU T4. Por límite de VRAM de T4, se usó Qwen/Qwen2.5-Coder-3B-Instruct (no 9B) para validar pipeline end-to-end + estabilidad real de entrenamiento.
The first training run has now completed successfully on Colab T4 GPU. Due to T4 VRAM limits, it used Qwen/Qwen2.5-Coder-3B-Instruct (not 9B) to validate full end-to-end pipeline + real training stability.
| MétricaMetric | Estado actualCurrent status |
|---|---|
| HardwareHardware | Google Colab T4 (15GB VRAM) |
| Modelo base de arranqueBootstrap base model | Qwen/Qwen2.5-Coder-3B-Instruct |
| Dataset usado en run inicialDataset used in initial run | 5,000 train / 500 valid (subset de finetune_csn20k_v2) |
| ProgresoProgress | Run completado: 313/313 steps, 1 época (~1h29m)Run completed: 313/313 steps, 1 epoch (~1h29m) |
| Bloqueo técnico resueltoResolved technical blocker | Compatibilidad TRL + precisión mixta en T4 (evitado crash bf16)TRL compatibility + mixed precision on T4 (bf16 crash avoided) |
| Artefacto finalFinal artifact | outputs/qwen-kern-qlora-t4/final_adapter |
| PublicadoPublished | Oscarcode99/kern-qwen25-3b-lora-t4-run1 |
Telemetría del run #1: train_loss=5.313, eval_loss=8.483, train_runtime=5338s. Este run valida la infraestructura; la siguiente métrica crítica es Pass@1 contra baseline Python.
Run #1 telemetry: train_loss=5.313, eval_loss=8.483, train_runtime=5338s. This run validates infrastructure; the next critical metric is Pass@1 against Python baseline.
Próximos pasos Next Steps
Siguiente fase inmediata: evaluar Pass@1 + round-trip/compilación del adapter entrenado, luego escalar de subset a corpus completo (20k) y comparar costo por solución contra baseline Python. En paralelo, ampliar cobertura con tareas inversas (Kern → Python) para reforzar lectura/edición nativa de Kern. Immediate next phase: evaluate Pass@1 + round-trip/compile behavior of the trained adapter, then scale from subset to the full 20k corpus and compare cost per solution versus a Python baseline. In parallel, expand coverage with inverse tasks (Kern → Python) to strengthen native Kern reading/editing.
Arte previo a leer: SimPy (ISSTA 2024) · Token Sugar (2025) · Token Efficiency Languages Prior art to read: SimPy (ISSTA 2024) · Token Sugar (2025) · Token Efficiency Languages
Si estás trabajando en algo relacionado o quieres discutir la gramática, búscame. Este es el tipo de problema que vale la pena atacar en comunidad. If you're working on something related or want to discuss the grammar, reach out. This is the kind of problem worth attacking together.