Official Codebase of 3DCodeVerse
Python
finetune: dialect-aware code extraction for free-form/reasoning models (eval/extract.py), one-engine multi-suite generation (generate_multi.py), unified eval_all/exec_suites/results_all, full 3DCodeVerse audit + md_max builder (768k pairs incl. animation2code), mix sampler, Qwen3.8-27B configs; REPORT §11
gaoypeng8088a5d632bc
diff --git a/finetune/configs/lf/lora_27b_ddp.yaml b/finetune/configs/lf/lora_27b_ddp.yamlnew file mode 100644index 00000000..57b35eb1--- /dev/null+++ b/finetune/configs/lf/lora_27b_ddp.yaml@@ -0,0 +1,44 @@+model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.8-27B+trust_remote_code: true+flash_attn: fa2+stage: sft+do_train: true+finetuning_type: lora+lora_rank: 64+lora_alpha: 128+lora_dropout: 0.05+lora_target: all+freeze_vision_tower: true+freeze_multi_modal_projector: true+dataset_dir: /wekafs/ict/hx_624/llm-ft/data/lf+dataset: md_27b_max4k_train+eval_dataset: md_27b_max4k_val+template: qwen3_5+enable_thinking: false+cutoff_len: 4096+preprocessing_num_workers: 16+dataloader_num_workers: 4+neat_packing: true+packing: true+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tokenized_md_27b_max4k_len4096_packed+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen38_27b_lora_md_max+logging_steps: 5+save_steps: 200+save_only_model: true+plot_loss: true+overwrite_output_dir: true+report_to: tensorboard+per_device_train_batch_size: 1+gradient_accumulation_steps: 4+learning_rate: 0.0001+num_train_epochs: 1.0+lr_scheduler_type: cosine+warmup_ratio: 0.05+bf16: true+gradient_checkpointing: true+ddp_timeout: 180000000+resume_from_checkpoint: null+per_device_eval_batch_size: 1+eval_strategy: steps+eval_steps: 200+save_total_limit: 8diff --git a/finetune/configs/lf/lora_27b_md.yaml b/finetune/configs/lf/lora_27b_md.yamlnew file mode 100644index 00000000..91bdb5ef--- /dev/null+++ b/finetune/configs/lf/lora_27b_md.yaml@@ -0,0 +1,44 @@+model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.8-27B+trust_remote_code: true+flash_attn: fa2+stage: sft+do_train: true+finetuning_type: lora+lora_rank: 64+lora_alpha: 128+lora_dropout: 0.05+lora_target: all+freeze_vision_tower: true+freeze_multi_modal_projector: true+dataset_dir: /wekafs/ict/hx_624/llm-ft/data/lf+dataset: md_27b_train+eval_dataset: md_27b_val+template: qwen3_5+enable_thinking: false+cutoff_len: 8192+preprocessing_num_workers: 16+dataloader_num_workers: 4+neat_packing: true+packing: true+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tokenized_md_27b_len8192_packed+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen38_27b_lora_md_27b+logging_steps: 5+save_steps: 180+save_only_model: true+plot_loss: true+overwrite_output_dir: true+report_to: tensorboard+per_device_train_batch_size: 1+gradient_accumulation_steps: 2+learning_rate: 0.0001+num_train_epochs: 1.0+lr_scheduler_type: cosine+warmup_ratio: 0.05+bf16: true+gradient_checkpointing: true+ddp_timeout: 180000000+resume_from_checkpoint: null+per_device_eval_batch_size: 1+eval_strategy: steps+eval_steps: 180+save_total_limit: 6diff --git a/finetune/configs/lf/lora_27b_md_z3.yaml b/finetune/configs/lf/lora_27b_md_z3.yamlnew file mode 100644index 00000000..85ac3a76--- /dev/null+++ b/finetune/configs/lf/lora_27b_md_z3.yaml@@ -0,0 +1,45 @@+model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.8-27B+trust_remote_code: true+flash_attn: fa2+stage: sft+do_train: true+finetuning_type: lora+lora_rank: 64+lora_alpha: 128+lora_dropout: 0.05+lora_target: all+freeze_vision_tower: true+freeze_multi_modal_projector: true+dataset_dir: /wekafs/ict/hx_624/llm-ft/data/lf+dataset: md_27b_max_train+eval_dataset: md_27b_max_val+template: qwen3_5+enable_thinking: false+cutoff_len: 8192+preprocessing_num_workers: 16+dataloader_num_workers: 4+neat_packing: true+packing: true+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tokenized_md_27b_max_len8192_packed+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen38_27b_lora_md_max+logging_steps: 5+save_steps: 150+save_only_model: true+plot_loss: true+overwrite_output_dir: true+report_to: tensorboard+per_device_train_batch_size: 1+gradient_accumulation_steps: 2+learning_rate: 0.0001+num_train_epochs: 1.0+lr_scheduler_type: cosine+warmup_ratio: 0.05+bf16: true+gradient_checkpointing: true+ddp_timeout: 180000000+resume_from_checkpoint: null+per_device_eval_batch_size: 1+eval_strategy: steps+eval_steps: 150+save_total_limit: 8+deepspeed: /wekafs/ict/hx_624/tools/LLaMA-Factory/examples/deepspeed/ds_z3_config.jsondiff --git a/finetune/configs/lf/lora_md_max_9b.yaml b/finetune/configs/lf/lora_md_max_9b.yamlnew file mode 100644index 00000000..60e9a4c8--- /dev/null+++ b/finetune/configs/lf/lora_md_max_9b.yaml@@ -0,0 +1,44 @@+model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.5-9B+trust_remote_code: true+flash_attn: fa2+stage: sft+do_train: true+finetuning_type: lora+lora_rank: 64+lora_alpha: 128+lora_dropout: 0.05+lora_target: all+freeze_vision_tower: true+freeze_multi_modal_projector: true+dataset_dir: /wekafs/ict/hx_624/llm-ft/data/lf+dataset: md_max_9b_train+eval_dataset: md_max_9b_val+template: qwen3_5+enable_thinking: false+cutoff_len: 8192+preprocessing_num_workers: 16+dataloader_num_workers: 4+neat_packing: true+packing: true+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tokenized_md_max_9b_len8192_packed+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_lora_md_max+logging_steps: 5+save_steps: 500+save_only_model: true+plot_loss: true+overwrite_output_dir: true+report_to: tensorboard+per_device_train_batch_size: 1+gradient_accumulation_steps: 8+learning_rate: 0.0001+num_train_epochs: 1.0+lr_scheduler_type: cosine+warmup_ratio: 0.05+bf16: true+gradient_checkpointing: true+ddp_timeout: 180000000+resume_from_checkpoint: null+per_device_eval_batch_size: 1+eval_strategy: steps+eval_steps: 500+save_total_limit: 10diff --git a/finetune/data_specs/dataset_info.json b/finetune/data_specs/dataset_info.jsonindex 2611010d..e1200b10 100644--- a/finetune/data_specs/dataset_info.json+++ b/finetune/data_specs/dataset_info.json@@ -368,5 +368,69 @@"chosen": "chosen","rejected": "rejected"}+ },+ "md_27b_train": {+ "file_name": "md_27b_train.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }+ },+ "md_27b_val": {+ "file_name": "md_27b_val.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }+ },+ "md_27b_max_train": {+ "file_name": "md_27b_max_train.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }+ },+ "md_27b_max_val": {+ "file_name": "md_27b_max_val.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }+ },+ "md_max_9b_train": {+ "file_name": "md_max_9b_train.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }+ },+ "md_max_9b_val": {+ "file_name": "md_max_9b_val.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }+ },+ "md_27b_max4k_train": {+ "file_name": "md_27b_max4k_train.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }+ },+ "md_27b_max4k_val": {+ "file_name": "md_27b_max4k_val.json",+ "formatting": "sharegpt",+ "columns": {+ "messages": "conversations",+ "system": "system"+ }}}\ No newline at end of filediff --git a/finetune/data_specs/md_max_report.json b/finetune/data_specs/md_max_report.jsonnew file mode 100644index 00000000..77183f16--- /dev/null+++ b/finetune/data_specs/md_max_report.json@@ -0,0 +1,58 @@+{+ "pairs_kept": 768596,+ "tokens": 891094910,+ "by_dialect": {+ "cadquery": {+ "n": 390449,+ "Mtok": 395.5,+ "by_caption": {+ "instruction": 129689,+ "detailed": 130171,+ "factory": 130589+ }+ },+ "glsl": {+ "n": 353061,+ "Mtok": 470.4,+ "by_caption": {+ "instruction": 117700,+ "detailed": 117682,+ "factory": 117679+ }+ },+ "blender": {+ "n": 19609,+ "Mtok": 15.2,+ "by_caption": {+ "instruction": 6579,+ "detailed": 6588,+ "factory": 6442+ }+ },+ "openscad": {+ "n": 3312,+ "Mtok": 4.9,+ "by_caption": {+ "instruction": 1104,+ "detailed": 1104,+ "factory": 1104+ }+ },+ "web": {+ "n": 1616,+ "Mtok": 2.5,+ "by_caption": {+ "instruction": 808,+ "detailed": 808+ }+ },+ "threejs": {+ "n": 549,+ "Mtok": 2.5,+ "by_caption": {+ "instruction": 274,+ "detailed": 275+ }+ }+ }+}\ No newline at end of filediff --git a/finetune/eval/eval_all.sh b/finetune/eval/eval_all.shnew file mode 100755index 00000000..a44fee33--- /dev/null+++ b/finetune/eval/eval_all.sh@@ -0,0 +1,74 @@+#!/bin/bash+# One command to evaluate ANY model on everything: 3DCodeBench (Blender exec + geometry vs GT) and the five+# held-out dialect sets (CadQuery / OpenSCAD / GLSL / Blender / three.js), with dialect-aware code extraction.+#+# GPUS=0 TP=1 eval/eval_all.sh <model_dir> <name> [--think] [--temp 0.7] [--seed 1] [--max_new 8192] [--suites ...]+#+# --think keep the model's reasoning on (default: enable_thinking=false)+# --temp/--seed sampling (default greedy)+# --suites space-separated subset of: bench cadquery openscad glsl blender threejs (default: all)+# results: eval/out/<name>_<suite>/summary.json + eval/out/<name>_report.json (one row per suite)+set -uo pipefail+MODEL=$(readlink -f "$1"); NAME=$2; shift 2+GPU=${GPUS:-0}; TP=${TP:-1}; THINK=""; TEMP=0.0; SEED=0; MAXNEW=8192+SUITES="bench cadquery openscad glsl blender threejs"+while [ $# -gt 0 ]; do+ case "$1" in+ --think) THINK="1"; shift;;+ --temp) TEMP=$2; shift 2;;+ --seed) SEED=$2; shift 2;;+ --max_new) MAXNEW=$2; shift 2;;+ --suites) shift; SUITES=""; while [ $# -gt 0 ] && [[ "$1" != --* ]]; do SUITES="$SUITES $1"; shift; done;;+ *) echo "unknown arg $1"; exit 2;;+ esac+done+cd /wekafs/ict/hx_624/llm-ft+source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh+export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING+export PLAYWRIGHT_BROWSERS_PATH=/wekafs/ict/hx_624/cache/ms-playwright CUDA_VISIBLE_DEVICES=$GPU+NOTHINK="--no_think"; [ -n "$THINK" ] && NOTHINK=""+MAXLEN=$((MAXNEW + 4096))+echo "[eval_all] $(date) model=$MODEL name=$NAME gpus=$GPU tp=$TP think=${THINK:-0} temp=$TEMP suites=$SUITES"++# ---------- generation: ONE engine for all suites (loading a 27B per suite costs more than generating) ----------+conda activate vllm+SPEC=$(mktemp /tmp/hx_624_evalspec_XXXX.json)+python - "$NAME" "$SUITES" "$SPEC" <<'PY'+import json, sys, os+name, suites, spec_path = sys.argv[1], sys.argv[2].split(), sys.argv[3]+jobs = []+for s in suites:+ out = f"eval/out/{name}_{s}"; os.makedirs(out, exist_ok=True)+ if s == "bench":+ prompts, dia = "data/sft_v1/bench_prompts.jsonl", "blender"+ elif s == "threejs":+ prompts, dia = "eval/out/_3js_prompts.jsonl", "threejs"+ else:+ prompts, dia = f"{out}/prompts.jsonl", s+ with open(prompts, "w") as f:+ for l in open(f"data/multidialect/{s}/test.jsonl"):+ r = json.loads(l); f.write(json.dumps({"task": r["id"].replace("/", "__"), "messages": r["messages"][:2]}) + "\n")+ jobs.append({"name": s, "prompts": prompts, "out": out, "dialect": dia})+json.dump(jobs, open(spec_path, "w"))+print("[eval_all] suites:", [j["name"] for j in jobs])+PY+python eval/generate_multi.py --model $MODEL --spec @$SPEC --tp $TP $NOTHINK \+ --max_new_tokens $MAXNEW --max_model_len $MAXLEN --temperature $TEMP --seed $SEED 2>&1 \+ | grep -E "gen-multi|extract\]|Error|Traceback" | tail -40+rm -f $SPEC++# ---------- execution + metrics (llmft env) ----------+conda activate llmft+for S in $SUITES; do+ OUT=eval/out/${NAME}_${S}+ echo "[eval_all] exec $S"+ case $S in+ bench) python eval/run_bench.py --gen_dir $OUT --workers 32 --timeout 300 2>&1 | grep -E "status counts" | tail -1+ python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1;;+ blender) python eval/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;+ threejs) python eval/threejs_eval.py --gen_dir $OUT 2>&1 | tail -2;;+ *) python eval/dialect_eval.py --dialect $S --test data/multidialect/$S/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;+ esac+done+python eval/results_all.py $NAME+echo "[eval_all] DONE $NAME"diff --git a/finetune/eval/eval_all_run2.sh b/finetune/eval/eval_all_run2.shnew file mode 100755index 00000000..a44fee33--- /dev/null+++ b/finetune/eval/eval_all_run2.sh@@ -0,0 +1,74 @@+#!/bin/bash+# One command to evaluate ANY model on everything: 3DCodeBench (Blender exec + geometry vs GT) and the five+# held-out dialect sets (CadQuery / OpenSCAD / GLSL / Blender / three.js), with dialect-aware code extraction.+#+# GPUS=0 TP=1 eval/eval_all.sh <model_dir> <name> [--think] [--temp 0.7] [--seed 1] [--max_new 8192] [--suites ...]+#+# --think keep the model's reasoning on (default: enable_thinking=false)+# --temp/--seed sampling (default greedy)+# --suites space-separated subset of: bench cadquery openscad glsl blender threejs (default: all)+# results: eval/out/<name>_<suite>/summary.json + eval/out/<name>_report.json (one row per suite)+set -uo pipefail+MODEL=$(readlink -f "$1"); NAME=$2; shift 2+GPU=${GPUS:-0}; TP=${TP:-1}; THINK=""; TEMP=0.0; SEED=0; MAXNEW=8192+SUITES="bench cadquery openscad glsl blender threejs"+while [ $# -gt 0 ]; do+ case "$1" in+ --think) THINK="1"; shift;;+ --temp) TEMP=$2; shift 2;;+ --seed) SEED=$2; shift 2;;+ --max_new) MAXNEW=$2; shift 2;;+ --suites) shift; SUITES=""; while [ $# -gt 0 ] && [[ "$1" != --* ]]; do SUITES="$SUITES $1"; shift; done;;+ *) echo "unknown arg $1"; exit 2;;+ esac+done+cd /wekafs/ict/hx_624/llm-ft+source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh+export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING+export PLAYWRIGHT_BROWSERS_PATH=/wekafs/ict/hx_624/cache/ms-playwright CUDA_VISIBLE_DEVICES=$GPU+NOTHINK="--no_think"; [ -n "$THINK" ] && NOTHINK=""+MAXLEN=$((MAXNEW + 4096))+echo "[eval_all] $(date) model=$MODEL name=$NAME gpus=$GPU tp=$TP think=${THINK:-0} temp=$TEMP suites=$SUITES"++# ---------- generation: ONE engine for all suites (loading a 27B per suite costs more than generating) ----------+conda activate vllm+SPEC=$(mktemp /tmp/hx_624_evalspec_XXXX.json)+python - "$NAME" "$SUITES" "$SPEC" <<'PY'+import json, sys, os+name, suites, spec_path = sys.argv[1], sys.argv[2].split(), sys.argv[3]+jobs = []+for s in suites:+ out = f"eval/out/{name}_{s}"; os.makedirs(out, exist_ok=True)+ if s == "bench":+ prompts, dia = "data/sft_v1/bench_prompts.jsonl", "blender"+ elif s == "threejs":+ prompts, dia = "eval/out/_3js_prompts.jsonl", "threejs"+ else:+ prompts, dia = f"{out}/prompts.jsonl", s+ with open(prompts, "w") as f:+ for l in open(f"data/multidialect/{s}/test.jsonl"):+ r = json.loads(l); f.write(json.dumps({"task": r["id"].replace("/", "__"), "messages": r["messages"][:2]}) + "\n")+ jobs.append({"name": s, "prompts": prompts, "out": out, "dialect": dia})+json.dump(jobs, open(spec_path, "w"))+print("[eval_all] suites:", [j["name"] for j in jobs])+PY+python eval/generate_multi.py --model $MODEL --spec @$SPEC --tp $TP $NOTHINK \+ --max_new_tokens $MAXNEW --max_model_len $MAXLEN --temperature $TEMP --seed $SEED 2>&1 \+ | grep -E "gen-multi|extract\]|Error|Traceback" | tail -40+rm -f $SPEC++# ---------- execution + metrics (llmft env) ----------+conda activate llmft+for S in $SUITES; do+ OUT=eval/out/${NAME}_${S}+ echo "[eval_all] exec $S"+ case $S in+ bench) python eval/run_bench.py --gen_dir $OUT --workers 32 --timeout 300 2>&1 | grep -E "status counts" | tail -1+ python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1;;+ blender) python eval/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;+ threejs) python eval/threejs_eval.py --gen_dir $OUT 2>&1 | tail -2;;+ *) python eval/dialect_eval.py --dialect $S --test data/multidialect/$S/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;+ esac+done+python eval/results_all.py $NAME+echo "[eval_all] DONE $NAME"diff --git a/finetune/eval/exec_suites.sh b/finetune/eval/exec_suites.shnew file mode 100755index 00000000..de3db938--- /dev/null+++ b/finetune/eval/exec_suites.sh@@ -0,0 +1,19 @@+#!/bin/bash+# Execute + score already-generated suites (no GPU): eval/exec_suites.sh <name> [suites...]+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft+NAME=$1; shift; SUITES=${@:-bench cadquery openscad glsl blender threejs}+source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate llmft+export PLAYWRIGHT_BROWSERS_PATH=/wekafs/ict/hx_624/cache/ms-playwright+for S in $SUITES; do+ OUT=eval/out/${NAME}_${S}; [ -d $OUT ] || continue+ echo "[exec] $NAME/$S"+ case $S in+ bench) python eval/run_bench.py --gen_dir $OUT --workers 24 --timeout 300 2>&1 | grep -E "status counts" | tail -1+ python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1;;+ blender) python eval/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 24 2>&1 | tail -1;;+ threejs) python eval/threejs_eval.py --gen_dir $OUT 2>&1 | tail -2;;+ *) python eval/dialect_eval.py --dialect $S --test data/multidialect/$S/test.jsonl --gen_dir $OUT --workers 24 2>&1 | tail -1;;+ esac+done+python eval/results_all.py $NAME+echo "[exec] DONE $NAME"diff --git a/finetune/eval/extract.py b/finetune/eval/extract.pynew file mode 100644index 00000000..55eaa783--- /dev/null+++ b/finetune/eval/extract.py@@ -0,0 +1,220 @@+"""Dialect-aware code extraction from free-form model output.++Why this exists: instruct/reasoning models do not answer with bare code. A single response may contain+a <think> block (often with *draft* code), prose, several fenced blocks (setup shell commands, a JSON+snippet, the real program, then a "here's a variant" block), or no fence at all. Taking "the longest+fenced block" (the old rule) picks the draft or the variant often enough to matter.++extract(text, dialect) -> (code, meta)+ * strips reasoning blocks (<think>…</think>, <thinking>…</thinking>, <reasoning>…</reasoning>);+ if the model never closed the block the answer is considered truncated-in-thought and we fall back+ to mining the thought itself (meta["from_think"]=True) so we can still score something.+ * collects candidates: every fenced block (closed or trailing-unterminated), plus the whole visible+ text as a last resort.+ * scores each candidate by: dialect markers (import bpy / cq. / mainImage / THREE. / module …),+ language tag on the fence, syntax validity (ast.parse for python dialects, structural checks+ otherwise), and penalises obvious non-answers (shell commands, pip installs, json, error logs).+ * ties are broken toward the LAST high-scoring block (models put the final program last), then length.++meta keys: n_blocks, chosen, score, lang, had_think, think_chars, from_think, no_fence, valid, markers.+"""+import ast+import json+import re++THINK_RE = re.compile(r"<(think|thinking|reasoning)>(.*?)</\1>", re.S | re.I)+THINK_OPEN_RE = re.compile(r"<(think|thinking|reasoning)>(.*)$", re.S | re.I)+FENCE_RE = re.compile(r"```([A-Za-z0-9_+.#-]*)[ \t]*\r?\n(.*?)```", re.S)+FENCE_OPEN_RE = re.compile(r"```([A-Za-z0-9_+.#-]*)[ \t]*\r?\n(.*)$", re.S)++# per-dialect: fence language tags, regexes that prove the block is that dialect, and how to syntax-check+DIALECTS = {+ "blender": {+ "langs": {"python", "py", "python3", "blender", "bpy"},+ "markers": [r"^\s*import\s+bpy\b", r"\bbpy\.(ops|data|context)\b"],+ "check": "python",+ },+ "cadquery": {+ "langs": {"python", "py", "python3", "cadquery", "cq"},+ "markers": [r"^\s*import\s+cadquery\b", r"^\s*from\s+cadquery\b", r"\bcq\.Workplane\b", r"\bcadquery\.Workplane\b"],+ "check": "python",+ },+ "openscad": {+ "langs": {"openscad", "scad"},+ "markers": [r"^\s*module\s+\w+\s*\(", r"\b(cube|cylinder|sphere|polyhedron|linear_extrude|rotate_extrude|hull|minkowski)\s*\("],+ "check": "scad",+ },+ "glsl": {+ "langs": {"glsl", "frag", "fragment", "fs", "c", "cpp"},+ "markers": [r"void\s+mainImage\s*\(", r"\bgl_FragColor\b", r"^\s*#version\b", r"\bfragColor\b"],+ "check": "glsl",+ },+ "threejs": {+ "langs": {"html", "htm", "javascript", "js", "jsx"},+ "markers": [r"<!DOCTYPE\s+html", r"<html", r"\bnew\s+THREE\.", r"\bTHREE\.[A-Z]\w+"],+ "check": "html",+ },+ # generic python (used by "auto" when nothing dialect-specific matches)+ "python": {"langs": {"python", "py", "python3"}, "markers": [r"^\s*(import|from|def|class)\s+\w"], "check": "python"},+}++# blocks that are never the answer+NEGATIVE = [+ (re.compile(r"^\s*(pip|conda|apt|sudo|blender|python)\s+(install|-m|-b)\b", re.M), 4),+ (re.compile(r"^\s*[$#>]\s+\w"), 3), # shell prompt+ (re.compile(r"^\s*\{[\s\S]*\}\s*$"), 2), # bare JSON+ (re.compile(r"^\s*(Traceback|Error:|error:)", re.M), 3), # pasted error log+]+++def _syntax_ok(code, kind):+ if kind == "python":+ try:+ ast.parse(code)+ return True+ except SyntaxError:+ return False+ except Exception:+ return False+ if kind == "scad":+ return code.count("{") == code.count("}") and code.count("(") == code.count(")") and bool(re.search(r"[;{]", code))+ if kind == "glsl":+ return code.count("{") == code.count("}") and "void" in code+ if kind == "html":+ return ("<" in code and ">" in code) or "THREE" in code+ return True+++def _candidates(text):+ """[(lang, code, start_index)] for every fenced block, plus a trailing unterminated one."""+ out, last_end = [], 0+ for m in FENCE_RE.finditer(text):+ out.append((m.group(1).lower(), m.group(2), m.start()))+ last_end = m.end()+ tail = text[last_end:]+ m = FENCE_OPEN_RE.search(tail)+ if m and m.group(2).strip():+ out.append((m.group(1).lower(), m.group(2), last_end + m.start()))+ return out+++def _first_code_line(text):+ """No fence anywhere: drop the prose preamble, keep from the first code-looking line on."""+ pat = re.compile(r"^\s*(import\s+\w|from\s+\w|def\s+\w|class\s+\w|#\s*!|#version|module\s+\w|void\s+\w|<!DOCTYPE|<html|const\s+\w|let\s+\w|var\s+\w|function\s+\w|\$fn\s*=)")+ lines = text.splitlines()+ for i, ln in enumerate(lines):+ if pat.match(ln):+ return "\n".join(lines[i:])+ return text+++def _score(lang, code, spec):+ s, markers = 0.0, 0+ for pat in spec["markers"]:+ if re.search(pat, code, re.M):+ markers += 1+ s += 3.0 * min(markers, 2)+ if lang in spec["langs"]:+ s += 2.0+ elif lang == "":+ s += 0.5+ valid = _syntax_ok(code, spec["check"])+ if valid:+ s += 2.0+ for pat, pen in NEGATIVE:+ if pat.search(code):+ s -= pen+ if len(code.strip()) < 40:+ s -= 2.0+ return s, valid, markers+++def extract(text, dialect="auto"):+ meta = {"n_blocks": 0, "chosen": None, "score": None, "lang": None, "had_think": False,+ "think_chars": 0, "from_think": False, "no_fence": False, "valid": False, "markers": 0,+ "dialect": dialect}+ if not text:+ return "", meta++ # 1) reasoning blocks+ thinks = THINK_RE.findall(text)+ visible = THINK_RE.sub("", text)+ if thinks:+ meta["had_think"] = True+ meta["think_chars"] = sum(len(t[1]) for t in thinks)+ m = THINK_OPEN_RE.search(visible)+ if m: # unterminated <think>: everything after it is thought+ meta["had_think"] = True+ meta["think_chars"] += len(m.group(2))+ visible = visible[: m.start()]++ def _pick(src):+ cands = _candidates(src)+ if not cands:+ return None, None+ specs = [DIALECTS[dialect]] if dialect in DIALECTS else list(DIALECTS.values())+ best = None+ for i, (lang, code, _pos) in enumerate(cands):+ sc = max((_score(lang, code, sp) for sp in specs), key=lambda x: x[0])+ key = (round(sc[0], 3), i, len(code)) # score, then LAST block, then length+ if best is None or key > best[0]:+ best = (key, i, lang, code, sc)+ return cands, best++ cands, best = _pick(visible)+ if best is None and visible.strip(): # no fence in the visible answer+ code = _first_code_line(visible)+ specs = [DIALECTS[dialect]] if dialect in DIALECTS else list(DIALECTS.values())+ sc = max((_score("", code, sp) for sp in specs), key=lambda x: x[0])+ meta.update(n_blocks=0, no_fence=True, chosen=-1, score=round(sc[0], 2), lang="", valid=sc[1], markers=sc[2])+ return code.strip("\n"), meta+ if best is None: # nothing visible: mine the thought+ cands, best = _pick(text)+ meta["from_think"] = True+ if best is None:+ return "", meta++ meta.update(n_blocks=len(cands), chosen=best[1], score=round(best[4][0], 2), lang=best[2],+ valid=best[4][1], markers=best[4][2])+ return best[3].strip("\n"), meta+++def extract_code(text, dialect="auto"):+ """Backwards-compatible single-value API (old callers import this name from generate.py)."""+ return extract(text, dialect)[0]+++def summarize(metas):+ """Aggregate extraction metadata over a run -> dict for extract_stats.json."""+ n = max(1, len(metas))+ return {+ "n": len(metas),+ "with_think": sum(m.get("had_think", False) for m in metas),+ "mean_think_chars": round(sum(m.get("think_chars", 0) for m in metas) / n, 1),+ "no_fence": sum(m.get("no_fence", False) for m in metas),+ "from_think_fallback": sum(m.get("from_think", False) for m in metas),+ "multi_block": sum((m.get("n_blocks") or 0) > 1 for m in metas),+ "mean_blocks": round(sum(m.get("n_blocks") or 0 for m in metas) / n, 2),+ "chosen_not_last": sum(m.get("chosen") is not None and m.get("n_blocks") and m["chosen"] != m["n_blocks"] - 1 for m in metas),+ "syntax_valid": sum(m.get("valid", False) for m in metas),+ "no_dialect_marker": sum((m.get("markers") or 0) == 0 for m in metas),+ "empty": sum((m.get("score") is None) for m in metas),+ }+++if __name__ == "__main__": # tiny self-test: python eval/extract.py+ T = [+ ("<think>let me draft\n```python\nimport bpy\nbpy.ops.mesh.primitive_cube_add() # draft\n```\nno, better</think>\n"+ "Here is the script:\n```python\nimport bpy\nbpy.ops.mesh.primitive_uv_sphere_add(radius=2)\n```\nThat creates a sphere.",+ "blender", "uv_sphere"),+ ("First install:\n```bash\npip install cadquery\n```\nThen:\n```python\nimport cadquery as cq\nresult = cq.Workplane('XY').box(1,2,3)\n```",+ "cadquery", "Workplane"),+ ("Sure!\nimport bpy\nbpy.ops.mesh.primitive_cone_add()\n", "blender", "cone"),+ ("```\n$fn = 64;\nmodule part(){ cube([10,10,2]); }\npart();\n```", "openscad", "module part"),+ ("```glsl\nvoid mainImage(out vec4 O, in vec2 U){ O = vec4(1.0); }\n```", "glsl", "mainImage"),+ ("<think>thinking forever without closing\n```python\nimport bpy\nbpy.ops.mesh.primitive_torus_add()\n```",+ "blender", "torus"),+ ]+ for text, d, needle in T:+ code, meta = extract(text, d)+ print(("OK " if needle in code else "FAIL"), d, json.dumps({k: meta[k] for k in ("n_blocks", "chosen", "score", "had_think", "from_think", "no_fence", "valid")}))diff --git a/finetune/eval/generate_multi.py b/finetune/eval/generate_multi.pynew file mode 100644index 00000000..7f38713b--- /dev/null+++ b/finetune/eval/generate_multi.py@@ -0,0 +1,81 @@+"""Run several evaluation suites through ONE vLLM engine (loading a 27B twice costs more than generating).++ python eval/generate_multi.py --model M --tp 2 --spec '[{"name":"bench","prompts":"...","out":"...","dialect":"blender"}, ...]'+ [--no_think] [--temperature 0.7] [--seed 1] [--max_new_tokens 12288] [--max_model_len 16384] [--limit N]++Writes, per job: <out>/<task>/{code.py,raw.txt}, <out>/gens_shard0.jsonl, <out>/extract_stats.json — identical to+generate_vllm.py, so every downstream executor/metric script works unchanged.+"""+import argparse+import json+import os+import sys+import time++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from extract import extract, summarize+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--model", required=True)+ ap.add_argument("--spec", required=True, help="JSON list (or @file) of {name,prompts,out,dialect}")+ ap.add_argument("--max_new_tokens", type=int, default=8192)+ ap.add_argument("--max_model_len", type=int, default=12288)+ ap.add_argument("--temperature", type=float, default=0.0)+ ap.add_argument("--seed", type=int, default=0)+ ap.add_argument("--no_think", action="store_true")+ ap.add_argument("--tp", type=int, default=1)+ ap.add_argument("--gpu_mem", type=float, default=0.88)+ ap.add_argument("--limit", type=int, default=None)+ a = ap.parse_args()+ spec = json.load(open(a.spec[1:])) if a.spec.startswith("@") else json.loads(a.spec)++ from vllm import LLM, SamplingParams+ t_load = time.time()+ llm = LLM(model=a.model, dtype="bfloat16", tensor_parallel_size=a.tp, max_model_len=a.max_model_len,+ gpu_memory_utilization=a.gpu_mem, enable_prefix_caching=True,+ limit_mm_per_prompt={"image": 0, "video": 0}, trust_remote_code=True)+ print(f"[gen-multi] engine up in {time.time()-t_load:.0f}s | jobs: {[j['name'] for j in spec]}", flush=True)+ sp = SamplingParams(temperature=a.temperature, top_p=0.95 if a.temperature > 0 else 1.0,+ max_tokens=a.max_new_tokens, seed=a.seed)+ kw = {"chat_template_kwargs": {"enable_thinking": False}} if a.no_think else {}++ for job in spec:+ rows = [json.loads(l) for l in open(job["prompts"])]+ if a.limit:+ rows = rows[: a.limit]+ os.makedirs(job["out"], exist_ok=True)+ t0 = time.time()+ outs = llm.chat([r["messages"] for r in rows], sp, use_tqdm=True, **kw)+ el = time.time() - t0+ ntok, metas = 0, []+ with open(f"{job['out']}/gens_shard0.jsonl", "w") as f:+ for r, o in zip(rows, outs):+ text = o.outputs[0].text+ n = len(o.outputs[0].token_ids)+ ntok += n+ d = f"{job['out']}/{r['task']}"+ os.makedirs(d, exist_ok=True)+ code, meta = extract(text, job.get("dialect", "auto"))+ metas.append(meta)+ open(f"{d}/code.py", "w").write(code + "\n")+ open(f"{d}/raw.txt", "w").write(text)+ f.write(json.dumps({"task": r["task"], "n_new_tokens": n,+ "finished": o.outputs[0].finish_reason == "stop",+ "has_code_block": "```" in text, "extract": meta}) + "\n")+ stats = summarize(metas)+ stats.update({"model": a.model, "dialect": job.get("dialect"), "temperature": a.temperature,+ "no_think": a.no_think, "max_new_tokens": a.max_new_tokens,+ "tok_per_s": round(ntok / max(el, 1e-6), 1), "mean_new_tokens": round(ntok / max(1, len(rows)), 1),+ "truncated": sum(1 for r, o in zip(rows, outs) if o.outputs[0].finish_reason != "stop")})+ json.dump(stats, open(f"{job['out']}/extract_stats.json", "w"), indent=2)+ print(f"[gen-multi] {job['name']}: {len(rows)} prompts | {ntok} tok | {ntok/el:.0f} tok/s | {el/60:.1f} min", flush=True)+ print("[extract] " + json.dumps({k: stats[k] for k in ("with_think", "no_fence", "from_think_fallback",+ "multi_block", "chosen_not_last", "syntax_valid",+ "no_dialect_marker", "truncated")}), flush=True)+ print("[gen-multi] ALL GENERATION DONE", flush=True)+++if __name__ == "__main__":+ main()diff --git a/finetune/eval/generate_vllm.py b/finetune/eval/generate_vllm.pyindex 28c4b867..1b98e6ea 100644--- a/finetune/eval/generate_vllm.py+++ b/finetune/eval/generate_vllm.py@@ -1,13 +1,16 @@"""vLLM version of generate.py: same outputs (<out>/<task>/code.py + raw.txt, <out>/gens_shard0.jsonl)."""import argparse, json, os, re, time, syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-from generate import extract_code+from generate import extract_code as extract_code_legacy+from extract import extract, summarizedef main():ap = argparse.ArgumentParser()ap.add_argument("--model", required=True); ap.add_argument("--prompts", required=True); ap.add_argument("--out", required=True)ap.add_argument("--max_new_tokens", type=int, default=6144); ap.add_argument("--temperature", type=float, default=0.0)ap.add_argument("--max_model_len", type=int, default=12288); ap.add_argument("--no_think", action="store_true")+ ap.add_argument("--dialect", default="auto", help="blender|cadquery|openscad|glsl|threejs|auto — steers code extraction from free-form answers")+ ap.add_argument("--legacy_extract", action="store_true", help="use the old longest-fenced-block rule")ap.add_argument("--tp", type=int, default=1); ap.add_argument("--gpu_mem", type=float, default=0.88); ap.add_argument("--limit", type=int, default=None); ap.add_argument("--seed", type=int, default=0)a = ap.parse_args()from vllm import LLM, SamplingParams@@ -21,13 +24,26 @@ def main():t0 = time.time()outs = llm.chat([r["messages"] for r in rows], sp, use_tqdm=True, **kw)el = time.time() - t0; ntok = 0+ metas = []with open(f"{a.out}/gens_shard0.jsonl", "w") as f:for r, o in zip(rows, outs):text = o.outputs[0].text; n = len(o.outputs[0].token_ids); ntok += nd = f"{a.out}/{r['task']}"; os.makedirs(d, exist_ok=True)- open(f"{d}/code.py", "w").write(extract_code(text) + "\n"); open(f"{d}/raw.txt", "w").write(text)- f.write(json.dumps({"task": r["task"], "n_new_tokens": n, "finished": o.outputs[0].finish_reason == "stop", "has_code_block": "```" in text}) + "\n")+ if a.legacy_extract:+ code, meta = extract_code_legacy(text), {}+ else:+ code, meta = extract(text, a.dialect)+ metas.append(meta)+ open(f"{d}/code.py", "w").write(code + "\n"); open(f"{d}/raw.txt", "w").write(text)+ f.write(json.dumps({"task": r["task"], "n_new_tokens": n, "finished": o.outputs[0].finish_reason == "stop",+ "has_code_block": "```" in text, "extract": meta}) + "\n")+ stats = summarize(metas) if not a.legacy_extract else {"legacy": True}+ stats.update({"model": a.model, "dialect": a.dialect, "temperature": a.temperature, "no_think": a.no_think,+ "max_new_tokens": a.max_new_tokens, "tok_per_s": round(ntok / el, 1), "mean_new_tokens": round(ntok / max(1, len(rows)), 1)})+ json.dump(stats, open(f"{a.out}/extract_stats.json", "w"), indent=2)print(f"[gen-vllm] {len(rows)} prompts | {ntok} tok | {ntok/el:.0f} tok/s | {el/60:.1f} min", flush=True)+ if not a.legacy_extract:+ print("[extract] " + json.dumps({k: stats[k] for k in ("with_think", "no_fence", "from_think_fallback", "multi_block", "chosen_not_last", "syntax_valid", "no_dialect_marker")}), flush=True)if __name__ == "__main__":main()diff --git a/finetune/eval/results_all.py b/finetune/eval/results_all.pynew file mode 100644index 00000000..dcbab515--- /dev/null+++ b/finetune/eval/results_all.py@@ -0,0 +1,59 @@+"""Aggregate every suite of one eval_all run (or compare several runs) into a table.++ python eval/results_all.py <name> [<name2> ...] -> markdown table + eval/out/<name>_report.json+"""+import json+import os+import sys++SUITES = [("bench", "3DCodeBench (212)"), ("blender", "Blender held-out (103)"), ("cadquery", "CadQuery (200)"),+ ("openscad", "OpenSCAD (50)"), ("glsl", "GLSL (200)"), ("threejs", "three.js (40)")]+ROOT = "/wekafs/ict/hx_624/llm-ft/eval/out"+++def suite_row(name, suite):+ d = os.path.join(ROOT, f"{name}_{suite}")+ s_path, x_path = os.path.join(d, "summary.json"), os.path.join(d, "extract_stats.json")+ if not os.path.exists(s_path):+ return None+ s = json.load(open(s_path))+ x = json.load(open(x_path)) if os.path.exists(x_path) else {}+ if suite == "bench":+ rate, f05, f01 = s.get("exec_ok_rate"), s.get("[email protected]_mean_all(fail=0)"), s.get("[email protected]_mean_scored")+ n_ok, n = s.get("exec_ok"), s.get("n_tasks")+ elif suite == "threejs":+ rate, f05, f01 = s.get("exec_rate"), None, None+ n_ok, n = s.get("exec_ok"), s.get("n")+ else:+ rate, f05, f01 = s.get("gen_exec_rate"), s.get("[email protected]_mean_all"), s.get("[email protected]_mean_scored")+ n_ok, n = s.get("gen_exec_ok"), s.get("n")+ return {"suite": suite, "n": n, "exec_ok": n_ok, "exec_rate": rate, "[email protected]_all": f05, "[email protected]_scored": f01,+ "mean_new_tokens": x.get("mean_new_tokens"), "with_think": x.get("with_think"), "no_fence": x.get("no_fence"),+ "multi_block": x.get("multi_block"), "chosen_not_last": x.get("chosen_not_last"),+ "syntax_valid": x.get("syntax_valid"), "no_dialect_marker": x.get("no_dialect_marker"),+ "from_think_fallback": x.get("from_think_fallback")}+++def main(names):+ print("| model | suite | exec | rate | [email protected](all) | [email protected](ok) | out tok | think | no-fence | multi-blk | not-last | no-marker |")+ print("|---|---|---|---|---|---|---|---|---|---|---|---|")+ for name in names:+ rows = []+ for suite, _label in SUITES:+ r = suite_row(name, suite)+ if not r:+ continue+ rows.append(r)+ pct = f"{100*r['exec_rate']:.1f}%" if r["exec_rate"] is not None else "–"+ f05 = f"{r['[email protected]_all']:.3f}" if r["[email protected]_all"] is not None else "–"+ f01 = f"{r['[email protected]_scored']:.3f}" if r["[email protected]_scored"] is not None else "–"+ print(f"| {name} | {suite} | {r['exec_ok']}/{r['n']} | {pct} | {f05} | {f01} | "+ f"{r['mean_new_tokens'] or '–'} | {r['with_think'] if r['with_think'] is not None else '–'} | "+ f"{r['no_fence'] if r['no_fence'] is not None else '–'} | {r['multi_block'] if r['multi_block'] is not None else '–'} | "+ f"{r['chosen_not_last'] if r['chosen_not_last'] is not None else '–'} | {r['no_dialect_marker'] if r['no_dialect_marker'] is not None else '–'} |")+ if rows:+ json.dump({"name": name, "suites": rows}, open(os.path.join(ROOT, f"{name}_report.json"), "w"), indent=2)+++if __name__ == "__main__":+ main(sys.argv[1:] or ["md_xl"])diff --git a/finetune/scripts/build_md_27b.py b/finetune/scripts/build_md_27b.pynew file mode 100644index 00000000..40f0f4e2--- /dev/null+++ b/finetune/scripts/build_md_27b.py@@ -0,0 +1,35 @@+"""md_27b: 5-dialect mix sized for a 27B LoRA run (~50M tok/epoch): CadQuery 15k, GLSL 12k, Blender all + boot 8k, OpenSCAD x4, three.js."""+import json, random, os, sys+sys.path.insert(0, "/wekafs/ict/hx_624/llm-ft/scripts"); from ntok_cache import load_ntok+from transformers import AutoTokenizer+random.seed(14); tok = AutoTokenizer.from_pretrained("/wekafs/ict/hx_624/models/Qwen3.5-9B")+MD = "/wekafs/ict/hx_624/llm-ft/data/multidialect"; CAP = {"cadquery": 15000, "glsl": 12000, "openscad": 10**9, "blender": 10**9, "threejs": 10**9}; REP = {"openscad": 4}; BOOT_REP = 1; BOOT_CAP = 8000+def ntok(r): return len(tok(tok.apply_chat_template(r["messages"], tokenize=False)).input_ids)+out_rows = []; stats = {}+for d, cap in CAP.items():+ rows = [json.loads(l) for l in open(f"{MD}/{d}/train.jsonl")]; NT = load_ntok(f"{MD}/{d}/train.jsonl", tok)+ for r, n_ in zip(rows, NT): r["_ntok"] = n_+ random.shuffle(rows); keep = []; toks = 0+ for r in rows:+ if len(keep) >= cap: break+ n = r.pop("_ntok")+ if n <= 8192: keep.append(r); toks += n+ rep = REP.get(d, 1); stats[d] = (len(keep) * rep, toks * rep); out_rows += keep * rep+BOOT = "/wekafs/ict/hx_624/llm-ft/data/sft_v13_boot/train.jsonl"; bl = open(BOOT).read().splitlines(); bn = load_ntok(BOOT, tok)+boot = [(json.loads(l), n) for l, n in zip(bl, bn) if '"source": "boot_' in l]+bt = 0; kb = []+for r, n in boot:+ if n <= 8192: kb.append({"messages": r["messages"], "dialect": "blender", "subset": "boot"}); bt += n+import random as _r; _r.shuffle(kb); kb = kb[:BOOT_CAP]; bt = sum(n for _, n in kb_ntok[:BOOT_CAP]) if False else int(bt * BOOT_CAP / max(1, len(boot)))+stats["blender_boot"] = (len(kb), bt); out_rows += kb+# LLaMA-Factory's qwen3_5 (multimodal) template treats literal <image>/<video>/<audio> in text as media placeholders -> escape them+def _san(t): return t.replace("<image>", "<image >").replace("<video>", "<video >").replace("<audio>", "<audio >")+for r in out_rows:+ for m in r["messages"]: m["content"] = _san(m["content"])+random.shuffle(out_rows)+out = "/wekafs/ict/hx_624/llm-ft/data/md_27b"; os.makedirs(out, exist_ok=True)+with open(f"{out}/train.jsonl", "w") as f:+ for r in out_rows: f.write(json.dumps(r, ensure_ascii=False) + "\n")+os.system(f"cp /wekafs/ict/hx_624/llm-ft/data/md_mixed/val.jsonl {out}/val.jsonl")+tot = sum(v[1] for v in stats.values())+print({k: (v[0], round(v[1]/1e6, 1)) for k, v in stats.items()}, "| total samples", len(out_rows), "| tokens/epoch %.1fM" % (tot/1e6))diff --git a/finetune/scripts/build_md_max.py b/finetune/scripts/build_md_max.pynew file mode 100644index 00000000..78937983--- /dev/null+++ b/finetune/scripts/build_md_max.py@@ -0,0 +1,242 @@+"""md_max: use EVERY usable 3DCodeVerse sample, with multi-caption prompt expansion (~0.5M prompt→code pairs).++Sources (all parquet metadata + the distilled file trees):+ blender bioinspired3d geo+tex, 3dcodebench factories (test factories removed), blender_distill (*.py)+ cadquery deepcad v1..v1_4, articraft cadquery_single_tex*+ openscad thingiverse/openscad+ glsl shadertoy (112 shards)+ threejs threejs_distill (*.html)+ web animation2code (*.html) — new: animated web/3D pages++Deliberately excluded and why:+ 3dcodebench/instances_* (3904) 100% of them are re-seeded instances of the 212 benchmark factories → test leakage+ articraft/urdf_* (6146) `code` column is empty in the metadata (URDF lives inside the 51 GB tars) and we have no URDF executor+ threejs_repos multi-file projects, not single-file prompt→code+ every id in data/multidialect/*/test.jsonl and the 212 3DCodeBench task names++Each sample yields up to 3 training pairs (captions: instruction / detailed / factory), deduped by (prompt, code).+Token length is estimated as tokens(code) + tokens(prompt) + template overhead, tokenizing each unique code/prompt once.++usage: python scripts/build_md_max.py [--max_tokens 8192] [--captions 3] [--out data/md_max]+"""+import argparse+import glob+import hashlib+import json+import os+import random+import re+import sys+import unicodedata+from concurrent.futures import ProcessPoolExecutor++import pandas as pd++sys.path.insert(0, "/wekafs/ict/hx_624/llm-ft/scripts")+META = "/wekafs/ict/hx_624/data/3dcodeverse_meta"+FILES = "/wekafs/ict/hx_624/data/3dcodeverse_files"+MD = "/wekafs/ict/hx_624/llm-ft/data/multidialect"+BENCH_DIR = "/wekafs/ict/hx_624/data/3dcodebench/data"++SYS = {+ "blender": "You are an expert in procedural 3D modeling with Blender Python (bpy). Given a description of an object, write a complete, standalone Blender 5 Python script that builds it from scratch (clear the default scene first). Output ONLY the code in one ```python block.",+ "cadquery": "You are an expert CAD programmer. Given a description of a part, write a complete, standalone CadQuery (Python) script that builds it and leaves the final solid in a variable named `result`. Output ONLY the code in one ```python block.",+ "openscad": "You are an expert OpenSCAD programmer. Given a request, write a complete, standalone OpenSCAD (.scad) program that produces the described model. Output ONLY the code in one ```openscad block.",+ "glsl": "You are an expert shader programmer. Given a description, write a complete Shadertoy-style GLSL ES 3.00 fragment shader defining `void mainImage(out vec4 fragColor, in vec2 fragCoord)`. Output ONLY the code in one ```glsl block.",+ "threejs": "You are an expert three.js developer. Given a description, write a complete, standalone HTML page that renders the described 3D scene with three.js (import three from a CDN-style module URL, create a renderer/camera/lights, and animate). Output ONLY the code in one ```html block.",+ "web": "You are an expert creative web developer. Given a description of an animation, write a complete, standalone HTML page (inline CSS/JS, no local assets) that reproduces it. Output ONLY the code in one ```html block.",+}+FENCE = {"blender": "python", "cadquery": "python", "openscad": "openscad", "glsl": "glsl", "threejs": "html", "web": "html"}+LEAD = { # how to phrase a bare description as a request, per dialect+ "blender": "Create the 3D object described below using Python Blender code: ",+ "cadquery": "Write a CadQuery (Python) script that builds the following CAD model: ",+ "openscad": "Write an OpenSCAD program for the following: ",+ "glsl": "Write a GLSL fragment shader for Shadertoy that renders: ",+ "threejs": "Write a standalone three.js page that renders: ",+ "web": "Write a standalone animated web page that reproduces: ",+}+IMPERATIVE = ("write", "create", "implement", "make", "build", "generate", "design", "produce")+++def bad_chars(s):+ return sum(1 for ch in s if unicodedata.category(ch) == "Cc" and ch not in "\n\t\r") + s.count("�")+++def phrase(dialect, kind, text):+ t = (text or "").strip()+ if not t:+ return None+ if kind == "instruction" and t.lower().startswith(IMPERATIVE):+ return t+ return LEAD[dialect] + t+++def load_parquet_rows(dialect, sub, drop_names=frozenset()):+ p = f"{META}/{sub}/metadata.parquet"+ if not os.path.exists(p):+ return []+ df = pd.read_parquet(p)+ out = []+ for r in df.itertuples():+ name = str(getattr(r, "name", "") or "")+ if name in drop_names or name.rsplit("_", 1)[0] in drop_names:+ continue+ code = getattr(r, "code", None) or ""+ if not isinstance(code, str) or len(code.strip()) < 40:+ continue+ caps = r.captions if isinstance(r.captions, dict) else (json.loads(r.captions) if isinstance(r.captions, str) else {})+ out.append({"dialect": dialect, "subset": sub, "id": str(r.id), "name": name, "code": code, "caps": dict(caps)})+ return out+++def load_tree_rows(dialect, root, code_glob):+ """distill / animation2code trees: <sample>/{code.py|code.html|index.html} + captions.json"""+ rows = []+ for cp in glob.glob(f"{FILES}/{root}/{code_glob}", recursive=True):+ d = os.path.dirname(cp)+ capp = os.path.join(d, "captions.json")+ try:+ code = open(cp, encoding="utf-8", errors="replace").read()+ caps = json.load(open(capp)) if os.path.exists(capp) else {}+ except Exception:+ continue+ if len(code.strip()) < 40:+ continue+ rid = f"{root}/{os.path.relpath(d, f'{FILES}/{root}')}"+ caps = {k: v for k, v in caps.items() if isinstance(v, str) and v.strip()}+ # tree sources use their own caption keys -> map onto instruction/detailed+ norm = {}+ if caps.get("user_instruction"): norm["instruction"] = caps["user_instruction"] # imperative request+ if caps.get("instruction"): norm["detailed"] = caps["instruction"] # description+ if caps.get("brief"): # animation2code+ extra = caps.get("function", "")+ norm["instruction"] = (caps["brief"] + ((" — " + extra) if extra and extra not in caps["brief"] else "")).strip()+ if caps.get("source_title") and "detailed" not in norm: norm["detailed"] = caps["source_title"]+ if caps.get("style") and norm.get("detailed"): norm["detailed"] += f" (style: {caps['style']})"+ rows.append({"dialect": dialect, "subset": root, "id": rid, "name": os.path.basename(d), "code": code, "caps": norm or caps})+ return rows+++_TOK = None+++def _init_tok():+ global _TOK+ from transformers import AutoTokenizer+ _TOK = AutoTokenizer.from_pretrained("/wekafs/ict/hx_624/models/Qwen3.5-9B")+++def _ntok(s):+ return len(_TOK(s).input_ids)+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--max_tokens", type=int, default=8192)+ ap.add_argument("--captions", type=int, default=3, help="max prompt variants per sample")+ ap.add_argument("--out", default="/wekafs/ict/hx_624/llm-ft/data/md_max")+ ap.add_argument("--workers", type=int, default=16)+ a = ap.parse_args()+ random.seed(17)++ bench_factories = {os.path.basename(p).replace("_seed0", "") for p in glob.glob(f"{BENCH_DIR}/*_seed0")}+ held_out = set()+ for f in glob.glob(f"{MD}/*/test.jsonl"):+ for l in open(f):+ held_out.add(json.loads(l)["id"])+ print(f"[md_max] excluding {len(bench_factories)} benchmark factories and {len(held_out)} held-out test ids", flush=True)++ samples = []+ for sub in ["bioinspired3d/bpy_structures_geo", "bioinspired3d/bpy_structures_tex", "3dcodebench/factories_geo", "3dcodebench/factories_tex"]:+ samples += load_parquet_rows("blender", sub, bench_factories)+ for sub in sorted(glob.glob(f"{META}/deepcad/*/metadata.parquet")) + sorted(glob.glob(f"{META}/articraft/cadquery_single_tex*/metadata.parquet")):+ samples += load_parquet_rows("cadquery", "/".join(sub.split("/")[-3:-1]))+ samples += load_parquet_rows("openscad", "thingiverse/openscad")+ for sub in sorted(glob.glob(f"{META}/shadertoy/*/metadata.parquet")):+ samples += load_parquet_rows("glsl", "/".join(sub.split("/")[-3:-1]))+ samples += load_tree_rows("blender", "blender_distill", "*/*/code.py")+ samples += load_tree_rows("threejs", "threejs_distill", "*/*/code.html")+ samples += load_tree_rows("web", "animation2code", "*/*/index.html")+ samples = [s for s in samples if s["id"] not in held_out]+ print(f"[md_max] samples after source load: {len(samples)}", flush=True)++ # build (prompt, code) pairs from up to N caption variants+ pairs, seen = [], set()+ for s in samples:+ code = s["code"]+ if bad_chars(code) > 5:+ continue+ used = 0+ for kind in ("instruction", "detailed", "factory"):+ if used >= a.captions:+ break+ p = phrase(s["dialect"], kind, s["caps"].get(kind))+ if not p or len(p) < 20:+ continue+ h = hashlib.md5((p[:400] + "|" + code[:400]).encode()).hexdigest()+ if h in seen:+ continue+ seen.add(h)+ pairs.append({"dialect": s["dialect"], "subset": s["subset"], "id": s["id"], "caption": kind, "prompt": p, "code": code})+ used += 1+ print(f"[md_max] prompt-code pairs before length filter: {len(pairs)}", flush=True)++ # length: tokenize each unique code and prompt once+ ucode = {}+ uprompt = {}+ for p in pairs:+ ucode.setdefault(p["code"], None)+ uprompt.setdefault(p["prompt"], None)+ cache_path = "/wekafs/ict/hx_624/llm-ft/data/md_max/.ntok_cache.json"+ cache = {}+ if os.path.exists(cache_path):+ try: cache = json.load(open(cache_path))+ except Exception: cache = {}+ def _key(x): return hashlib.md5(x.encode()).hexdigest()+ for store in (ucode, uprompt):+ for k in list(store):+ v = cache.get(_key(k))+ if v is not None: store[k] = v+ codes = [k for k, v in ucode.items() if v is None]; prompts = [k for k, v in uprompt.items() if v is None]+ print(f"[md_max] tokenizing {len(codes)} unique codes + {len(prompts)} unique prompts on {a.workers} procs", flush=True)+ with ProcessPoolExecutor(a.workers, initializer=_init_tok) as ex:+ for k, n in zip(codes, ex.map(_ntok, codes, chunksize=64)):+ ucode[k] = n+ for k, n in zip(prompts, ex.map(_ntok, prompts, chunksize=256)):+ uprompt[k] = n+ os.makedirs(os.path.dirname(cache_path), exist_ok=True)+ json.dump({_key(k): v for store in (ucode, uprompt) for k, v in store.items()}, open(cache_path, "w"))++ OVERHEAD = 60 # chat template + system prompt + fence+ keep, stats = [], {}+ for p in pairs:+ n = ucode[p["code"]] + uprompt[p["prompt"]] + OVERHEAD+ if n > a.max_tokens:+ continue+ p["ntok"] = n+ keep.append(p)+ d = stats.setdefault(p["dialect"], {"n": 0, "tok": 0, "by_caption": {}})+ d["n"] += 1+ d["tok"] += n+ d["by_caption"][p["caption"]] = d["by_caption"].get(p["caption"], 0) + 1+ random.shuffle(keep)++ os.makedirs(a.out, exist_ok=True)+ val = keep[:600]+ train = keep[600:]+ for split, rows in (("train", train), ("val", val)):+ with open(f"{a.out}/{split}.jsonl", "w") as f:+ for p in rows:+ msgs = [{"role": "system", "content": SYS[p["dialect"]]},+ {"role": "user", "content": p["prompt"]},+ {"role": "assistant", "content": f"```{FENCE[p['dialect']]}\n{p['code'].strip()}\n```"}]+ f.write(json.dumps({"id": p["id"], "dialect": p["dialect"], "subset": p["subset"], "caption": p["caption"], "messages": msgs}, ensure_ascii=False) + "\n")+ tot_tok = sum(v["tok"] for v in stats.values())+ report = {"pairs_kept": len(keep), "tokens": tot_tok, "by_dialect": {k: {"n": v["n"], "Mtok": round(v["tok"] / 1e6, 1), "by_caption": v["by_caption"]} for k, v in sorted(stats.items(), key=lambda x: -x[1]["n"])}}+ json.dump(report, open(f"{a.out}/report.json", "w"), indent=2)+ print(json.dumps(report["by_dialect"], indent=1))+ print(f"[md_max] total samples {len(keep)} | tokens/epoch {tot_tok/1e6:.1f}M | train {len(train)} val {len(val)}", flush=True)+++if __name__ == "__main__":+ main()diff --git a/finetune/scripts/run_27b.sh b/finetune/scripts/run_27b.shnew file mode 100755index 00000000..3c4d30d7--- /dev/null+++ b/finetune/scripts/run_27b.sh@@ -0,0 +1,24 @@+#!/bin/bash+# 27B pipeline: wait for free GPUs -> ZeRO-3 LoRA smoke test -> full train -> merge -> eval_all (TP=2) on all six suites+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft+echo "[27b] $(date) waiting for GPUs 0-3 to be free"+until [ "$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i 0,1,2,3 | sort -n | tail -1)" -lt 8000 ]; do sleep 60; done # all four idle+echo "[27b] $(date) ZeRO-3 smoke test (6 steps, 4 GPUs)"+GPUS=0,1,2,3 scripts/lf_train.sh configs/lf/lora_27b_md_z3.yaml max_steps=6 save_steps=100000 eval_steps=100000 \+ output_dir=/wekafs/ict/hx_624/llm-ft/runs/_smoke_27b_z3 > logs/smoke_27b_z3.log 2>&1+if ! grep -q "train_runtime" logs/smoke_27b_z3.log; then+ echo "[27b] SMOKE FAILED: $(grep -E 'OutOfMemoryError|RuntimeError|Error' logs/smoke_27b_z3.log | grep -v errors | tail -1 | cut -c1-200)"; exit 1+fi+echo "[27b] smoke ok: $(grep -oE "'train_runtime': [0-9.]+" logs/smoke_27b_z3.log | tail -1)"; rm -rf runs/_smoke_27b_z3+echo "[27b] $(date) full LoRA train (md_27b_max: 78k pairs / 67.6M tok, 6 dialects)"+GPUS=0,1,2,3 scripts/lf_train.sh configs/lf/lora_27b_md_z3.yaml > logs/train_27b_max.log 2>&1+RUN=runs/lf_qwen38_27b_lora_md_max+[ -f $RUN/train_results.json ] || { echo "[27b] TRAIN FAILED: $(grep -E 'Error|OutOfMemory' logs/train_27b_max.log | grep -v errors | tail -1 | cut -c1-200)"; exit 1; }+echo "[27b] $(date) train done: $(tr -d '\n' < $RUN/train_results.json | cut -c1-200)"+sed -e "s|model_name_or_path:.*|model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.8-27B|" \+ -e "s|adapter_name_or_path:.*|adapter_name_or_path: $(readlink -f $RUN)|" \+ -e "s|export_dir:.*|export_dir: $(readlink -f $RUN)/merged|" configs/lf/export_lora_template.yaml > configs/lf/export_27b_max.yaml+scripts/lf_export.sh configs/lf/export_27b_max.yaml > logs/export_27b_max.log 2>&1 || { echo "[27b] EXPORT FAILED"; exit 1; }+echo "[27b] $(date) eval tuned model (TP=2, GPUs 0,1)"+GPUS=0,1 TP=2 eval/eval_all.sh $RUN/merged q27b_ft --max_new 8192 2>&1 | grep -E "gen-multi|extract\]|status counts|dialect|DONE" | tail -30+echo "[27b] ALL DONE"diff --git a/finetune/scripts/run_27b_think32k.sh b/finetune/scripts/run_27b_think32k.shnew file mode 100755index 00000000..80726ebb--- /dev/null+++ b/finetune/scripts/run_27b_think32k.sh@@ -0,0 +1,12 @@+#!/bin/bash+# Fair-budget rerun: 27B with thinking ON but a 32k output budget on 3DCodeBench (the 12k run truncated 204/212).+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft+until grep -qE "\[9bmax\] (ALL DONE|TRAIN FAILED|EXPORT FAILED)" logs/run_md_max_9b.log 2>/dev/null; do sleep 120; done+until [ "$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i 0,1 | sort -n | tail -1)" -lt 8000 ]; do sleep 60; done+echo "[27b32k] $(date) bench with thinking, 32k budget"+source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate vllm+export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING CUDA_VISIBLE_DEVICES=0,1+python eval/generate_multi.py --model /wekafs/ict/hx_624/models/Qwen3.8-27B --tp 2 --max_new_tokens 30000 --max_model_len 34816 \+ --spec '[{"name":"bench","prompts":"data/sft_v1/bench_prompts.jsonl","out":"eval/out/q27b_think32k_bench","dialect":"blender"}]' 2>&1 | grep -E "gen-multi|extract\]" | tail -3+conda activate llmft; eval/exec_suites.sh q27b_think32k bench+echo "[27b32k] DONE"diff --git a/finetune/scripts/run_27b_v2.sh b/finetune/scripts/run_27b_v2.shnew file mode 100755index 00000000..2d3121f8--- /dev/null+++ b/finetune/scripts/run_27b_v2.sh@@ -0,0 +1,15 @@+#!/bin/bash+# 27B six-dialect LoRA, DDP @ cutoff 4096 (ZeRO-3 was 7.8x slower), then merge + full eval+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft+echo "[27b] $(date) LoRA DDP train (md_27b_max4k, ~64M tok, 4 GPUs, ~5 h)"+GPUS=0,1,2,3 scripts/lf_train.sh configs/lf/lora_27b_ddp.yaml > logs/train_27b_ddp.log 2>&1+RUN=runs/lf_qwen38_27b_lora_md_max+[ -f $RUN/train_results.json ] || { echo "[27b] TRAIN FAILED: $(grep -E 'OutOfMemory|Error' logs/train_27b_ddp.log | grep -v errors | tail -1 | cut -c1-200)"; exit 1; }+echo "[27b] $(date) train done: $(tr -d '\n' < $RUN/train_results.json | cut -c1-200)"+sed -e "s|model_name_or_path:.*|model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.8-27B|" \+ -e "s|adapter_name_or_path:.*|adapter_name_or_path: $(readlink -f $RUN)|" \+ -e "s|export_dir:.*|export_dir: $(readlink -f $RUN)/merged|" configs/lf/export_lora_template.yaml > configs/lf/export_27b_max.yaml+scripts/lf_export.sh configs/lf/export_27b_max.yaml > logs/export_27b_max.log 2>&1 || { echo "[27b] EXPORT FAILED"; exit 1; }+echo "[27b] $(date) eval tuned 27B (TP=2)"+GPUS=0,1 TP=2 eval/eval_all_run2.sh $RUN/merged q27b_ft --max_new 8192 2>&1 | grep -E "gen-multi|extract\]|status counts|dialect|DONE" | tail -30+echo "[27b] ALL DONE"diff --git a/finetune/scripts/run_md_max_9b.sh b/finetune/scripts/run_md_max_9b.shnew file mode 100755index 00000000..bff9edc9--- /dev/null+++ b/finetune/scripts/run_md_max_9b.sh@@ -0,0 +1,15 @@+#!/bin/bash+# After the 27B pipeline: 9B on the caption-augmented full corpus at the SAME token budget as md_xl (~300M)+# -> answers "does using ALL sources + 3 captions/sample beat 270k single-caption pairs at equal compute?"+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft+until grep -qE "\[27b\] (ALL DONE|TRAIN FAILED|SMOKE FAILED|EXPORT FAILED)" logs/run_27b.log 2>/dev/null; do sleep 120; done+until [ "$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i 0,1,2,3 | sort -n | tail -1)" -lt 8000 ]; do sleep 60; done+echo "[9bmax] $(date) train 9B on md_max_9b (364k pairs / ~304M tok, 6 dialects, 3 captions/sample)"+GPUS=0,1,2,3 scripts/lf_train.sh configs/lf/lora_md_max_9b.yaml > logs/train_md_max_9b.log 2>&1+RUN=runs/lf_qwen35_9b_lora_md_max+[ -f $RUN/train_results.json ] || { echo "[9bmax] TRAIN FAILED"; exit 1; }+echo "[9bmax] $(date) train done: $(tr -d '\n' < $RUN/train_results.json | cut -c1-200)"+sed -e "s|model_name_or_path:.*|model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.5-9B|" -e "s|adapter_name_or_path:.*|adapter_name_or_path: $(readlink -f $RUN)|" -e "s|export_dir:.*|export_dir: $(readlink -f $RUN)/merged|" configs/lf/export_lora_template.yaml > configs/lf/export_md_max_9b.yaml+scripts/lf_export.sh configs/lf/export_md_max_9b.yaml > logs/export_md_max_9b.log 2>&1 || { echo "[9bmax] EXPORT FAILED"; exit 1; }+GPUS=0 TP=1 eval/eval_all_run2.sh $RUN/merged q9b_md_max --max_new 8192 2>&1 | grep -E "gen-multi|extract\]|status counts|dialect|DONE" | tail -30+echo "[9bmax] ALL DONE"diff --git a/finetune/scripts/sample_mix.py b/finetune/scripts/sample_mix.pynew file mode 100644index 00000000..548d8489--- /dev/null+++ b/finetune/scripts/sample_mix.py@@ -0,0 +1,80 @@+"""Sample a training mix out of the md_max corpus with a per-dialect TOKEN budget.++md_max is ~0.77M pairs / ~0.9B tokens and 97% CadQuery+GLSL; every real run wants a different slice of it.++ python scripts/sample_mix.py --out data/md_27b_max \+ --budget blender=all,openscad=all,threejs=all,web=all,cadquery=25M,glsl=25M \+ [--src data/md_max] [--captions_per_sample 2] [--seed 5]++--captions_per_sample caps how many prompt variants of the SAME code may be kept (1 = no augmentation,+2 = instruction+detailed, 3 = everything) so you can ablate caption augmentation at a fixed token budget.+"""+import argparse+import collections+import json+import os+import random+++def parse_budget(s):+ out = {}+ for part in s.split(","):+ if not part.strip():+ continue+ k, v = part.split("=")+ v = v.strip().lower()+ out[k.strip()] = None if v == "all" else int(float(v.rstrip("mk")) * (1e6 if v.endswith("m") else 1e3 if v.endswith("k") else 1))+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--src", default="/wekafs/ict/hx_624/llm-ft/data/md_max")+ ap.add_argument("--out", required=True)+ ap.add_argument("--budget", required=True, help="dialect=tokens|all, comma separated")+ ap.add_argument("--captions_per_sample", type=int, default=3)+ ap.add_argument("--seed", type=int, default=5)+ a = ap.parse_args()+ random.seed(a.seed)+ budget = parse_budget(a.budget)++ rows = [json.loads(l) for l in open(f"{a.src}/train.jsonl")]+ # estimate tokens per row: chars/3.4 is close enough for budgeting (exact counts live in md_max/report.json)+ for r in rows:+ r["_ntok"] = int(sum(len(m["content"]) for m in r["messages"]) / 3.4)+ by = collections.defaultdict(list)+ for r in rows:+ by[r["dialect"]].append(r)++ kept, stats = [], {}+ for dia, pool in by.items():+ if dia not in budget:+ continue+ random.shuffle(pool)+ per_sample = collections.Counter()+ take, tok = [], 0+ for r in pool:+ if per_sample[r["id"]] >= a.captions_per_sample:+ continue+ if budget[dia] is not None and tok + r["_ntok"] > budget[dia]:+ continue+ per_sample[r["id"]] += 1+ take.append(r)+ tok += r["_ntok"]+ if budget[dia] is not None and tok >= budget[dia]:+ break+ kept += take+ stats[dia] = {"n": len(take), "Mtok_est": round(tok / 1e6, 1), "uniq_samples": len(per_sample)}+ random.shuffle(kept)+ os.makedirs(a.out, exist_ok=True)+ with open(f"{a.out}/train.jsonl", "w") as f:+ for r in kept:+ f.write(json.dumps({k: v for k, v in r.items() if k != "_ntok"}, ensure_ascii=False) + "\n")+ os.system(f"cp {a.src}/val.jsonl {a.out}/val.jsonl")+ json.dump(stats, open(f"{a.out}/mix.json", "w"), indent=2)+ print(json.dumps(stats, indent=1))+ print(f"[mix] {len(kept)} pairs | ~{sum(v['Mtok_est'] for v in stats.values()):.1f}M tokens -> {a.out}")+++if __name__ == "__main__":+ main()diff --git a/finetune/scripts/smoke_27b.sh b/finetune/scripts/smoke_27b.shnew file mode 100755index 00000000..e10005c4--- /dev/null+++ b/finetune/scripts/smoke_27b.sh@@ -0,0 +1,13 @@+#!/bin/bash+# 8-step smoke test of a 27B LoRA config to pick DDP vs ZeRO-3 before committing hours+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft; CFG=$1; TAG=$2+GPUS=0,1,2,3 scripts/lf_train.sh $CFG max_steps=8 num_train_epochs=1.0 save_steps=100000 eval_steps=100000 \+ tokenized_path=/wekafs/ict/hx_624/llm-ft/data/lf/tokenized_md_27b_len8192_packed \+ output_dir=/wekafs/ict/hx_624/llm-ft/runs/_smoke_$TAG > logs/smoke_$TAG.log 2>&1+if grep -q "train_runtime" logs/smoke_$TAG.log; then+ echo "[smoke $TAG] OK $(grep -oE '[0-9]+/8 \[[0-9:]+<[0-9:]+, *[0-9.]+s/it' logs/smoke_$TAG.log | tail -1)"+ grep -oE "'train_runtime': [0-9.]+" logs/smoke_$TAG.log | tail -1+else+ echo "[smoke $TAG] FAILED: $(grep -E 'OutOfMemoryError|Error|RuntimeError' logs/smoke_$TAG.log | grep -v errors | tail -1 | cut -c1-160)"+fi+rm -rf runs/_smoke_$TAG