Datdanboi25 commited on
Commit
76db545
·
1 Parent(s): e916491

Proper commit

Browse files
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ generate_integer_arithmetic.py
2
+ *.json
3
+ *.parquet
AxiomicBanner.png CHANGED

Git LFS Details

  • SHA256: 75c38db1d76736a243905a29ba6e85eaf65e14037cd78c4f391bc146fe36fe4e
  • Pointer size: 130 Bytes
  • Size of remote file: 88 kB
README.md CHANGED
@@ -15,6 +15,47 @@ ArithMark 2.0 is a procedurally generated benchmark for evaluating integer arith
15
 
16
  The benchmark is designed for base-model log-likelihood scoring. It does not require instruction following, chain-of-thought, or generated explanations. Random chance is 25%.
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  ---
19
 
20
  ## Task Format
 
15
 
16
  The benchmark is designed for base-model log-likelihood scoring. It does not require instruction following, chain-of-thought, or generated explanations. Random chance is 25%.
17
 
18
+ The included script benchmark_arithmark-2.0.py can be used to run the benchmark.
19
+ ---
20
+
21
+ ## Baseline Results
22
+
23
+ The following results use raw continuation log-likelihood scoring on the 2,500-example ArithMark 2.0 set. Random chance is 25%.
24
+
25
+ | Model | Parameters | Overall | 1 Op | 2 Ops | 3 Ops |
26
+ | ----- | ---------- | ------: | ---: | ----: | ----: |
27
+ | Qwen/Qwen2.5-Math-1.5B | 1.54B | 82.08% | 97.44% | 77.87% | 50.00% |
28
+ | Qwen/Qwen2.5-3B | 3.09B | 78.44% | 95.52% | 71.47% | 46.20% |
29
+ | Qwen/Qwen2.5-1.5B | 1.54B | 77.72% | 97.12% | 69.47% | 41.60% |
30
+ | Qwen/Qwen2.5-Coder-1.5B | 1.54B | 74.88% | 94.96% | 65.73% | 38.40% |
31
+ | HuggingFaceTB/SmolLM2-1.7B | 1.71B | 66.12% | 89.36% | 49.33% | 33.20% |
32
+ | Qwen/Qwen2.5-0.5B | 494M | 63.04% | 82.96% | 49.87% | 33.00% |
33
+ | facebook/MobileLLM-R1-140M-base | 140M | 53.88% | 62.16% | 51.47% | 36.80% |
34
+ | EleutherAI/pythia-2.8b | 2.78B | 36.72% | 34.48% | 44.93% | 30.00% |
35
+ | HuggingFaceTB/SmolLM2-135M | 135M | 33.48% | 36.32% | 33.87% | 25.80% |
36
+ | AxiomicLabs/GPT-X2-125M | 125M | 30.72% | 28.88% | 36.00% | 27.40% |
37
+ | AxiomicLabs/GPT-X-125M | 125M | 30.16% | 27.92% | 35.20% | 28.20% |
38
+ | openai-community/gpt2-xl | 1.56B | 29.92% | 29.84% | 35.20% | 22.20% |
39
+ | HuggingFaceTB/SmolLM-135M | 135M | 28.96% | 28.40% | 31.47% | 26.60% |
40
+ | AxiomicLabs/GPT-S-5M | 5.2M | 27.24% | 26.32% | 30.00% | 25.40% |
41
+ | SupraLabs/Supra-50M-Base | 52M | 27.12% | 26.08% | 31.60% | 23.00% |
42
+ | EleutherAI/pythia-31m | 30M | 27.04% | 26.16% | 31.60% | 22.40% |
43
+ | EleutherAI/pythia-14m | 14M | 27.04% | 25.04% | 31.87% | 24.80% |
44
+ | CompactAI-O/Shard-1 | 55M | 26.92% | 26.00% | 29.20% | 25.80% |
45
+ | google/gemma-3-270m | 268M | 26.84% | 25.76% | 30.40% | 24.20% |
46
+ | openai-community/gpt2 | 124M | 26.52% | 24.80% | 31.33% | 23.60% |
47
+ | openai-community/gpt2-medium | 355M | 26.48% | 24.96% | 30.67% | 24.00% |
48
+ | EleutherAI/gpt-neo-125m | 125M | 26.36% | 27.28% | 27.87% | 21.80% |
49
+ | HuggingFaceTB/nanowhale-100m-base | 110M | 25.52% | 23.68% | 27.20% | 27.60% |
50
+ | EleutherAI/pythia-70m | 70M | 25.40% | 24.48% | 26.80% | 25.60% |
51
+ | EleutherAI/pythia-160m | 162M | 25.32% | 25.44% | 26.93% | 22.60% |
52
+ | LH-Tech-AI/Spark-5M-Base-v4 | 5.0M | 25.04% | 25.04% | 27.33% | 21.60% |
53
+ | Harley-ml/Dillion-1.2M | 1.3M | 24.92% | 24.56% | 27.47% | 22.00% |
54
+ | facebook/opt-125m | 125M | 24.68% | 24.56% | 26.67% | 22.00% |
55
+ | CompactAI-O/Glint-1.3 | 982k | 24.68% | 24.48% | 24.13% | 26.00% |
56
+ | SupraLabs/Supra-Mini-v5-8M | 7.9M | 24.40% | 24.48% | 25.73% | 22.20% |
57
+ | SupraLabs/Supra-Mini-v4-2M | 2.6M | 24.08% | 23.04% | 27.47% | 21.60% |
58
+
59
  ---
