tdprm-results / code /v2 /tdprm /sampling /generate.py
JoshuaW1997's picture
Super-squash branch 'main' using huggingface_hub
575b0ec
Raw History Blame Contribute Delete
2.2 kB
"""vLLM generation shared by base sampling and evaluation (identical prompts to training)."""
import gzip
import json
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from ..data.prepare import messages
from ..data.verify import verify
CHAT_KWARGS = {"date_string": "26 Jul 2024"} # same as data.apply_chat_template_kwargs in training
def render_prompt_ids(tokenizer, record):
text = tokenizer.apply_chat_template(messages(record), add_generation_prompt=True, tokenize=False, **CHAT_KWARGS)
return tokenizer.encode(text, add_special_tokens=False)
def load_llm(model_path, max_model_len, gpu_memory_utilization=0.9, tensor_parallel_size=1, seed=0):
from vllm import LLM
return LLM(model=model_path, dtype="bfloat16", max_model_len=max_model_len, seed=seed,
gpu_memory_utilization=gpu_memory_utilization, tensor_parallel_size=tensor_parallel_size,
enable_prefix_caching=True)
def generate(llm, prompt_ids, n, temperature, top_p, max_tokens, seed):
from vllm import SamplingParams
params = [SamplingParams(n=n, temperature=temperature, top_p=top_p, max_tokens=max_tokens,
seed=None if temperature == 0 else seed + i) for i in range(len(prompt_ids))]
outs = llm.generate([{"prompt_token_ids": ids} for ids in prompt_ids], sampling_params=params, use_tqdm=True)
return [[(list(o.token_ids), o.text, o.finish_reason) for o in out.outputs] for out in outs]
def _verify_one(args):
source, text, gold = args
return verify(source, text, gold)
def verify_all(sources, texts, golds, workers=32):
with ProcessPoolExecutor(max_workers=workers) as pool:
return list(pool.map(_verify_one, zip(sources, texts, golds), chunksize=64))
def write_jsonl_gz(path, rows):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
with gzip.open(tmp, "wt") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
tmp.replace(path)
def read_jsonl_gz(path):
with gzip.open(path, "rt") as f:
return [json.loads(line) for line in f if line.strip()]