David-Coronel commited on
Commit
380240b
·
verified ·
1 Parent(s): 08f5328

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -67,6 +67,7 @@ El resultado es una medida de **autoconocimiento del modelo**: no si es capaz de
67
  | `tasks.jsonl` | Las 14 tareas: `id`, `category`, `prompt`. |
68
  | `results.jsonl` | Una fila por par (modelo, tarea): estimación, tokens reales, texto completo de la respuesta, error si lo hubo. |
69
  | `estimate_bench.py` | El código exacto del runner para reproducir o extender el benchmark. |
 
70
 
71
  Esquema de `results.jsonl`:
72
 
@@ -93,6 +94,15 @@ python estimate_bench.py --model openai/gpt-4o-mini --model qwen/qwen3-max
93
 
94
  El runner funciona con cualquier endpoint compatible con la API de OpenAI (OpenRouter por defecto). Cada par (modelo, tarea) hace dos llamadas independientes con temperatura 0: la de estimación (con la instrucción de no resolver la tarea) y la de ejecución (la tarea a secas). Los tokens reales son `usage.completion_tokens` devuelto por la API.
95
 
 
 
 
 
 
 
 
 
 
96
  ## Limitaciones
97
 
98
  - **Una muestra por celda**: cada par (modelo, tarea) se ejecutó una vez (temperatura 0); la longitud real puede variar entre ejecuciones.
 
67
  | `tasks.jsonl` | Las 14 tareas: `id`, `category`, `prompt`. |
68
  | `results.jsonl` | Una fila por par (modelo, tarea): estimación, tokens reales, texto completo de la respuesta, error si lo hubo. |
69
  | `estimate_bench.py` | El código exacto del runner para reproducir o extender el benchmark. |
70
+ | `lm_eval_tasks/` | Adaptación del benchmark como tarea de [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) (ver su README). |
71
 
72
  Esquema de `results.jsonl`:
73
 
 
94
 
95
  El runner funciona con cualquier endpoint compatible con la API de OpenAI (OpenRouter por defecto). Cada par (modelo, tarea) hace dos llamadas independientes con temperatura 0: la de estimación (con la instrucción de no resolver la tarea) y la de ejecución (la tarea a secas). Los tokens reales son `usage.completion_tokens` devuelto por la API.
96
 
97
+ También puedes correrlo como tarea de lm-evaluation-harness (ver `lm_eval_tasks/README.md`):
98
+
99
+ ```bash
100
+ pip install "lm-eval[api]" transformers
101
+ lm_eval --model local-chat-completions \
102
+ --model_args "model=qwen/qwen3-max,base_url=https://openrouter.ai/api/v1/chat/completions,tokenizer=Qwen/Qwen2.5-7B-Instruct" \
103
+ --apply_chat_template --tasks estimate_bench --include_path lm_eval_tasks
104
+ ```
105
+
106
  ## Limitaciones
107
 
108
  - **Una muestra por celda**: cada par (modelo, tarea) se ejecutó una vez (temperatura 0); la longitud real puede variar entre ejecuciones.