60
 
61
  ## Task Format
__pycache__/benchmark_arithmark-2.0.cpython-311.pyc.1797471302448 ADDED
Binary file (21.2 kB). View file
 
__pycache__/generate_integer_arithmetic.cpython-311.pyc ADDED
Binary file (55.5 kB). View file
 
__pycache__/generate_integer_arithmetic.cpython-311.pyc.2249071489840 ADDED
Binary file (39.9 kB). View file
 
benchmark_arithmark-2.0.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Benchmark Hugging Face causal language models exclusively on ArithMark 2.0.
3
+
4
+ The benchmark data is pulled from the official dataset repo:
5
+ https://huggingface.co/datasets/AxiomicLabs/Arithmark-2.0
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import subprocess
11
+ from contextlib import nullcontext
12
+ from pathlib import Path
13
+
14
+ import torch
15
+ import torch.nn.functional as F
16
+ from tqdm import tqdm
17
+ from transformers import AutoModelForCausalLM, AutoTokenizer
18
+
19
+
20
+ OFFICIAL_REPO = "https://huggingface.co/datasets/AxiomicLabs/Arithmark-2.0"
21
+ DATA_FILE = "arithmark_2.0.jsonl"
22
+ CACHE_DIR = "benchmark_cache"
23
+ BATCH_SIZE = 16
24
+ MAX_CONTEXT = 1024
25
+
26
+ # (model_name,) or (model_name, tokenizer_name)
27
+ MODELS = [
28
+ ("AxiomicLabs/GPT-X2-125M",),
29
+ ("AxiomicLabs/GPT-X-125M",),
30
+ ("HuggingFaceTB/SmolLM-135M",),
31
+ ]
32
+
33
+
34
+ def ensure_official_arithmark_repo(dataset_dir: Path, pull: bool = True) -> Path:
35
+ """Ensure the official ArithMark 2.0 repo exists locally and is current."""
36
+ data_path = dataset_dir / DATA_FILE
37
+
38
+ if dataset_dir.exists() and (dataset_dir / ".git").exists():
39
+ if pull:
40
+ print(f"Updating official ArithMark 2.0 repo in {dataset_dir}...")
41
+ try:
42
+ subprocess.run(
43
+ ["git", "pull", "--ff-only"],
44
+ cwd=dataset_dir,
45
+ check=True,
46
+ text=True,
47
+ )
48
+ except (OSError, subprocess.CalledProcessError) as exc:
49
+ if not data_path.exists():
50
+ raise RuntimeError(f"Could not pull {OFFICIAL_REPO}, and {data_path} is missing.") from exc
51
+ print(f" Git pull failed; using existing {data_path.name}. ({exc})")
52
+ elif not dataset_dir.exists():
53
+ print(f"Cloning official ArithMark 2.0 repo into {dataset_dir}...")
54
+ subprocess.run(["git", "clone", OFFICIAL_REPO, str(dataset_dir)], check=True, text=True)
55
+ elif not data_path.exists():
56
+ raise FileNotFoundError(
57
+ f"{dataset_dir} exists but is not a git repo and {DATA_FILE} is missing. "
58
+ f"Clone {OFFICIAL_REPO} there or pass --dataset-dir to a repo checkout."
59
+ )
60
+
61
+ if not data_path.exists():
62
+ raise FileNotFoundError(f"Expected ArithMark 2.0 data file not found: {data_path}")
63
+
64
+ return data_path
65
+
66
+
67
+ def load_arithmark_2(data_path: Path):
68
+ examples = []
69
+ with data_path.open("r", encoding="utf-8") as f:
70
+ for line in f:
71
+ item = json.loads(line)
72
+ examples.append(
73
+ {
74
+ "ctx": item["ctx"],
75
+ "endings": item["endings"],
76
+ "label": int(item["label"]),
77
+ "metadata": item.get("metadata", {}),
78
+ }
79
+ )
80
+ return examples
81
+
82
+
83
+ def load_hf_model(model_name: str, tokenizer_name: str, device: str):
84
+ model = AutoModelForCausalLM.from_pretrained(
85
+ model_name,
86
+ dtype=torch.bfloat16 if device == "cuda" else torch.float32,
87
+ trust_remote_code=True,
88
+ ).to(device)
89
+ model.eval()
90
+
91
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, trust_remote_code=True, use_fast=False)
92
+ if tokenizer.pad_token is None:
93
+ tokenizer.pad_token = tokenizer.eos_token
94
+ if tokenizer.pad_token_id is None:
95
+ tokenizer.pad_token_id = tokenizer.eos_token_id if tokenizer.eos_token_id is not None else 0
96
+
97
+ return model, tokenizer
98
+
99
+
100
+ def tokenize_request(tokenizer, context: str, continuation: str):
101
+ ctx_tokens = tokenizer(context, add_special_tokens=False).input_ids
102
+ # ArithMark 2.0 continuations already include the leading space documented
103
+ # by the official dataset, so score the raw continuation as provided.
104
+ cont_tokens = tokenizer(continuation, add_special_tokens=False).input_ids
105
+ tokens = ctx_tokens + cont_tokens
106
+
107
+ if len(tokens) > MAX_CONTEXT:
108
+ tokens = tokens[-MAX_CONTEXT:]
109
+ ctx_len = max(1, len(tokens) - len(cont_tokens))
110
+ else:
111
+ ctx_len = len(ctx_tokens)
112
+
113
+ return tokens, max(0, len(tokens) - ctx_len)
114
+
115
+
116
+ def evaluate_arithmark_2(model, tokenizer, device: str, examples, batch_size: int):
117
+ correct = 0
118
+ total = 0
119
+ grouped = {}
120
+
121
+ for idx_start in tqdm(range(0, len(examples), batch_size), desc=" arithmark_2.0"):
122
+ batch_ex = examples[idx_start:idx_start + batch_size]
123
+ batch_tokens = []
124
+ batch_cont_lens = []
125
+ ex_offsets = []
126
+
127
+ for ex in batch_ex:
128
+ flat_start = len(batch_tokens)
129
+ for ending in ex["endings"]:
130
+ tokens, cont_len = tokenize_request(tokenizer, ex["ctx"], ending)
131
+ batch_tokens.append(tokens)
132
+ batch_cont_lens.append(cont_len)
133
+ ex_offsets.append((flat_start, len(ex["endings"])))
134
+
135
+ max_len = max(len(tokens) for tokens in batch_tokens)
136
+ padded = [tokens + [tokenizer.pad_token_id] * (max_len - len(tokens)) for tokens in batch_tokens]
137
+ tokens_t = torch.tensor(padded, dtype=torch.long, device=device)
138
+ lengths = torch.tensor([len(tokens) for tokens in batch_tokens], device=device)
139
+ attention_mask = torch.arange(max_len, device=device)[None, :] < lengths[:, None]
140
+
141
+ attention_mask = attention_mask.bool()
142
+
143
+ autocast_context = (
144
+ torch.autocast(device_type="cuda", dtype=torch.bfloat16)
145
+ if device == "cuda"
146
+ else nullcontext()
147
+ )
148
+
149
+ with torch.no_grad():
150
+ with autocast_context:
151
+ logits = model(tokens_t, attention_mask=attention_mask).logits
152
+
153
+ log_probs = F.log_softmax(logits.float(), dim=-1)
154
+
155
+ for ex_idx, ex in enumerate(batch_ex):
156
+ flat_start, num_choices = ex_offsets[ex_idx]
157
+ lls = []
158
+ for choice_idx in range(num_choices):
159
+ flat_idx = flat_start + choice_idx
160
+ tokens_i = batch_tokens[flat_idx]
161
+ cont_len = batch_cont_lens[flat_idx]
162
+ start = len(tokens_i) - cont_len
163
+ ll = 0.0
164
+ for pos in range(start, len(tokens_i)):
165
+ if pos > 0:
166
+ ll += log_probs[flat_idx, pos - 1, tokens_i[pos]].item()
167
+ lls.append(ll)
168
+
169
+ pred = max(range(num_choices), key=lambda i: lls[i])
170
+ label = int(ex["label"])
171
+ correct += int(pred == label)
172
+ total += 1
173
+
174
+ operator_count = ex.get("metadata", {}).get("operator_count", "unknown")
175
+ if operator_count not in grouped:
176
+ grouped[operator_count] = [0, 0]
177
+ grouped[operator_count][0] += int(pred == label)
178
+ grouped[operator_count][1] += 1
179
+
180
+ del tokens_t, logits, log_probs
181
+ if device == "cuda":
182
+ torch.cuda.empty_cache()
183
+
184
+ acc = correct / total * 100 if total else 0.0
185
+ print(f" arithmark_2.0: acc {acc:.2f}% ({correct}/{total})")
186
+
187
+ if grouped:
188
+ groups = sorted(grouped, key=lambda value: (str(type(value)), value))
189
+ header = " " + " ".join(f"ops={group!s:>3}" for group in groups) + f" {'Avg':>6}"
190
+ vals = []
191
+ for group in groups:
192
+ group_correct, group_total = grouped[group]
193
+ vals.append(group_correct / group_total * 100 if group_total else 0.0)
194
+ print(header)
195
+ print(f" {'-' * (len(header) - 2)}")
196
+ print(" " + " ".join(f"{value:>6.2f}%" for value in vals) + f" {acc:>5.2f}%")
197
+
198
+ return {"acc": acc, "correct": correct, "total": total}
199
+
200
+
201
+ def parse_args():
202
+ parser = argparse.ArgumentParser(description="Run ArithMark 2.0 only.")
203
+ parser.add_argument("--model", action="append", help="HF model id. Can be passed multiple times.")
204
+ parser.add_argument("--tokenizer", help="Tokenizer id to use for all --model entries.")
205
+ parser.add_argument("--batch-size", type=int, default=BATCH_SIZE)
206
+ parser.add_argument("--dataset-dir", default=str(Path(__file__).resolve().parent))
207
+ parser.add_argument("--no-pull", action="store_true", help="Do not git pull the official dataset repo before running.")
208
+ return parser.parse_args()
209
+
210
+
211
+ def main():
212
+ args = parse_args()
213
+ torch.set_float32_matmul_precision("high")
214
+ torch.backends.cuda.matmul.allow_tf32 = True
215
+ torch.backends.cudnn.allow_tf32 = True
216
+
217
+ dataset_dir = Path(args.dataset_dir).resolve()
218
+ data_path = ensure_official_arithmark_repo(dataset_dir, pull=not args.no_pull)
219
+ examples = load_arithmark_2(data_path)
220
+ print(f"Loaded {len(examples)} ArithMark 2.0 examples from {data_path}")
221
+
222
+ device = "cuda" if torch.cuda.is_available() else "cpu"
223
+ print(f"Using device: {device}")
224
+
225
+ model_entries = [(model,) for model in args.model] if args.model else MODELS
226
+ all_results = {}
227
+
228
+ for model_entry in model_entries:
229
+ model_name = model_entry[0]
230
+ tokenizer_name = args.tokenizer or (model_entry[1] if len(model_entry) > 1 else model_name)
231
+
232
+ print(f"\n{'=' * 60}")
233
+ print(f" Loading {model_name}...")
234
+ print(f"{'=' * 60}")
235
+
236
+ try:
237
+ model, tokenizer = load_hf_model(model_name, tokenizer_name, device)
238
+ except Exception as exc:
239
+ print(f" Failed to load model: {exc}")
240
+ continue
241
+
242
+ total_params = sum(param.numel() for param in model.parameters())
243
+ print(f" {total_params:,} parameters")
244
+
245
+ result = evaluate_arithmark_2(model, tokenizer, device, examples, args.batch_size)
246
+ all_results[model_name] = result
247
+
248
+ print(f"\n{'=' * 60}")
249
+ print(f" {model_name} ({total_params:,} params) RESULTS")
250
+ print(f"{'=' * 60}")
251
+ print(f" arithmark_2.0 {result['acc']:>9.2f}%")
252
+ print(f"{'=' * 60}")
253
+
254
+ model_tag = model_name.replace("/", "_")
255
+ results_dir = Path(CACHE_DIR)
256
+ results_dir.mkdir(parents=True, exist_ok=True)
257
+ results_file = results_dir / f"{model_tag}_arithmark_2.0_results.json"
258
+ with results_file.open("w", encoding="utf-8") as f:
259
+ json.dump(
260
+ {
261
+ "model": model_name,
262
+ "params": total_params,
263
+ "dataset": str(data_path),
264
+ "results": {"arithmark_2.0": result},
265
+ },
266
+ f,
267
+ indent=2,
268
+ )
269
+ print(f"Results saved to {results_file}")
270
+
271
+ del model
272
+ if device == "cuda":
273
+ torch.cuda.empty_cache()
274
+
275
+ if len(all_results) > 1:
276
+ print(f"\n{'=' * 60}")
277
+ print(" FINAL SUMMARY")
278
+ print(f"{'=' * 60}")
279
+ for model_name, result in all_results.items():
280
+ print(f" {model_name:<45} {result['acc']:>7.2f}%")
281
+ print(f"{'=' * 60}")
282
+
283
+
284
+ if __name__ == "__main__":
285
+ main()