Spaces:
Running
Running
Batch HF inference with pretokenization and live progress
#1
by appvoid - opened
marc.py
CHANGED
|
@@ -26,6 +26,17 @@ Usage (multi-model bucket — run any mix of HF + OpenAI models, print a summary
|
|
| 26 |
python marc.py --openai m1 --openai m2 \\
|
| 27 |
--base-url http://h1/v1 --base-url http://h2/v1
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
Usage (verify leak invariants):
|
| 30 |
python marc.py --selftest
|
| 31 |
"""
|
|
@@ -368,41 +379,222 @@ def parse_grid(text: str) -> Grid | None:
|
|
| 368 |
# 3. Models — HF (base or instruct) + OpenAI-compatible endpoint
|
| 369 |
# ═══════════════════════════════════════════════════════════════════════════
|
| 370 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
class HFModel:
|
| 372 |
def __init__(self, name: str, chat: bool, device: str = "cuda",
|
| 373 |
-
trust_remote_code: bool = False
|
|
|
|
|
|
|
| 374 |
import torch
|
| 375 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
self.tok.pad_token = self.tok.eos_token
|
| 380 |
self.tok.padding_side = "left"
|
|
|
|
|
|
|
|
|
|
| 381 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 382 |
-
name, torch_dtype=
|
| 383 |
trust_remote_code=trust_remote_code).to(device).eval()
|
| 384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
def generate(self, prompts, n, temperature, max_new_tokens):
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
|
|
|
|
|
|
| 405 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
class OpenAIModel:
|
| 408 |
def __init__(self, model: str, base_url: str, chat: bool, api_key: str = "EMPTY"):
|
|
@@ -440,16 +632,25 @@ def _score(samples: list[str], target: Grid) -> dict:
|
|
| 440 |
|
| 441 |
def run(model, chat, families, difficulties, n_per_cell, n_samples,
|
| 442 |
temperature, max_new_tokens, seed, verbose=True):
|
|
|
|
|
|
|
| 443 |
rows, t0 = [], time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
for diff in difficulties:
|
| 445 |
for fam in families:
|
| 446 |
acc = {"em": 0.0, "format": 0.0, "pass": 0.0}
|
| 447 |
-
for
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
for m, v in _score(samples, task.query_out).items():
|
| 452 |
-
acc[m] += v
|
| 453 |
cell = {m: acc[m] / n_per_cell for m in acc}
|
| 454 |
cell.update({"family": fam, "difficulty": diff})
|
| 455 |
rows.append(cell)
|
|
@@ -479,7 +680,9 @@ def build_models(args):
|
|
| 479 |
specs.append((f"hf:{name}",
|
| 480 |
lambda n=name: HFModel(
|
| 481 |
n, chat=args.chat, device=args.device,
|
| 482 |
-
trust_remote_code=args.trust_remote_code
|
|
|
|
|
|
|
| 483 |
|
| 484 |
if args.openai:
|
| 485 |
if not args.base_url:
|
|
@@ -519,7 +722,7 @@ def run_multi(specs, args):
|
|
| 519 |
all_results[label] = run(
|
| 520 |
model, args.chat, args.families, args.difficulties,
|
| 521 |
args.n_per_cell, args.n_samples, args.temperature,
|
| 522 |
-
args.max_new_tokens, args.seed)
|
| 523 |
finally:
|
| 524 |
del model
|
| 525 |
gc.collect()
|
|
@@ -645,7 +848,22 @@ def main():
|
|
| 645 |
ap.add_argument("--temperature", type=float, default=0.0)
|
| 646 |
ap.add_argument("--max-new-tokens", type=int, default=200)
|
| 647 |
ap.add_argument("--seed", default="0")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
args = ap.parse_args()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 649 |
|
| 650 |
if args.selftest:
|
| 651 |
_self_test()
|
|
@@ -659,4 +877,4 @@ def main():
|
|
| 659 |
|
| 660 |
|
| 661 |
if __name__ == "__main__":
|
| 662 |
-
main()
|
|
|
|
| 26 |
python marc.py --openai m1 --openai m2 \\
|
| 27 |
--base-url http://h1/v1 --base-url http://h2/v1
|
| 28 |
|
| 29 |
+
HF inference tokenizes the selected run once, length-buckets cached input IDs,
|
| 30 |
+
and uses batched KV-cached decoding (default 32 puzzles) with CUDA OOM backoff.
|
| 31 |
+
Progress reports actual completed puzzles, decode tokens, elapsed time and ETA.
|
| 32 |
+
Set --batch-size 1 for single-item comparisons. Batching can change floating-point
|
| 33 |
+
rounding and sampled RNG order; do not expect identical sampled completions.
|
| 34 |
+
Task seeds, puzzle demonstrations, grid parsing and scoring are unchanged.
|
| 35 |
+
|
| 36 |
+
Usage (batched HF):
|
| 37 |
+
python marc.py --hf HuggingFaceTB/SmolLM2-360M --batch-size 32
|
| 38 |
+
python marc.py --hf YOUR_MODEL --device cpu --dtype float32 --batch-size 8
|
| 39 |
+
|
| 40 |
Usage (verify leak invariants):
|
| 41 |
python marc.py --selftest
|
| 42 |
"""
|
|
|
|
| 379 |
# 3. Models — HF (base or instruct) + OpenAI-compatible endpoint
|
| 380 |
# ═══════════════════════════════════════════════════════════════════════════
|
| 381 |
|
| 382 |
+
class _Progress:
|
| 383 |
+
"""Periodic, flushed progress for long GPU calls; never prints model text."""
|
| 384 |
+
def __init__(self, total, quiet=False, interval=5.0):
|
| 385 |
+
import threading
|
| 386 |
+
self.total, self.quiet, self.interval = total, quiet, interval
|
| 387 |
+
self.done = self.tokens = 0
|
| 388 |
+
self.stage = "prefill"
|
| 389 |
+
self.started = time.monotonic()
|
| 390 |
+
self.stop = threading.Event()
|
| 391 |
+
self.lock = threading.RLock()
|
| 392 |
+
|
| 393 |
+
def update(self, stage=None, done=None, tokens=None):
|
| 394 |
+
with self.lock:
|
| 395 |
+
if stage is not None:
|
| 396 |
+
self.stage = stage
|
| 397 |
+
if done is not None:
|
| 398 |
+
self.done = done
|
| 399 |
+
if tokens is not None:
|
| 400 |
+
self.tokens = tokens
|
| 401 |
+
|
| 402 |
+
def show(self):
|
| 403 |
+
if self.quiet:
|
| 404 |
+
return
|
| 405 |
+
with self.lock:
|
| 406 |
+
elapsed = max(time.monotonic() - self.started, 1e-6)
|
| 407 |
+
rate = self.done / elapsed
|
| 408 |
+
eta = f"{(self.total - self.done) / rate:.0f}s" if rate else "pending"
|
| 409 |
+
print(f"MARC {self.stage}: {self.done}/{self.total} puzzles | "
|
| 410 |
+
f"{self.tokens} generated tokens | {rate:.2f} puzzles/s | "
|
| 411 |
+
f"elapsed {elapsed:.0f}s | ETA {eta}", file=sys.stderr, flush=True)
|
| 412 |
+
|
| 413 |
+
def __enter__(self):
|
| 414 |
+
import threading
|
| 415 |
+
def heartbeat():
|
| 416 |
+
while not self.stop.wait(self.interval):
|
| 417 |
+
self.show()
|
| 418 |
+
self.thread = threading.Thread(target=heartbeat, daemon=True)
|
| 419 |
+
self.show()
|
| 420 |
+
if not self.quiet:
|
| 421 |
+
self.thread.start()
|
| 422 |
+
return self
|
| 423 |
+
|
| 424 |
+
def __exit__(self, kind, value, tb):
|
| 425 |
+
self.stop.set()
|
| 426 |
+
if self.thread.is_alive():
|
| 427 |
+
self.thread.join(timeout=1)
|
| 428 |
+
self.update(stage="failed" if kind else "finished")
|
| 429 |
+
self.show()
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class _TokenProgress:
|
| 433 |
+
"""Transformers streamer counting decode tokens, excluding after-EOS padding."""
|
| 434 |
+
def __init__(self, progress, count, eos, base):
|
| 435 |
+
self.progress, self.eos, self.base = progress, eos, base
|
| 436 |
+
self.active = [True] * count
|
| 437 |
+
self.first, self.tokens = True, 0
|
| 438 |
+
|
| 439 |
+
def put(self, value):
|
| 440 |
+
if self.first: # Initial prompt IDs are not generated tokens.
|
| 441 |
+
self.first = False
|
| 442 |
+
return
|
| 443 |
+
for i, token in enumerate(value.tolist()):
|
| 444 |
+
if self.active[i]:
|
| 445 |
+
self.tokens += 1
|
| 446 |
+
if token in self.eos:
|
| 447 |
+
self.active[i] = False
|
| 448 |
+
self.progress.update(stage="decoding", tokens=self.base + self.tokens)
|
| 449 |
+
|
| 450 |
+
def end(self):
|
| 451 |
+
pass
|
| 452 |
+
|
| 453 |
+
|
| 454 |
class HFModel:
|
| 455 |
def __init__(self, name: str, chat: bool, device: str = "cuda",
|
| 456 |
+
trust_remote_code: bool = False, batch_size: int = 32,
|
| 457 |
+
max_model_len: int | None = None, dtype: str = "auto",
|
| 458 |
+
quiet: bool = False, progress_interval: float = 5.0):
|
| 459 |
import torch
|
| 460 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 461 |
+
if batch_size < 1 or (max_model_len is not None and max_model_len < 1):
|
| 462 |
+
raise ValueError("batch_size and max_model_len must be positive")
|
| 463 |
+
if progress_interval <= 0:
|
| 464 |
+
raise ValueError("progress_interval must be positive")
|
| 465 |
+
self.batch_size, self.max_model_len = batch_size, max_model_len
|
| 466 |
+
self.quiet, self.progress_interval = quiet, progress_interval
|
| 467 |
+
self.device, self.chat, self.torch = device, chat, torch
|
| 468 |
+
self._encoded = {}
|
| 469 |
+
if not quiet:
|
| 470 |
+
print(f"MARC loading tokenizer: {name}", file=sys.stderr, flush=True)
|
| 471 |
+
self.tok = AutoTokenizer.from_pretrained(name, trust_remote_code=trust_remote_code)
|
| 472 |
+
if self.tok.pad_token_id is None:
|
| 473 |
+
if self.tok.eos_token_id is None:
|
| 474 |
+
raise ValueError("Tokenizer needs a PAD or EOS token for batching")
|
| 475 |
self.tok.pad_token = self.tok.eos_token
|
| 476 |
self.tok.padding_side = "left"
|
| 477 |
+
resolved_dtype = (torch.bfloat16 if device.startswith("cuda") else torch.float32) if dtype == "auto" else getattr(torch, dtype)
|
| 478 |
+
if not quiet:
|
| 479 |
+
print(f"MARC loading model weights: {name}", file=sys.stderr, flush=True)
|
| 480 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 481 |
+
name, torch_dtype=resolved_dtype,
|
| 482 |
trust_remote_code=trust_remote_code).to(device).eval()
|
| 483 |
+
|
| 484 |
+
def _text(self, prompt):
|
| 485 |
+
return (self.tok.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
|
| 486 |
+
if self.chat else prompt)
|
| 487 |
+
|
| 488 |
+
def prepare(self, prompts, max_new_tokens):
|
| 489 |
+
"""Tokenize the complete selected run once, without truncating puzzle demos."""
|
| 490 |
+
texts = [self._text(p) for p in prompts]
|
| 491 |
+
missing = list(dict.fromkeys(t for t in texts if t not in self._encoded))
|
| 492 |
+
for off in range(0, len(missing), 256):
|
| 493 |
+
chunk = missing[off:off + 256]
|
| 494 |
+
# Preserve the former single-prompt tokenizer's special-token policy.
|
| 495 |
+
encoded = self.tok(chunk, add_special_tokens=True, padding=False,
|
| 496 |
+
truncation=False, return_attention_mask=False)
|
| 497 |
+
for i, text in enumerate(chunk):
|
| 498 |
+
item = {key: list(values[i]) for key, values in encoded.items()
|
| 499 |
+
if key in ("input_ids", "token_type_ids")}
|
| 500 |
+
if not item["input_ids"]:
|
| 501 |
+
raise ValueError("Tokenizer produced an empty prompt")
|
| 502 |
+
self._encoded[text] = item
|
| 503 |
+
if not self.quiet:
|
| 504 |
+
print(f"MARC pretokenized {min(off + 256, len(missing))}/{len(missing)} unique prompts",
|
| 505 |
+
file=sys.stderr, flush=True)
|
| 506 |
+
limits = [v for v in (self.max_model_len,
|
| 507 |
+
getattr(self.model.config, "max_position_embeddings", None),
|
| 508 |
+
getattr(self.tok, "model_max_length", None))
|
| 509 |
+
if isinstance(v, int) and 0 < v < 1_000_000_000]
|
| 510 |
+
limit = min(limits) if limits else None
|
| 511 |
+
for text in texts:
|
| 512 |
+
length = len(self._encoded[text]["input_ids"])
|
| 513 |
+
if limit and length + max_new_tokens > limit:
|
| 514 |
+
raise ValueError(f"Prompt ({length}) + output budget ({max_new_tokens}) "
|
| 515 |
+
f"exceeds context {limit}; puzzle prompts are never truncated")
|
| 516 |
+
return [self._encoded[t] for t in texts]
|
| 517 |
|
| 518 |
def generate(self, prompts, n, temperature, max_new_tokens):
|
| 519 |
+
import inspect
|
| 520 |
+
if n < 1 or max_new_tokens < 1 or temperature < 0:
|
| 521 |
+
raise ValueError("Invalid generation settings")
|
| 522 |
+
if n > 1 and temperature == 0:
|
| 523 |
+
raise ValueError("HF --n-samples > 1 requires --temperature > 0")
|
| 524 |
+
if not prompts:
|
| 525 |
+
return []
|
| 526 |
+
encoded = self.prepare(prompts, max_new_tokens)
|
| 527 |
+
order = sorted(range(len(prompts)), key=lambda i: len(encoded[i]["input_ids"]))
|
| 528 |
+
results = [None] * len(prompts)
|
| 529 |
+
eos = self.model.generation_config.eos_token_id
|
| 530 |
+
if eos is None:
|
| 531 |
+
eos = self.tok.eos_token_id
|
| 532 |
+
eos = set(eos if isinstance(eos, (list, tuple)) else [] if eos is None else [eos])
|
| 533 |
+
extra = {}
|
| 534 |
+
parameters = inspect.signature(self.model.forward).parameters
|
| 535 |
+
for key in ("logits_to_keep", "num_logits_to_keep"):
|
| 536 |
+
if key in parameters:
|
| 537 |
+
extra[key] = 1
|
| 538 |
+
break
|
| 539 |
|
| 540 |
+
def infer(indices, progress, tokens_done):
|
| 541 |
+
width = max(len(encoded[i]["input_ids"]) for i in indices)
|
| 542 |
+
data = {"input_ids": self.torch.full((len(indices), width), self.tok.pad_token_id,
|
| 543 |
+
dtype=self.torch.long),
|
| 544 |
+
"attention_mask": self.torch.zeros((len(indices), width), dtype=self.torch.long)}
|
| 545 |
+
if all("token_type_ids" in encoded[i] for i in indices):
|
| 546 |
+
data["token_type_ids"] = self.torch.zeros_like(data["input_ids"])
|
| 547 |
+
for row, i in enumerate(indices):
|
| 548 |
+
size = len(encoded[i]["input_ids"])
|
| 549 |
+
data["attention_mask"][row, -size:] = 1
|
| 550 |
+
for key in data.keys() - {"attention_mask"}:
|
| 551 |
+
data[key][row, -size:] = self.torch.tensor(encoded[i][key], dtype=self.torch.long)
|
| 552 |
+
data = {k: v.to(self.device) for k, v in data.items()}
|
| 553 |
+
progress.update(stage=f"prefill batch={len(indices)} width={width}")
|
| 554 |
+
stream = _TokenProgress(progress, len(indices) * n, eos, tokens_done)
|
| 555 |
+
kwargs = dict(max_new_tokens=max_new_tokens, do_sample=temperature > 0,
|
| 556 |
+
num_beams=1, num_return_sequences=n, use_cache=True,
|
| 557 |
+
pad_token_id=self.tok.pad_token_id, streamer=stream,
|
| 558 |
+
return_dict_in_generate=False, output_scores=False, **extra)
|
| 559 |
+
if temperature > 0:
|
| 560 |
+
kwargs["temperature"] = temperature
|
| 561 |
+
out = self.model.generate(**data, **kwargs)
|
| 562 |
+
sequences = out[:, width:].tolist()
|
| 563 |
+
# Preserve EOS and <think> spellings as before; remove only batch padding
|
| 564 |
+
# after the first EOS so batching does not change the parser's input.
|
| 565 |
+
sequences = [s[:next((i + 1 for i, t in enumerate(s) if t in eos), len(s))]
|
| 566 |
+
for s in sequences]
|
| 567 |
+
decoded = self.tok.batch_decode(sequences, skip_special_tokens=False)
|
| 568 |
+
if len(decoded) != len(indices) * n:
|
| 569 |
+
raise RuntimeError("HF returned an unexpected number of sequences")
|
| 570 |
+
return [decoded[i:i + n] for i in range(0, len(decoded), n)], sum(map(len, sequences))
|
| 571 |
+
|
| 572 |
+
offset = tokens_done = 0
|
| 573 |
+
batch_size = self.batch_size
|
| 574 |
+
with self.torch.inference_mode(), _Progress(len(prompts), self.quiet, self.progress_interval) as progress:
|
| 575 |
+
while offset < len(order):
|
| 576 |
+
indices = order[offset:offset + batch_size]
|
| 577 |
+
try:
|
| 578 |
+
answers, count = infer(indices, progress, tokens_done)
|
| 579 |
+
except self.torch.cuda.OutOfMemoryError:
|
| 580 |
+
if len(indices) == 1:
|
| 581 |
+
raise
|
| 582 |
+
batch_size = max(1, len(indices) // 2)
|
| 583 |
+
progress.update(stage=f"CUDA OOM; retry batch={batch_size}", tokens=tokens_done)
|
| 584 |
+
progress.show()
|
| 585 |
+
else:
|
| 586 |
+
for index, samples in zip(indices, answers):
|
| 587 |
+
results[index] = samples
|
| 588 |
+
offset += len(indices)
|
| 589 |
+
tokens_done += count
|
| 590 |
+
progress.update(stage="batch complete", done=offset, tokens=tokens_done)
|
| 591 |
+
progress.show()
|
| 592 |
+
continue
|
| 593 |
+
# Drop failed-call traceback tensors before clearing CUDA allocations.
|
| 594 |
+
gc.collect()
|
| 595 |
+
if self.torch.cuda.is_available():
|
| 596 |
+
self.torch.cuda.empty_cache()
|
| 597 |
+
return results
|
| 598 |
|
| 599 |
class OpenAIModel:
|
| 600 |
def __init__(self, model: str, base_url: str, chat: bool, api_key: str = "EMPTY"):
|
|
|
|
| 632 |
|
| 633 |
def run(model, chat, families, difficulties, n_per_cell, n_samples,
|
| 634 |
temperature, max_new_tokens, seed, verbose=True):
|
| 635 |
+
if n_per_cell < 1 or n_samples < 1 or max_new_tokens < 1 or temperature < 0:
|
| 636 |
+
raise ValueError("Counts/budgets must be positive and temperature nonnegative")
|
| 637 |
rows, t0 = [], time.time()
|
| 638 |
+
tasks = [generate_task(fam, diff, f"{seed}:{fam}:{diff}:{k}")
|
| 639 |
+
for diff in difficulties for fam in families for k in range(n_per_cell)]
|
| 640 |
+
prompts = [prompt_for(task, chat) for task in tasks]
|
| 641 |
+
# HFModel pretokenizes and length-buckets the entire run. Other adapters keep
|
| 642 |
+
# their existing generate API (including OpenAI's sequential request behavior).
|
| 643 |
+
predictions = model.generate(prompts, n_samples, temperature, max_new_tokens)
|
| 644 |
+
if len(predictions) != len(tasks) or any(len(s) != n_samples for s in predictions):
|
| 645 |
+
raise RuntimeError("Model returned an unexpected number of predictions")
|
| 646 |
+
offset = 0
|
| 647 |
for diff in difficulties:
|
| 648 |
for fam in families:
|
| 649 |
acc = {"em": 0.0, "format": 0.0, "pass": 0.0}
|
| 650 |
+
for task, samples in zip(tasks[offset:offset + n_per_cell], predictions[offset:offset + n_per_cell]):
|
| 651 |
+
for metric, value in _score(samples, task.query_out).items():
|
| 652 |
+
acc[metric] += value
|
| 653 |
+
offset += n_per_cell
|
|
|
|
|
|
|
| 654 |
cell = {m: acc[m] / n_per_cell for m in acc}
|
| 655 |
cell.update({"family": fam, "difficulty": diff})
|
| 656 |
rows.append(cell)
|
|
|
|
| 680 |
specs.append((f"hf:{name}",
|
| 681 |
lambda n=name: HFModel(
|
| 682 |
n, chat=args.chat, device=args.device,
|
| 683 |
+
trust_remote_code=args.trust_remote_code, batch_size=args.batch_size,
|
| 684 |
+
max_model_len=args.max_model_len, dtype=args.dtype,
|
| 685 |
+
quiet=args.quiet, progress_interval=args.progress_interval)))
|
| 686 |
|
| 687 |
if args.openai:
|
| 688 |
if not args.base_url:
|
|
|
|
| 722 |
all_results[label] = run(
|
| 723 |
model, args.chat, args.families, args.difficulties,
|
| 724 |
args.n_per_cell, args.n_samples, args.temperature,
|
| 725 |
+
args.max_new_tokens, args.seed, verbose=not args.quiet)
|
| 726 |
finally:
|
| 727 |
del model
|
| 728 |
gc.collect()
|
|
|
|
| 848 |
ap.add_argument("--temperature", type=float, default=0.0)
|
| 849 |
ap.add_argument("--max-new-tokens", type=int, default=200)
|
| 850 |
ap.add_argument("--seed", default="0")
|
| 851 |
+
ap.add_argument("--batch-size", type=int, default=32,
|
| 852 |
+
help="HF generation batch size; CUDA OOM retries smaller batches")
|
| 853 |
+
ap.add_argument("--max-model-len", type=int, default=None,
|
| 854 |
+
help="Optional context cap; prompts are never silently truncated")
|
| 855 |
+
ap.add_argument("--dtype", choices=["auto", "float32", "float16", "bfloat16"], default="auto",
|
| 856 |
+
help="HF precision; auto uses BF16 on CUDA, FP32 elsewhere")
|
| 857 |
+
ap.add_argument("--progress-interval", type=float, default=5.0,
|
| 858 |
+
help="Seconds between HF progress heartbeats")
|
| 859 |
+
ap.add_argument("--quiet", action="store_true", help="Suppress per-batch progress and per-cell scores")
|
| 860 |
args = ap.parse_args()
|
| 861 |
+
if min(args.batch_size, args.n_per_cell, args.n_samples, args.max_new_tokens) < 1:
|
| 862 |
+
ap.error("batch-size, n-per-cell, n-samples and max-new-tokens must be positive")
|
| 863 |
+
if args.temperature < 0 or args.progress_interval <= 0 or (args.max_model_len is not None and args.max_model_len < 1):
|
| 864 |
+
ap.error("temperature must be nonnegative; context and progress interval must be positive")
|
| 865 |
+
if args.hf and args.n_samples > 1 and args.temperature == 0:
|
| 866 |
+
ap.error("HF --n-samples > 1 requires --temperature > 0")
|
| 867 |
|
| 868 |
if args.selftest:
|
| 869 |
_self_test()
|
|
|
|
| 877 |
|
| 878 |
|
| 879 |
if __name__ == "__main__":
|
| 880 |
+
main()
|