lm_eval_tasks/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # estimate-bench como tarea de lm-evaluation-harness
2
+
3
+ Adaptación del benchmark para el [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) de EleutherAI.
4
+
5
+ Por cada tarea se emiten **dos generaciones**: una de estimación (el modelo
6
+ predice los tokens de su propia respuesta sin resolverla) y una de ejecución.
7
+ Se comparan y se agregan cuatro métricas:
8
+
9
+ | métrica | significado | mejor |
10
+ |---|---|---|
11
+ | `mape` | error porcentual medio estimado vs real | menor |
12
+ | `log2_ratio` (agregado como `bias_agg`) | sesgo: factor medio estimado/real (1.0 = perfecto) | cercano a 1 |
13
+ | `within_2x` | % de tareas con estimación entre 0.5x y 2x de la realidad | mayor |
14
+ | `pair` (agregado como `spearman_agg`) | correlación de rangos estimado vs real | mayor |
15
+
16
+ ## Uso
17
+
18
+ ```bash
19
+ pip install "lm-eval[api]" transformers
20
+
21
+ # con cualquier endpoint OpenAI-compatible de chat (OpenRouter, vLLM, etc.)
22
+ export OPENAI_API_KEY=sk-or-...
23
+ lm_eval \
24
+ --model local-chat-completions \
25
+ --model_args "model=qwen/qwen3-max,base_url=https://openrouter.ai/api/v1/chat/completions,num_concurrent=4,tokenizer=Qwen/Qwen2.5-7B-Instruct" \
26
+ --apply_chat_template \
27
+ --tasks estimate_bench \
28
+ --include_path lm_eval_tasks \
29
+ --output_path results/
30
+ ```
31
+
32
+ Notas:
33
+
34
+ - `local-chat-completions` (no `local-completions`) es la clase para endpoints de chat.
35
+ - `tokenizer=` solo se usa internamente para plantillas de chat; cualquier tokenizer de HF con chat template sirve.
36
+ - Verificado end-to-end con `lm_eval 0.4.13` y OpenRouter.
37
+
38
+ ## Diferencias con el runner original (`estimate_bench.py`)
39
+
40
+ - **Los tokens "reales" son una aproximación**: la API del harness no expone
41
+ `usage.completion_tokens`, así que la longitud real se estima tokenizando la
42
+ respuesta (~0.75 palabras/token). El runner original usa el conteo exacto
43
+ de la API.
44
+ - Los modelos con razonamiento oculto (Kimi K2, o-series, R1) devuelven por
45
+ la API de chat solo el texto final: su razonamiento **no** se cuenta aquí,
46
+ mientras que en el runner original sí (va incluido en `completion_tokens`).
47
+ Los números de ambas vías no son directamente comparables para razonadores.
lm_eval_tasks/estimate_bench/estimate_bench.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task: estimate_bench
2
+ class: !function task.EstimateBenchTask
3
+ dataset_path: json
4
+ dataset_kwargs:
5
+ data_files:
6
+ validation: tasks.jsonl
7
+ test_split: null
8
+ validation_split: validation
9
+ doc_to_text: "{{prompt}}"
10
+ doc_to_target: "0"
11
+ output_type: generate_until
12
+ generation_kwargs:
13
+ temperature: 0
14
+ until: []
15
+ metric_list:
16
+ - metric: est_mape
17
+ aggregation: est_mape
18
+ higher_is_better: false
19
+ - metric: est_log2_ratio
20
+ aggregation: est_bias
21
+ higher_is_better: false
22
+ - metric: est_within_2x
23
+ aggregation: est_within_2x
24
+ higher_is_better: true
25
+ - metric: est_pair
26
+ aggregation: est_spearman
27
+ higher_is_better: true
28
+ metadata:
29
+ version: 0.1
lm_eval_tasks/estimate_bench/task.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ # estimate-bench — Copyright (C) 2026 David Coronel
3
+ """Tarea estimate-bench para lm-evaluation-harness.
4
+
5
+ Mide la autoestimación de tokens de salida: por cada documento se emiten DOS
6
+ peticiones de generación —una de estimación (predecir los tokens de la propia
7
+ respuesta, sin resolver la tarea) y una de ejecución (resolverla)— y se
8
+ comparan. Los "tokens reales" se cuentan tokenizando la respuesta generada
9
+ (la API del harness no expone usage.completion_tokens), así que son una
10
+ aproximación al tokenizer del modelo evaluado.
11
+
12
+ Métricas agregadas: MAPE, sesgo (factor), % dentro de 2x y Spearman.
13
+ """
14
+
15
+ import json
16
+ import math
17
+ import re
18
+ import statistics
19
+ from pathlib import Path
20
+
21
+ from lm_eval.api.instance import Instance
22
+ from lm_eval.api.registry import (register_aggregation, register_metric)
23
+ from lm_eval.api.task import ConfigurableTask
24
+ from lm_eval.models.api_models import JsonChatStr
25
+
26
+ ESTIMATE_INSTRUCTION = (
27
+ "You will be given a task. Do NOT solve the task.\n"
28
+ "Instead, estimate how many tokens your own response would contain if you "
29
+ "did solve it.\n"
30
+ "Respond with a single integer and nothing else.\n\n"
31
+ "Task:\n\"\"\"\n{prompt}\n\"\"\""
32
+ )
33
+
34
+
35
+ def parse_estimate(text: str) -> int | None:
36
+ m = re.search(r'"estimated_tokens"\s*:\s*([\d,]+)', text)
37
+ if m:
38
+ return int(m.group(1).replace(",", ""))
39
+ nums = re.findall(r"[\d][\d,]*", text)
40
+ return int(nums[-1].replace(",", "")) if nums else None
41
+
42
+
43
+ def _tokens(text: str) -> int:
44
+ """Aproximación de tokens sin acceso al tokenizer del modelo.
45
+
46
+ ~0.75 palabras/token es la media habitual en inglés para tokenizers BPE;
47
+ se documenta como limitación de la adaptación al harness.
48
+ """
49
+ return max(1, round(len(text.split()) / 0.75))
50
+
51
+
52
+ class EstimateBenchTask(ConfigurableTask):
53
+ def __init__(self, config=None):
54
+ # el factory de lm-eval deja la clave "class" dentro del config
55
+ config = dict(config or {})
56
+ config.pop("class", None)
57
+ super().__init__(config=config)
58
+
59
+ def build_all_requests(self, *, limit=None, samples=None, rank=0,
60
+ world_size=1, apply_chat_template=False, **kwargs):
61
+ # 2 instancias por documento: idx 0 = estimación, idx 1 = ejecución;
62
+ # el evaluator las agrupa por doc_id y las ordena por idx
63
+ def ctx(text: str):
64
+ # los modelos de chat de la API esperan los mensajes como
65
+ # JsonChatStr (JSON con list[dict]); modelos de texto plano, str
66
+ if apply_chat_template:
67
+ return JsonChatStr(prompt=json.dumps(
68
+ [{"role": "user", "content": text}]))
69
+ return text
70
+
71
+ self._instances = []
72
+ for doc_id, doc in self.doc_iterator(rank=rank, limit=limit,
73
+ world_size=world_size,
74
+ samples=samples):
75
+ self._instances.append(Instance(
76
+ request_type="generate_until",
77
+ doc=doc,
78
+ arguments=(ctx(ESTIMATE_INSTRUCTION.format(prompt=doc["prompt"])),
79
+ {"max_gen_toks": 64, "temperature": 0}),
80
+ idx=0,
81
+ metadata=(self.config.task, doc_id, 1),
82
+ ))
83
+ self._instances.append(Instance(
84
+ request_type="generate_until",
85
+ doc=doc,
86
+ arguments=(ctx(doc["prompt"]),
87
+ {"max_gen_toks": 2048, "temperature": 0}),
88
+ idx=1,
89
+ metadata=(self.config.task, doc_id, 1),
90
+ ))
91
+
92
+ def process_results(self, doc, results):
93
+ # results llegan en orden de idx: [estimación, ejecución]
94
+ est_text = results[0][0] if isinstance(results[0], (list, tuple)) else results[0]
95
+ answer = results[1][0] if isinstance(results[1], (list, tuple)) else results[1]
96
+ est = parse_estimate(est_text or "")
97
+ actual = _tokens(answer or "")
98
+ if not est or not actual:
99
+ return {"est_mape": None, "est_log2_ratio": None,
100
+ "est_within_2x": None, "est_pair": None}
101
+ return {
102
+ "est_mape": abs(est - actual) / actual,
103
+ "est_log2_ratio": math.log2(max(est, 1) / actual),
104
+ "est_within_2x": 1.0 if 0.5 <= est / actual <= 2 else 0.0,
105
+ "est_pair": (est, actual),
106
+ }
107
+
108
+
109
+ # --- funciones de agregación (referenciadas desde el YAML) -------------------
110
+
111
+ def _valid(items):
112
+ return [x for x in items if x is not None]
113
+
114
+
115
+ @register_aggregation("est_mape")
116
+ def mape_agg(items):
117
+ items = _valid(items)
118
+ return statistics.mean(items) if items else float("nan")
119
+
120
+
121
+ @register_aggregation("est_bias")
122
+ def bias_agg(items):
123
+ items = _valid(items)
124
+ return 2 ** statistics.mean(items) if items else float("nan")
125
+
126
+
127
+ @register_aggregation("est_within_2x")
128
+ def within_2x_agg(items):
129
+ items = _valid(items)
130
+ return statistics.mean(items) if items else float("nan")
131
+
132
+
133
+ @register_aggregation("est_spearman")
134
+ def spearman_agg(items):
135
+ items = _valid(items)
136
+ if len(items) < 3:
137
+ return float("nan")
138
+ est = [p[0] for p in items]
139
+ act = [p[1] for p in items]
140
+
141
+ def rank(v):
142
+ order = sorted(range(len(v)), key=lambda i: v[i])
143
+ ranks = [0.0] * len(v)
144
+ i = 0
145
+ while i < len(v):
146
+ j = i
147
+ while j + 1 < len(v) and v[order[j + 1]] == v[order[i]]:
148
+ j += 1
149
+ for k in range(i, j + 1):
150
+ ranks[order[k]] = (i + j) / 2 + 1
151
+ i = j + 1
152
+ return ranks
153
+
154
+ rx, ry = rank(est), rank(act)
155
+ mx, my = statistics.mean(rx), statistics.mean(ry)
156
+ cov = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
157
+ vx = sum((a - mx) ** 2 for a in rx)
158
+ vy = sum((b - my) ** 2 for b in ry)
159
+ return cov / math.sqrt(vx * vy) if vx and vy else float("nan")
160
+
161
+
162
+ # Registro de los nombres de métrica para que lm-eval no los busque en el
163
+ # registro global ni en HF Evaluate. Las funciones per-doc no se llaman
164
+ # nunca: los valores los calcula EstimateBenchTask.process_results.
165
+ @register_metric(metric="est_mape", higher_is_better=False,
166
+ aggregation="est_mape")
167
+ def _metric_mape(references, predictions):
168
+ raise NotImplementedError
169
+
170
+
171
+ @register_metric(metric="est_log2_ratio", higher_is_better=False,
172
+ aggregation="est_bias")
173
+ def _metric_log2_ratio(references, predictions):
174
+ raise NotImplementedError
175
+
176
+
177
+ @register_metric(metric="est_within_2x", higher_is_better=True,
178
+ aggregation="est_within_2x")
179
+ def _metric_within_2x(references, predictions):
180
+ raise NotImplementedError
181
+
182
+
183
+ @register_metric(metric="est_pair", higher_is_better=True,
184
+ aggregation="est_spearman")
185
+ def _metric_pair(references, predictions):
186
+ raise NotImplementedError
lm_eval_tasks/estimate_bench/tasks.jsonl ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "factual-short", "category": "qa", "prompt": "What is the capital of Australia? Answer with a single word."}
2
+ {"id": "definition", "category": "qa", "prompt": "Define the term \"photosynthesis\" in one sentence."}
3
+ {"id": "list-20", "category": "generation", "prompt": "List 20 European capitals, one per line, with no extra commentary."}
4
+ {"id": "poem", "category": "generation", "prompt": "Write a haiku about autumn rain."}
5
+ {"id": "essay-500", "category": "long-form", "prompt": "Write an essay of approximately 500 words on the main causes of World War I."}
6
+ {"id": "code-small", "category": "code", "prompt": "Write a Python function that checks whether a string is a palindrome. Include a docstring and two example calls."}
7
+ {"id": "code-lru", "category": "code", "prompt": "Implement an LRU cache in Python with O(1) get and put operations. Use type hints and include a short usage example."}
8
+ {"id": "math-short", "category": "math", "prompt": "Compute 17 * 23. Show your steps briefly."}
9
+ {"id": "math-word", "category": "math", "prompt": "A train travels 300 km in 2.5 hours, then 180 km in 1.5 hours. What is its average speed for the whole journey? Explain your reasoning step by step."}
10
+ {"id": "translation", "category": "translation", "prompt": "Translate the following paragraph into French: \"The library was quiet except for the soft rustling of pages. Outside, the rain traced silver lines down the windows, and the smell of old paper filled the air.\""}
11
+ {"id": "summarize", "category": "summarization", "prompt": "Summarize the following passage in exactly 3 bullet points: \"The Industrial Revolution, beginning in Britain in the late 18th century, transformed economies that had been based on agriculture and handicrafts into economies based on large-scale industry, mechanized manufacturing, and the factory system. New machines, new power sources, and new ways of organizing work made existing industries more productive and efficient. The textile industry was among the first to use modern production methods. The revolution spread to other parts of Europe and North America over the following decades, and its social consequences included urbanization, the growth of a working class, and new patterns of labor that still shape modern life.\""}
12
+ {"id": "json-extract", "category": "extraction", "prompt": "Extract structured data from this text and return ONLY valid JSON with keys name, role, company, start_year: \"Maria Chen joined Orbital Dynamics as a senior propulsion engineer in 2019, after five years at a rival firm.\""}
13
+ {"id": "table-50", "category": "generation", "prompt": "Generate a markdown table of all 50 US states with their capital city and approximate population."}
14
+ {"id": "explain-technical", "category": "long-form", "prompt": "Explain how a transformer neural network works, in technical detail, covering attention, positional encodings, and training. Aim for roughly 800 words."}