Add glm-4.7-flash/stories-v0
Browse filesFiles changed (7)
- glm-4.7-flash/stories-v0/README.mdAdded+24
- glm-4.7-flash/stories-v0/hf_stories.pyAdded+87
- glm-4.7-flash/stories-v0/serve.shAdded+77
- glm-4.7-flash/stories-v0/stories.jsonlAdded
- glm-4.7-flash/stories-v0/story_job.shAdded+98
- glm-4.7-flash/stories-v0/strip_marks.pyAdded+33
- glm-4.7-flash/stories-v0/write_answers.pyAdded+224
123456789101112131415161718192021222324# GLM-4.7-Flash on the story benchmark of Lech Mazur, 2 stories for each prompt`zai-org/GLM-4.7-Flash` on 120 prompts of the [story benchmark of Lech Mazur](https://github.com/lechmazur/writing), 2 stories for each prompt. A prompt asks for a story of 600 to 800 words that uses 10 given elements. It also asks for the cumulative word count in square brackets after each sentence. There are no tool calls. Two jobs on DeltaAI did the work on Oct 10 and Oct 11, 2026, with commit `5bf1798` of the team repo:- Job 3357246 (node gh152, one GH200 for this model), 21 min: a test in an interactive session, the first stories.- Job 3362123 (node gh128, one GH200), 23 min: the other stories.The server had 23 calls at one time. The other three teachers wrote the same prompts: `qwen3.8-27b/stories-v0/`, `gemma-4-26b-a4b/stories-v0/`, `muse-glimmer-30b/stories-v0/` in this dataset.First run, no baseline. Training link unknown.| File | Prompts | Stories | Cut at the token limit | Tokens of a story, median | Tokens, largest | Words of a story, median | Stories with 600 to 800 words ||---|---|---|---|---|---|---|---|| `stories.jsonl` | 120 | 240 | 2 | 5,893 | 32,768 | 579 | 67 |The tokens of a story are the thinking and the story together. The words are the text in the story tags with the word counts removed.## Known problemsThis run:- One call has a limit of 32,768 tokens for the thinking and the story together. The limit cut 2 of the 240 stories (`finish` is `length`).- 1 story has fewer than 100 words of final text.- In 56 answers, the story tags are not complete. Such an answer can hold notes of the model on its word count.- 173 of the 240 stories are not in the range of 600 to 800 words. We keep each story. The maker of the benchmark draws such a story again.Each model of this run:- No story has a grade. We did not do the grading step of the benchmark.- A request has the model, the prompt and the token limit, and no sampling value. Thinking is on. The maker of the benchmark gives no token limit, no temperature and no thinking setting.- The prompts are not in this folder, because the repo of the maker has no license file. `task` is the number of the prompt file in that repo: `prompt_wc_<task>.txt`, with 600 and 800 as its word limits.## Files- `stories.jsonl`: one line for each story with `model`, `lab`, `task`, `trial` (0 or 1), `text` (the final answer), `thinking`, `tokens_out`, `finish` and `seconds`.- `write_answers.py`, `story_job.sh` and `serve.sh`: the client, the batch job and the start of the server.- `hf_stories.py` and `strip_marks.py`: the scripts that made this folder.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""One teacher's stories for the team dataset: stories.jsonl (each story one time) and README.md. Standard library only.
python hf_stories.py TAG ROWS.jsonl OUT_FOLDER TAG is qwen, gemma, muse or glm"""import jsonimport osimport reimport statisticsimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # python -I leaves the folder of the script outimport strip_marks # noqa: E402
M = { "qwen": dict(name="Qwen3.8-27B", mid="Qwen/Qwen3.8-27B", dest="qwen3.8-27b", calls=24, job="Job 3362121 (node gh106, one GH200), 58 min"), "gemma": dict(name="Gemma 4 26B A4B", mid="google/gemma-4-26B-A4B-it", dest="gemma-4-26b-a4b", calls=51, job="Job 3362122 (node gh128, one GH200), 36 min"), "muse": dict(name="Muse Glimmer 30B", mid="meta-models/Muse-Glimmer-30B", dest="muse-glimmer-30b", calls=60, job="Job 3362124 (node gh128, one GH200), 9 min"), "glm": dict(name="GLM-4.7-Flash", mid="zai-org/GLM-4.7-Flash", dest="glm-4.7-flash", calls=23, job="Job 3362123 (node gh128, one GH200), 23 min"),}STORY = re.compile(r"<story>(.*?)</story>", re.S)
def merge(rows): """Each (task, trial) one time. A story that the token limit did not cut replaces a cut one.""" best = {} for r in rows: key = (str(r["task"]), r["trial"]) if key not in best or (best[key].get("finish") == "length" and r.get("finish") != "length"): best[key] = r return [best[k] for k in sorted(best, key=lambda k: (int(k[0]), k[1]))]
def words(text): """The words of the story with no word-count marks. The text in the story tags, or all the text when the tags are not complete.""" blocks = STORY.findall(text) body = blocks[-1] if blocks else re.sub(r"</?story>", "", text) return len(strip_marks.strip(body).split())
def main(argv=None): tag, src, out = (sys.argv[1:] if argv is None else argv)[:3] m = M[tag] rows = merge([json.loads(line) for line in open(src, encoding="utf-8")]) os.makedirs(out, exist_ok=True) with open(os.path.join(out, "stories.jsonl"), "w", encoding="utf-8") as f: f.writelines(json.dumps(r) + "\n" for r in rows) w = [words(r["text"] or "") for r in rows] tokens = [r["tokens_out"] for r in rows if r.get("tokens_out")] cut = sum(r.get("finish") == "length" for r in rows) short = sum(len((r["text"] or "").split()) < 100 for r in rows) no_tags = sum(not STORY.search(r["text"] or "") for r in rows) in_range = sum(600 <= x <= 800 for x in w) others = ", ".join("`%s/stories-v0/`" % M[t]["dest"] for t in M if t != tag) L = ["# %s on the story benchmark of Lech Mazur, 2 stories for each prompt" % m["name"], "`%s` on 120 prompts of the [story benchmark of Lech Mazur](https://github.com/lechmazur/writing), 2 stories for each prompt. A prompt asks for a story of 600 to 800 words that uses 10 given elements. It also asks for the cumulative word count in square brackets after each sentence. There are no tool calls. Two jobs on DeltaAI did the work on Oct 10 and Oct 11, 2026, with commit `5bf1798` of the team repo:" % m["mid"], "- Job 3357246 (node gh152, one GH200 for this model), 21 min: a test in an interactive session, the first stories.", "- %s: the other stories." % m["job"], "The server had %d calls at one time. The other three teachers wrote the same prompts: %s in this dataset." % (m["calls"], others), "First run, no baseline. Training link unknown.", "| File | Prompts | Stories | Cut at the token limit | Tokens of a story, median | Tokens, largest | Words of a story, median | Stories with 600 to 800 words |", "|---|---|---|---|---|---|---|---|", "| `stories.jsonl` | 120 | %d | %d | %s | %s | %d | %d |" % (len(rows), cut, format(int(statistics.median(tokens)), ","), format(max(tokens), ","), statistics.median(w), in_range), "The tokens of a story are the thinking and the story together. The words are the text in the story tags with the word counts removed.", "## Known problems", "This run:"] L.append("- One call has a limit of 32,768 tokens for the thinking and the story together. The limit cut %d of the %d stories (`finish` is `length`)." % (cut, len(rows))) if short: L.append("- %d stor%s fewer than 100 words of final text." % (short, "y has" if short == 1 else "ies have")) if no_tags: L.append("- In %d answers, the story tags are not complete. Such an answer can hold notes of the model on its word count." % no_tags) if in_range < len(rows): L.append("- %d of the %d stories are not in the range of 600 to 800 words. We keep each story. The maker of the benchmark draws such a story again." % (len(rows) - in_range, len(rows))) L += ["Each model of this run:", "- No story has a grade. We did not do the grading step of the benchmark.", "- A request has the model, the prompt and the token limit, and no sampling value. Thinking is on. The maker of the benchmark gives no token limit, no temperature and no thinking setting.", "- The prompts are not in this folder, because the repo of the maker has no license file. `task` is the number of the prompt file in that repo: `prompt_wc_<task>.txt`, with 600 and 800 as its word limits.", "## Files", "- `stories.jsonl`: one line for each story with `model`, `lab`, `task`, `trial` (0 or 1), `text` (the final answer), `thinking`, `tokens_out`, `finish` and `seconds`.", "- `write_answers.py`, `story_job.sh` and `serve.sh`: the client, the batch job and the start of the server.", "- `hf_stories.py` and `strip_marks.py`: the scripts that made this folder."] open(os.path.join(out, "README.md"), "w", encoding="utf-8").write("\n".join(L) + "\n") print("%s: stories %d, cut %d, below 100 words %d, tags not complete %d, words median %d, in the range %d" % ( tag, len(rows), cut, short, no_tags, statistics.median(w), in_range))
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#!/bin/bash# MODEL_ID picks the weights and the model's own vLLM flags. Default: Qwen/Qwen3.8-27B, the Oct 1 settings.# MAX_MODEL_LEN overrides Qwen's context window.# KV_OFFLOAD_GIB: CPU memory, in GiB, that holds context the GPU cache had to drop (default 32, 0 turns it off).# PORT defaults to 8000. batch.sh gives each job its own free ports. The GPU is whatever CUDA_VISIBLE_DEVICES allows.# STUDENT_PATH: the folder of a student, a fine-tuned copy of a starting model. The MODEL_ID of a student is the name of# its starting model, a `+` and a tag: ibm-granite/granite-4.2-8b+qwen38. It gets the flags of its starting model.set -eHERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)ENV=/work/nvme/bfvr/msalunkhe/envs/vllm-latestsource $ENV/bin/activateW=/work/nvme/bfvr/$USER/serve-cachemkdir -p $Wexport HF_HUB_OFFLINE=1 HF_HOME=$W/hf VLLM_CACHE_ROOT=$W/vllm TRITON_CACHE_DIR=$W/triton XDG_CACHE_HOME=$W/xdg FLASHINFER_WORKSPACE_BASE=$W/flashinferMODEL_ID=${MODEL_ID:-Qwen/Qwen3.8-27B}M=/work/nvme/bfvr/msalunkhe/modelsSEQS=64case $MODEL_ID in Qwen/Qwen3.8-27B) MODEL=$M/Qwen3.8-27B # 262144 is the full window in config.json and on the model card. The Oct 1 job ran at 131072. # qwen3_xml is the name in the vLLM recipe of the model. It loads the same class as qwen3_coder, the name until Oct 6. ARGS=(--max-model-len ${MAX_MODEL_LEN:-262144} --reasoning-parser qwen3 --tool-call-parser qwen3_xml) ;; google/gemma-4-26B-A4B-it) # 262144 is the full window in config.json. Gemma's template leaves thinking off unless asked, Qwen's has it on. # The template keeps the thinking between the tool calls of the current turn without an option, as Google asks. # Until Oct 6 this line also set preserve_thinking, which keeps the thinking of earlier turns too. The vLLM # recipe of the model does not set it, and Google's page says that no thinking of a previous turn stays. MODEL=$M/gemma-4-26B-A4B-it ARGS=(--max-model-len 262144 --reasoning-parser gemma4 --tool-call-parser gemma4 --default-chat-template-kwargs '{"enable_thinking": true}') ;; meta-models/Muse-Glimmer-30B) # 131072 is the full window in config.json. Its template sets "Reasoning strength: high" unless a request asks otherwise. # muse_glimmer_typed (muse_typed_parser.py, since Oct 6) is vLLM's muse_glimmer parser with each argument typed # by the tool's schema, as vLLM types Qwen's. The plain parser sent the product id 9523456873 as a number. MODEL=$M/Muse-Glimmer-30B ARGS=(--max-model-len 131072 --reasoning-parser muse_glimmer --tool-parser-plugin "$HERE/muse_typed_parser.py" --tool-call-parser muse_glimmer_typed) ;; zai-org/GLM-4.7-Flash) # 202752 is the full window in config.json. glm45 and glm47 are the parser names on the model card. # glm47_open (glm_open_parser.py, since Oct 9) is vLLM's glm47 parser that also keeps a tool call whose name is # not in the tools of the request. The plain parser dropped such a call. The reply then had no content and no # tool call, and tau2 threw the conversation away. The parsers of the other three models send the call on. # clear_thinking false keeps the thinking of earlier turns, as Z.ai asks for agent tasks ("Preserved Thinking"). # generation_config.json has temperature 1.0 only, so the top-p of the card, 0.95, is set here. A request that # sends its own top-p keeps it. # The card's command also turns on MTP, a draft head for speed. It is off for the first run: the GPU cache is small. MODEL=$M/GLM-4.7-Flash ARGS=(--max-model-len 202752 --reasoning-parser glm45 --tool-parser-plugin "$HERE/glm_open_parser.py" --tool-call-parser glm47_open --default-chat-template-kwargs '{"enable_thinking": true, "clear_thinking": false}' --override-generation-config '{"top_p": 0.95}') ;; ibm-granite/granite-4.2-8b|ibm-granite/granite-4.2-8b+*) # Granite 4.2 8B, the starting model, and each student of it: only the weights and the served name change (rule 8). # The flags are those of the model card and of track A's test of Oct 8 (A-build/runs/start-model-test/README.md): # bf16, 131072 (the full window in config.json) and 16 sequences at most, so more calls wait in the server. # granite_thinking_parser is a file in the folder of the released model, and a student uses that same file. # qwen3_coder is the tool parser on the model card. # generation_config.json has temperature 1.0 and top-p 0.95, the values of the model card for each task. # The template has thinking on. It removes the thinking of each turn before the last user message. # A student uses the generation_config.json and the template in its own folder. No check here compares them. MODEL=$M/granite-4.2-8b if [ "$MODEL_ID" != ibm-granite/granite-4.2-8b ]; then [ -n "${STUDENT_PATH:-}" ] || { echo "serve.sh: $MODEL_ID is a student, and STUDENT_PATH has no folder"; exit 2; } MODEL=$STUDENT_PATH fi SEQS=16 ARGS=(--dtype bfloat16 --max-model-len 131072 --reasoning-parser granite_thinking_parser --reasoning-parser-plugin $M/granite-4.2-8b/granite_thinking_parser.py --tool-call-parser qwen3_coder) ;; *) echo "serve.sh: no settings for MODEL_ID=$MODEL_ID"; exit 2 ;;esacecho "node $(hostname) vllm $(python -c "import vllm;print(vllm.__version__)" 2>/dev/null) model $MODEL_ID"KV_OFFLOAD_GIB=${KV_OFFLOAD_GIB:-32}[ "$KV_OFFLOAD_GIB" = 0 ] || ARGS+=(--kv-offloading-size "$KV_OFFLOAD_GIB" --kv-offloading-backend native)exec vllm serve $MODEL --served-model-name $MODEL_ID --host 0.0.0.0 --port ${PORT:-8000} \ --gpu-memory-utilization 0.90 --max-num-seqs $SEQS --language-model-only \ --enable-auto-tool-choice "${ARGS[@]}"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798#!/bin/bash#SBATCH --job-name=story-teacher#SBATCH --account=betw-dtai-gh#SBATCH --partition=ghx4#SBATCH --nodes=1#SBATCH --gpus=1#SBATCH --cpus-per-task=72#SBATCH --mem=110G#SBATCH --time=01:00:00#SBATCH --output=/work/nvme/bfvr/msalunkhe/distill/replacement-benchmarks/writing-test/logs/story-%j.log# One teacher writes SAMPLES stories for each prompt of the story benchmark. One server on one GPU.# CODE=<code copy of one commit> MODEL_ID=Qwen/Qwen3.8-27B LAB=Alibaba NAME=ours-qwen3.8-27b OUT=<folder of the teacher> \# PROMPTS=<prompts-stories.jsonl> PARALLEL=24 STOP_NEW_MIN=<minutes> \# sbatch --job-name=story-qwen --time=<limit> $CODE/lead/runs/replacement-benchmarks/writing-test/story_job.sh# 72 CPUs and 110G are the share of one GPU, so the job bills as one GPU.# Env: PARALLEL (calls at one time, default 24), SAMPLES (default 2), N_PROMPTS (the first lines of PROMPTS, default# each line), MAX_TOKENS (one call, the thinking and the story together, default 32768), GATE_CUT (default 12: the# teacher stops when the token limit cut more than half of its first 12 stories), STOP_NEW_MIN (no new call starts# after this many minutes of the job, and the calls in work end), STOP_FILE (no new call starts while this file is# there: story_test_session.sh makes one file for its four jobs), HARD_END_MIN (default 600: a call in work ends at# this minute with no answer. Set it 1 minute below the time limit), READY_LIMIT_S (default 900), GPU (default 0)# and PORT: story_test_session.sh starts four of these scripts in one allocation. SERVE: a fake server, for the dry run.# The job goes on from the rows of OUT: a story that ended is not written again. A story that the token limit cut is.# The rows are OUT/rows-stories-gpu0.jsonl, the name that score.sh reads.# Exit 0: each story is there, or the stop file or the end time came. 1: no new story. 2: the server did not start,# or the smoke call failed. 3: a gate of write_answers.py. 5: the server did not answer.# The server stops with TERM, then KILL after 20 s (GPU rule 11).set -uo pipefail: "${CODE:?}" "${MODEL_ID:?}" "${LAB:?}" "${NAME:?}" "${OUT:?}" "${PROMPTS:?}"W=$CODE/lead/runs/replacement-benchmarks/writing-testPY=${PY:-/work/nvme/bfvr/msalunkhe/envs/vllm-latest/bin/python}SERVE=${SERVE:-$CODE/lead/runs/qwen38-five/serve.sh}PARALLEL=${PARALLEL:-24} SAMPLES=${SAMPLES:-2} MAX_TOKENS=${MAX_TOKENS:-32768} GATE_CUT=${GATE_CUT:-12}READY_LIMIT_S=${READY_LIMIT_S:-900} GPU=${GPU:-0}JOB=${SLURM_JOB_ID:-0}PORT=${PORT:-$(( 10000 + 2 * (JOB % 10000) ))} # a node holds more than one job, thus each job has its own portT0=$(date +%s)mkdir -p "$OUT/logs"STOP_FILE=${STOP_FILE:-$OUT/logs/stop-new-$JOB-$T0}ROWS=$OUT/rows-stories-gpu0.jsonlsay() { echo "[$(date '+%F %T')] $*" | tee -a "$OUT/logs/job.log"; }answers() { "$PY" -I "$W/write_answers.py" "$@"; }
LIST=$PROMPTS[ -z "${N_PROMPTS:-}" ] || { LIST=$OUT/logs/prompts-$JOB-$T0.jsonl; head -n "$N_PROMPTS" "$PROMPTS" > "$LIST"; }[ -s "$LIST" ] || { say "no prompt in $PROMPTS"; exit 2; }left() { answers --count --prompts "$LIST" --samples "$SAMPLES" --done "$OUT"/rows-stories-gpu*.jsonl; }N=$(left)[[ $N =~ ^[0-9]+$ ]] || { say "write_answers.py gave no count"; exit 2; }[ "$N" -gt 0 ] || { say "no story is left in $OUT: the job ends with no server"; exit 0; }say "job $JOB on $(hostname): $MODEL_ID, $PARALLEL calls at one time, $N stories to write of $(( SAMPLES * $(wc -l < "$LIST") )), limit $MAX_TOKENS tokens, code $CODE"
SERVER= CLIENT= TIMER=stop_group() { kill -TERM -- "-$1" 2>/dev/null; for _ in $(seq 1 20); do kill -0 -- "-$1" 2>/dev/null || return 0; sleep 1; done; kill -KILL -- "-$1" 2>/dev/null; }cleanup() { trap - EXIT TERM INT [ -z "$TIMER" ] || kill "$TIMER" 2>/dev/null [ -z "$CLIENT" ] || kill "$CLIENT" 2>/dev/null [ -z "$SERVER" ] || stop_group "$SERVER"}trap cleanup EXITtrap 'exit 143' TERM INT
up() { curl -sf -m 20 "http://127.0.0.1:$PORT/v1/models" 2>/dev/null | grep -q "\"$MODEL_ID\""; }! curl -s -m 3 "http://127.0.0.1:$PORT/v1/models" > /dev/null || { say "port $PORT has a server of a different job: the job stops"; exit 2; }CUDA_VISIBLE_DEVICES=$GPU PORT=$PORT MODEL_ID=$MODEL_ID setsid bash "$SERVE" > "$OUT/logs/serve-$JOB-gpu0.log" 2>&1 &SERVER=$!until up; do kill -0 "$SERVER" 2>/dev/null || { say "the server ended at its start: $OUT/logs/serve-$JOB-gpu0.log"; exit 2; } [ $(( $(date +%s) - T0 )) -lt "$READY_LIMIT_S" ] || { say "the server is not ready after $READY_LIMIT_S s"; exit 2; } sleep 3donesay "the server is ready $(( $(date +%s) - T0 )) s after the start of the job"timeout "${SMOKE_S:-300}" "$PY" -I "$W/write_answers.py" --base-url "http://127.0.0.1:$PORT/v1" --model "$MODEL_ID" --smoke >> "$OUT/logs/job.log" 2>&1 \ || { say "the smoke call failed: the SMOKE line is above"; exit 2; }
if [ -n "${STOP_NEW_MIN:-}" ]; then # the job makes its stop file at this minute ( while [ "$(date +%s)" -lt $(( T0 + 60 * STOP_NEW_MIN )) ]; do sleep 5; done; : > "$STOP_FILE" ) & TIMER=$!fiSINCE=0; [ ! -e "$ROWS" ] || SINCE=$(wc -l < "$ROWS")answers --base-url "http://127.0.0.1:$PORT/v1" --model "$MODEL_ID" --name "$NAME" --lab "$LAB" --prompts "$LIST" --out "$ROWS" \ --done "$OUT"/rows-stories-gpu*.jsonl --samples "$SAMPLES" --parallel "$PARALLEL" --max-tokens "$MAX_TOKENS" --gate-cut "$GATE_CUT" \ --end $(( T0 + 60 * ${HARD_END_MIN:-600} )) --stop-file "$STOP_FILE" >> "$OUT/logs/answers-$JOB.log" 2>&1 &CLIENT=$!say "the client started"
miss=0while kill -0 "$CLIENT" 2>/dev/null; do sleep "${POLL:-20}" kill -0 "$SERVER" 2>/dev/null && up && miss=0 || miss=$(( miss + 1 )) [ "$miss" -lt "${MISS_LIMIT:-8}" ] || { say "the server did not answer $miss times in sequence: the job stops"; exit 5; }donewait "$CLIENT"; rc=$?; CLIENT=say "the client ended with exit $rc, $(( $(date +%s) - T0 )) s after the start of the job: $(tail -n 1 "$OUT/logs/answers-$JOB.log" 2>/dev/null)"say "$("$PY" -I "$W/story_stats.py" "$ROWS" --since "$SINCE")"say "stories with no row: $(left)"exit "$rc"123456789101112131415161718192021222324252627282930313233"""The story rows with no word counts, so that the text test reads the prose only. Standard library only.
python strip_marks.py rows_text.jsonl OUT.jsonl
The prompt of the story benchmark asks for the cumulative word count in square brackets after each sentence, forexample "The wizard laughed. [413]". Each model writes these marks. This removes each "[number]"."""import jsonimport reimport sys
MARK = re.compile(r"[ \t]*\[\d[\d,]*\]")
def strip(text): return MARK.sub("", text)
def main(argv=None): src, out = (sys.argv[1:] if argv is None else argv)[:2] rows = marks = 0 with open(src, encoding="utf-8") as f, open(out, "w", encoding="utf-8") as g: for line in f: r = json.loads(line) marks += len(MARK.findall(r["text"])) rows += 1 r["text"] = strip(r["text"]) g.write(json.dumps(r) + "\n") print("rows %d, marks removed %d" % (rows, marks))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224"""Ask one model for written answers: each prompt SAMPLES times. Standard library only.
python write_answers.py --base-url http://127.0.0.1:8101/v1 --model Qwen/Qwen3.8-27B --name ours-qwen3.8-27b --lab Alibaba \ --prompts prompts-stories.jsonl --out rows.jsonl [--samples 2] [--parallel 24] [--max-tokens 12288] [--end EPOCH | --deadline-s 1200] [--stop-file FILE] [--claims FOLDER] [--done ROWS ...] [--gate 8] [--gate-cut 12] [--min-words 100] python write_answers.py --base-url URL --model ID --smoke one short call: exit 0 when the reply has text python write_answers.py --count --prompts P [--done ROWS ...] [--claims FOLDER] prints the answers that no client has
prompts: one line for each task: {"task", "prompt", "system": optional}.out: one line for each answer: {"model", "lab", "task", "trial", "text", "thinking", "finish", "tokens_out", "seconds"}.A request sends no sampling setting: the server has the settings of the maker of the model."text" is the final answer. "thinking" is the reasoning text, and no test reads it.The samples of one task go one after the other, so a stop at the end time leaves tasks that have each sample.A second start reads `out` and asks only for the answers that are not there. --done names more row files of the model, for example the rows of a session before. An answer that the token limit cut is not there: a second start asks for it again.--claims: a folder that two clients of one model share. A client makes one empty file for an answer before its call, and only one client can make it. Thus a second server of the model can help, and no answer is written two times.--stop-file: no new call starts while this file is there, and a call in work ends with its answer. A batch job makes the file some minutes before its time limit, and a test session makes it when each model has its answers.--gate: when the first GATE answers are there and none has MIN_WORDS words, the client stops with exit 3.--gate-cut: when the first GATE_CUT answers are there and the token limit cut more than half of them, the client stops with exit 3. In job 3355704 a limit of 12,288 tokens cut 21 of the first 25 stories of Gemma, and the calls went on.Exit 0: one answer or more, or nothing to do. Exit 1: no answer. Exit 3: the gate."""import argparseimport jsonimport osimport sysimport threadingimport timeimport urllib.errorimport urllib.parseimport urllib.requestfrom concurrent.futures import ThreadPoolExecutor, wait
ERRORS = (urllib.error.URLError, OSError, ValueError, KeyError, IndexError, TypeError)
def call(base, body, timeout): req = urllib.request.Request(base.rstrip("/") + "/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json"}) return json.load(urllib.request.urlopen(req, timeout=timeout))
def parse(reply): """(text, thinking, finish, tokens_out) of one chat reply. vLLM names the thinking `reasoning` or `reasoning_content`.""" choice = reply["choices"][0] msg = choice["message"] thinking = msg.get("reasoning") or msg.get("reasoning_content") or "" return msg.get("content") or "", thinking, choice.get("finish_reason"), (reply.get("usage") or {}).get("completion_tokens")
def todo(prompts, done, samples): """The (prompt, trial) pairs with no row, task by task in the sequence of the file.""" return [(p, k) for p in prompts for k in range(samples) if (str(p["task"]), k) not in done]
def read_done(paths): """The (task, trial) pairs with an answer that the token limit did not cut, in one file or more.""" done = set() for path in [paths] if isinstance(paths, str) else paths: try: for line in open(path, encoding="utf-8"): if line.strip(): r = json.loads(line) if r.get("finish") != "length": done.add((str(r["task"]), r["trial"])) except FileNotFoundError: pass return done
def claim(folder, task, trial): """True when this client gets the answer. With no folder, each answer is its own.""" if not folder: return True try: os.close(os.open(os.path.join(folder, "%s.%d" % (urllib.parse.quote(str(task), safe=""), trial)), os.O_CREAT | os.O_EXCL | os.O_WRONLY)) return True except FileExistsError: return False
def count_left(prompts, done, samples, claims=None): """The answers that are not in the rows and that no client has a claim for.""" claimed = set(os.listdir(claims)) if claims and os.path.isdir(claims) else set() return sum("%s.%d" % (urllib.parse.quote(str(p["task"]), safe=""), k) not in claimed for p, k in todo(prompts, done, samples))
def gate_fails(first_words, gate, min_words): """True when the first `gate` answers are there and none has min_words words.""" return gate > 0 and len(first_words) >= gate and max(first_words[:gate]) < min_words
def cut_gate_fails(first_cut, gate_cut): """True when the first `gate_cut` answers are there and the token limit cut more than half of them.""" return gate_cut > 0 and len(first_cut) >= gate_cut and 2 * sum(first_cut[:gate_cut]) > gate_cut
def run(a): prompts = [json.loads(line) for line in open(a.prompts, encoding="utf-8") if line.strip()] work = todo(prompts, read_done([a.out] + (a.done or [])), a.samples) end = a.end if a.end else time.time() + a.deadline_s lock, stop, first, first_cut = threading.Lock(), threading.Event(), [], [] count = {"ok": 0, "error": 0, "cut": 0, "late": 0, "other": 0, "short": 0, "held": 0} if a.claims: os.makedirs(a.claims, exist_ok=True) out = open(a.out, "a", encoding="utf-8")
def bump(key): with lock: count[key] += 1
def one(item): p, k = item if stop.is_set(): return if end - time.time() <= 1: return bump("late") if a.stop_file and os.path.exists(a.stop_file): return bump("held") if not claim(a.claims, p["task"], k): return bump("other") messages = ([{"role": "system", "content": p["system"]}] if p.get("system") else []) + [{"role": "user", "content": p["prompt"]}] body = {"model": a.model, "messages": messages, "max_tokens": a.max_tokens} for attempt in (0, 1): left = end - time.time() if left <= 1: return bump("late") t0 = time.time() try: text, thinking, finish, tokens = parse(call(a.base_url, body, left)) except ERRORS as e: if attempt == 0 and end - time.time() > 30 and not stop.is_set(): time.sleep(5) continue late = time.time() >= end - 1 if not late: print("ERROR task %s trial %d: %s" % (p["task"], k, str(e)[:200]), flush=True) return bump("late" if late else "error") row = {"model": a.name or a.model, "lab": a.lab, "task": str(p["task"]), "trial": k, "text": text, "thinking": thinking, "finish": finish, "tokens_out": tokens, "seconds": round(time.time() - t0, 1)} words = len(text.split()) with lock: out.write(json.dumps(row, ensure_ascii=False) + "\n") out.flush() count["ok"] += 1 count["cut"] += finish == "length" count["short"] += words < a.min_words first.append(words) first_cut.append(finish == "length") if gate_fails(first, a.gate, a.min_words) or cut_gate_fails(first_cut, a.gate_cut): stop.set() return
t0 = time.time() pool = ThreadPoolExecutor(max_workers=a.parallel) futures = [pool.submit(one, item) for item in work] while futures and not stop.is_set(): futures = list(wait(futures, timeout=0.5).not_done) pool.shutdown(wait=False, cancel_futures=True) label = "%s %s" % (a.name or a.model, os.path.basename(a.prompts)) if stop.is_set(): if cut_gate_fails(first_cut, a.gate_cut): print("STOP %s: the token limit of %d cut %d of the first %d answers" % (label, a.max_tokens, sum(first_cut[:a.gate_cut]), a.gate_cut), flush=True) else: print("STOP %s: the first %d answers have no text of %d words: %s" % (label, a.gate, a.min_words, first[:a.gate]), flush=True) return 3 print("DONE %s: %d answers of %d asked, %d below %d words, %d cut at the token limit, %d errors, %d not done at the end time, " "%d not started for the stop file, %d of another client, %d s" % ( label, count["ok"], len(work), count["short"], a.min_words, count["cut"], count["error"], count["late"], count["held"], count["other"], time.time() - t0), flush=True) return 0 if count["ok"] or not work or count["other"] + count["held"] == len(work) else 1
def smoke(a): body = {"model": a.model, "max_tokens": 4000, "messages": [{"role": "user", "content": "Write two sentences about the sea."}]} try: text, thinking, finish, tokens = parse(call(a.base_url, body, 300)) except ERRORS as e: print("SMOKE FAIL", a.model, str(e)[:200], flush=True) return 1 ok = len(text.split()) >= 5 print("SMOKE", "ok" if ok else "FAIL", a.model, "finish", finish, "tokens", tokens, "thinking chars", len(thinking), "text:", repr(text[:120]), flush=True) return 0 if ok else 1
def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--base-url") ap.add_argument("--model") ap.add_argument("--name", help="the model name in the rows. Default: --model") ap.add_argument("--lab", default="other") ap.add_argument("--prompts") ap.add_argument("--out") ap.add_argument("--samples", type=int, default=2) ap.add_argument("--parallel", type=int, default=24) ap.add_argument("--max-tokens", type=int, default=12288) ap.add_argument("--deadline-s", type=float, default=1200, help="no call starts or stays after this time from the start") ap.add_argument("--end", type=float, default=0, help="the end time in epoch seconds. It replaces --deadline-s") ap.add_argument("--stop-file", help="no new call starts while this file is there") ap.add_argument("--claims") ap.add_argument("--done", nargs="*", help="more row files of this model: an answer in them is not asked again") ap.add_argument("--gate", type=int, default=8) ap.add_argument("--gate-cut", type=int, default=12) ap.add_argument("--min-words", type=int, default=100) ap.add_argument("--smoke", action="store_true") ap.add_argument("--count", action="store_true") a = ap.parse_args(argv) if a.smoke: return smoke(a) if a.count: prompts = [json.loads(line) for line in open(a.prompts, encoding="utf-8") if line.strip()] print(count_left(prompts, read_done(([a.out] if a.out else []) + (a.done or [])), a.samples, a.claims)) return 0 if not (a.prompts and a.out and a.base_url and a.model): ap.error("--base-url, --model, --prompts and --out, or --smoke, or --count") return run(a)
if __name__ == "__main__": code = main() sys.stdout.flush() os._exit(code) # a call in work does not hold the exitglm-4.7-flash/stories-v0/README.mdAdded+24
glm-4.7-flash/stories-v0/hf_stories.pyAdded+87
glm-4.7-flash/stories-v0/serve.shAdded+77
glm-4.7-flash/stories-v0/stories.jsonlAdded
glm-4.7-flash/stories-v0/story_job.shAdded+98
glm-4.7-flash/stories-v0/strip_marks.pyAdded+33
glm-4.7-flash/stories-v0/write_answers.pyAdded+224