JuliaKreutzerCohere commited on
Commit
b3f3da1
·
verified ·
1 Parent(s): 717d7e4

Upload script.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. script.py +52 -49
script.py CHANGED
@@ -40,11 +40,12 @@ from transformers import AutoTokenizer, AutoModelForCausalLM
40
  os.environ["HF_HUB_OFFLINE"] = "1"
41
  os.environ["TRANSFORMERS_OFFLINE"] = "1"
42
  MODEL_ID = "."
43
- MAX_NEW_TOKENS = 2000
 
44
  TEMPERATURE = 0.8
45
  TOP_P = 0.95
46
- NUM_SAMPLES = 5 # independent rollouts per problem
47
- MAX_ATTEMPTS = 2 # parse-retries per sample; ensemble covers the rest
48
 
49
 
50
  def load_tokenizer(model_id: str = "."):
@@ -357,7 +358,7 @@ def generate_explanation(
357
  with torch.no_grad():
358
  out = model.generate(
359
  ids,
360
- max_new_tokens=MAX_NEW_TOKENS,
361
  do_sample=False,
362
  )
363
  return tok.decode(out[0][ids.shape[-1] :], skip_special_tokens=True).strip()
@@ -371,52 +372,54 @@ model = AutoModelForCausalLM.from_pretrained(
371
  with open("/tmp/data/test.csv", encoding="utf-8", newline="") as f:
372
  test_rows = list(csv.DictReader(f))
373
 
374
- rows = []
375
- for idx, r in enumerate(test_rows, start=1):
376
- messages = [
377
- {"role": "system", "content": SYSTEM},
378
- {
379
- "role": "user",
380
- "content": (
381
- f"CONTEXT:{r['context'].strip()}\n"
382
- f"TASK TYPE:`{r['task_type']}`\n\n"
383
- f"QUERY:{r['query'].strip()}"
384
- ),
385
- },
386
- ]
387
- ids = tok.apply_chat_template(
388
- messages, add_generation_prompt=True, return_tensors="pt",
389
- ).to(model.device)
390
-
391
- print(f"{idx}/{len(test_rows)} sampling {NUM_SAMPLES}x", flush=True)
392
- raw_texts: list[str] = []
393
- rollouts: list[list[str]] = []
394
- for s in range(1, NUM_SAMPLES + 1):
395
- text = generate_sample(tok, model, ids)
396
- answers = postprocess_answer(text, r["query"], r["task_type"])
397
- raw_texts.append(text)
398
- rollouts.append(answers)
399
- print(f" sample {s}/{NUM_SAMPLES} parsed={answers!r}", flush=True)
400
-
401
- expected = expected_answer_count(r["query"], r["task_type"])
402
- voted = majority_vote(rollouts, expected, r["task_type"])
403
- source_i = select_source_sample(rollouts, voted, r["task_type"])
404
- print(f" vote -> {voted!r} (explain from sample {source_i + 1})", flush=True)
405
-
406
- explanation = generate_explanation(
407
- tok, model, r["context"], r["task_type"], r["query"], raw_texts[source_i],
408
- )
409
-
410
- rows.append(
411
- {
412
- "id": r["id"],
413
- "pred": json.dumps(voted, ensure_ascii=False),
414
- "explanation": explanation,
415
- }
416
- )
417
-
418
  with open("submission.csv", "w", encoding="utf-8", newline="") as f:
419
  writer = csv.DictWriter(f, fieldnames=["id", "pred", "explanation"])
420
  writer.writeheader()
421
- writer.writerows(rows)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
  print("wrote submission.csv", flush=True)
 
40
  os.environ["HF_HUB_OFFLINE"] = "1"
41
  os.environ["TRANSFORMERS_OFFLINE"] = "1"
42
  MODEL_ID = "."
43
+ MAX_NEW_TOKENS = 1200 # was 2000; cut to fit T4 wall clock
44
+ MAX_NEW_TOKENS_EXPLAIN = 600
45
  TEMPERATURE = 0.8
46
  TOP_P = 0.95
47
+ NUM_SAMPLES = 3 # independent rollouts per problem (was 5; timeout)
48
+ MAX_ATTEMPTS = 1 # no per-sample retry; majority vote absorbs misses
49
 
50
 
51
  def load_tokenizer(model_id: str = "."):
 
358
  with torch.no_grad():
359
  out = model.generate(
360
  ids,
361
+ max_new_tokens=MAX_NEW_TOKENS_EXPLAIN,
362
  do_sample=False,
363
  )
364
  return tok.decode(out[0][ids.shape[-1] :], skip_special_tokens=True).strip()
 
372
  with open("/tmp/data/test.csv", encoding="utf-8", newline="") as f:
373
  test_rows = list(csv.DictReader(f))
374
 
375
+ # Write incrementally so a wall-clock kill still leaves a partial submission.csv.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  with open("submission.csv", "w", encoding="utf-8", newline="") as f:
377
  writer = csv.DictWriter(f, fieldnames=["id", "pred", "explanation"])
378
  writer.writeheader()
379
+ f.flush()
380
+
381
+ for idx, r in enumerate(test_rows, start=1):
382
+ messages = [
383
+ {"role": "system", "content": SYSTEM},
384
+ {
385
+ "role": "user",
386
+ "content": (
387
+ f"CONTEXT:{r['context'].strip()}\n"
388
+ f"TASK TYPE:`{r['task_type']}`\n\n"
389
+ f"QUERY:{r['query'].strip()}"
390
+ ),
391
+ },
392
+ ]
393
+ ids = tok.apply_chat_template(
394
+ messages, add_generation_prompt=True, return_tensors="pt",
395
+ ).to(model.device)
396
+
397
+ print(f"{idx}/{len(test_rows)} sampling {NUM_SAMPLES}x", flush=True)
398
+ raw_texts: list[str] = []
399
+ rollouts: list[list[str]] = []
400
+ for s in range(1, NUM_SAMPLES + 1):
401
+ text = generate_sample(tok, model, ids)
402
+ answers = postprocess_answer(text, r["query"], r["task_type"])
403
+ raw_texts.append(text)
404
+ rollouts.append(answers)
405
+ print(f" sample {s}/{NUM_SAMPLES} parsed={answers!r}", flush=True)
406
+
407
+ expected = expected_answer_count(r["query"], r["task_type"])
408
+ voted = majority_vote(rollouts, expected, r["task_type"])
409
+ source_i = select_source_sample(rollouts, voted, r["task_type"])
410
+ print(f" vote -> {voted!r} (explain from sample {source_i + 1})", flush=True)
411
+
412
+ explanation = generate_explanation(
413
+ tok, model, r["context"], r["task_type"], r["query"], raw_texts[source_i],
414
+ )
415
+
416
+ writer.writerow(
417
+ {
418
+ "id": r["id"],
419
+ "pred": json.dumps(voted, ensure_ascii=False),
420
+ "explanation": explanation,
421
+ }
422
+ )
423
+ f.flush()
424
+
425
  print("wrote submission.csv", flush=True)