Skip to content

Official Codebase of 3DCodeVerse

Python

eval: the OpenSCAD collapse was greedy decoding, not a forgotten dialect

gaoypeng38a050fd1ac9
diff --git a/finetune/configs/lf/dpo_stop.yaml b/finetune/configs/lf/dpo_stop.yaml
new file mode 100644
index 00000000..fe0a66ae
--- /dev/null
+++ b/finetune/configs/lf/dpo_stop.yaml
@@ -0,0 +1,42 @@
+### DPO with execution-feedback preference pairs, on top of LoRA-v1 (merged)
+model_name_or_path: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mmmix2/merged
+trust_remote_code: true
+flash_attn: fa2
+stage: dpo
+do_train: true
+finetuning_type: lora
+lora_rank: 16
+lora_alpha: 32
+lora_dropout: 0.05
+lora_target: all
+freeze_vision_tower: true
+freeze_multi_modal_projector: true
+pref_beta: 0.1
+pref_loss: sigmoid
+dataset_dir: /wekafs/ict/hx_624/llm-ft/data/lf
+dataset: stop_dpo_pairs
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 4096
+preprocessing_num_workers: 16
+dataloader_num_workers: 2
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_stopdpo
+logging_steps: 5
+save_steps: 1000
+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: 5.0e-6
+num_train_epochs: 2.0
+lr_scheduler_type: cosine
+warmup_ratio: 0.1
+bf16: true
+gradient_checkpointing: true
+ddp_timeout: 180000000
+val_size: 0.02
+per_device_eval_batch_size: 1
+eval_strategy: steps
+eval_steps: 100
diff --git a/finetune/configs/lf/export_27b_mm.yaml b/finetune/configs/lf/export_27b_mm.yaml
new file mode 100644
index 00000000..c51bf103
--- /dev/null
+++ b/finetune/configs/lf/export_27b_mm.yaml
@@ -0,0 +1,12 @@
+### Merge a LoRA adapter into the base model (LLaMA-Factory): llamafactory-cli export <this file>
+model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.8-27B
+adapter_name_or_path: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen38_27b_mm_img_text
+template: qwen3_5
+enable_thinking: false
+trust_remote_code: true
+finetuning_type: lora
+
+export_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen38_27b_mm_img_text/merged
+export_size: 5
+export_device: cpu
+export_legacy_format: false
diff --git a/finetune/configs/lf/export_9b_mm1_img_text.yaml b/finetune/configs/lf/export_9b_mm1_img_text.yaml
new file mode 100644
index 00000000..979754c1
--- /dev/null
+++ b/finetune/configs/lf/export_9b_mm1_img_text.yaml
@@ -0,0 +1,12 @@
+### Merge a LoRA adapter into the base model (LLaMA-Factory): llamafactory-cli export <this file>
+model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.5-9B
+adapter_name_or_path: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mm1_img_text
+template: qwen3_5
+enable_thinking: false
+trust_remote_code: true
+finetuning_type: lora
+
+export_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mm1_img_text/merged
+export_size: 5
+export_device: cpu
+export_legacy_format: false
diff --git a/finetune/configs/lf/export_bal_lr1e4.yaml b/finetune/configs/lf/export_bal_lr1e4.yaml
new file mode 100644
index 00000000..7e91da3c
--- /dev/null
+++ b/finetune/configs/lf/export_bal_lr1e4.yaml
@@ -0,0 +1,12 @@
+### Merge a LoRA adapter into the base model (LLaMA-Factory): llamafactory-cli export <this file>
+model_name_or_path: /wekafs/ict/hx_624/models/Qwen3.5-9B
+adapter_name_or_path: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_bal_lr1e4
+template: qwen3_5
+enable_thinking: false
+trust_remote_code: true
+finetuning_type: lora
+
+export_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_bal_lr1e4/merged
+export_size: 5
+export_device: cpu
+export_legacy_format: false
diff --git a/finetune/configs/lf/lora_9b_bal_lr1e4.yaml b/finetune/configs/lf/lora_9b_bal_lr1e4.yaml
new file mode 100644
index 00000000..29ae6077
--- /dev/null
+++ b/finetune/configs/lf/lora_9b_bal_lr1e4.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_bal9b_hard_train
+eval_dataset: md_bal9b_hard_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/tok_bal9b_hard
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_bal_lr1e4
+logging_steps: 5
+save_steps: 300
+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: 300
+save_total_limit: 3
diff --git a/finetune/configs/lf/lora_9b_bal_lr3e5.yaml b/finetune/configs/lf/lora_9b_bal_lr3e5.yaml
new file mode 100644
index 00000000..2331cf6f
--- /dev/null
+++ b/finetune/configs/lf/lora_9b_bal_lr3e5.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_bal9b_hard_train
+eval_dataset: md_bal9b_hard_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/tok_bal9b_hard
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_bal_lr3e5
+logging_steps: 5
+save_steps: 300
+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.00003
+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: 300
+save_total_limit: 3
diff --git a/finetune/data_specs/dataset_info.json b/finetune/data_specs/dataset_info.json
index d204a8f9..dad0b3ff 100644
--- a/finetune/data_specs/dataset_info.json
+++ b/finetune/data_specs/dataset_info.json
@@ -571,5 +571,32 @@
"messages": "conversations",
"system": "system"
}
+ },
+ "md_bal9b_hard_train": {
+ "file_name": "md_bal9b_hard_train.json",
+ "formatting": "sharegpt",
+ "columns": {
+ "messages": "conversations",
+ "system": "system"
+ }
+ },
+ "md_bal9b_hard_val": {
+ "file_name": "md_bal9b_hard_val.json",
+ "formatting": "sharegpt",
+ "columns": {
+ "messages": "conversations",
+ "system": "system"
+ }
+ },
+ "stop_dpo_pairs": {
+ "file_name": "stop_dpo_pairs.json",
+ "ranking": true,
+ "formatting": "sharegpt",
+ "columns": {
+ "messages": "conversations",
+ "system": "system",
+ "chosen": "chosen",
+ "rejected": "rejected"
+ }
}
}
\ No newline at end of file
diff --git a/finetune/eval/generate_multi.py b/finetune/eval/generate_multi.py
index eb971149..db6f08f8 100644
--- a/finetune/eval/generate_multi.py
+++ b/finetune/eval/generate_multi.py
@@ -17,12 +17,17 @@ from extract import extract, summarize
-def auto_gpu_mem(requested, tp=1, headroom_gib=4.0):
+def auto_gpu_mem(requested, tp=1, headroom_gib=4.0, model_dir=None):
"""`gpu_memory_utilization` is a fraction of the card's TOTAL memory, but this box is shared — asking for
- 0.88 of a card that another user already half fills makes vLLM refuse to start. Derive the fraction from what
- is actually free, keeping a little headroom, and never exceed what the caller asked for."""
+ 0.88 of a card that another user already half fills makes vLLM refuse to start, and asking for exactly what
+ is free makes its KV-cache profiling OOM instead. Derive the fraction from what is actually free, and scale
+ the headroom with the model: a 51 GB checkpoint needs far more slack than a 18 GB one."""
try:
- import subprocess
+ import subprocess, glob, os
+ if model_dir and os.path.isdir(model_dir):
+ gib = sum(os.path.getsize(f) for f in glob.glob(os.path.join(model_dir, "*.safetensors"))) / 1024**3
+ if gib > 30:
+ headroom_gib = max(headroom_gib, 10.0)
out = subprocess.run(["nvidia-smi", "--query-gpu=memory.total,memory.used", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=30).stdout.strip().splitlines()
vis = os.environ.get("CUDA_VISIBLE_DEVICES", "")
@@ -33,7 +38,7 @@ def auto_gpu_mem(requested, tp=1, headroom_gib=4.0):
free_gib = (tot - used) / 1024.0
worst = min(worst, max(0.10, (free_gib - headroom_gib) / (tot / 1024.0)))
if worst < requested:
- print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (the card is shared)", flush=True)
+ print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (shared card, {headroom_gib:.0f} GiB headroom)", flush=True)
return round(worst, 2)
except Exception as e:
print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
@@ -51,6 +56,9 @@ def main():
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)
+ # Qwen3.5/3.8 carry linear-attention layers and vLLM needs one Mamba cache block per concurrent sequence;
+ # the default 1024 exceeds the blocks a 27B leaves free and the engine refuses to start
+ ap.add_argument("--max_num_seqs", type=int, default=None)
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)
@@ -58,8 +66,9 @@ def main():
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=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1)), enable_prefix_caching=True,
- limit_mm_per_prompt={"image": 0, "video": 0}, trust_remote_code=True)
+ gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1), model_dir=a.model), enable_prefix_caching=True,
+ limit_mm_per_prompt={"image": 0, "video": 0}, trust_remote_code=True,
+ **({"max_num_seqs": a.max_num_seqs} if a.max_num_seqs else {}))
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)
diff --git a/finetune/eval/generate_vllm.py b/finetune/eval/generate_vllm.py
index 27e43ad7..d0593ba9 100644
--- a/finetune/eval/generate_vllm.py
+++ b/finetune/eval/generate_vllm.py
@@ -5,12 +5,17 @@ from generate import extract_code as extract_code_legacy
from extract import extract, summarize
-def auto_gpu_mem(requested, tp=1, headroom_gib=4.0):
+def auto_gpu_mem(requested, tp=1, headroom_gib=4.0, model_dir=None):
"""`gpu_memory_utilization` is a fraction of the card's TOTAL memory, but this box is shared — asking for
- 0.88 of a card that another user already half fills makes vLLM refuse to start. Derive the fraction from what
- is actually free, keeping a little headroom, and never exceed what the caller asked for."""
+ 0.88 of a card that another user already half fills makes vLLM refuse to start, and asking for exactly what
+ is free makes its KV-cache profiling OOM instead. Derive the fraction from what is actually free, and scale
+ the headroom with the model: a 51 GB checkpoint needs far more slack than a 18 GB one."""
try:
- import subprocess
+ import subprocess, glob, os
+ if model_dir and os.path.isdir(model_dir):
+ gib = sum(os.path.getsize(f) for f in glob.glob(os.path.join(model_dir, "*.safetensors"))) / 1024**3
+ if gib > 30:
+ headroom_gib = max(headroom_gib, 10.0)
out = subprocess.run(["nvidia-smi", "--query-gpu=memory.total,memory.used", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=30).stdout.strip().splitlines()
vis = os.environ.get("CUDA_VISIBLE_DEVICES", "")
@@ -21,7 +26,7 @@ def auto_gpu_mem(requested, tp=1, headroom_gib=4.0):
free_gib = (tot - used) / 1024.0
worst = min(worst, max(0.10, (free_gib - headroom_gib) / (tot / 1024.0)))
if worst < requested:
- print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (the card is shared)", flush=True)
+ print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (shared card, {headroom_gib:.0f} GiB headroom)", flush=True)
return round(worst, 2)
except Exception as e:
print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
@@ -35,14 +40,18 @@ def main():
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)
+ ap.add_argument("--tp", type=int, default=1); ap.add_argument("--gpu_mem", type=float, default=0.88)
+ # Qwen3.5/3.8 carry linear-attention layers and vLLM needs one Mamba cache block per concurrent sequence;
+ # the default 1024 exceeds the blocks a 27B leaves free and the engine refuses to start
+ ap.add_argument("--max_num_seqs", type=int, default=None); 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
os.makedirs(a.out, exist_ok=True)
rows = [json.loads(l) for l in open(a.prompts)]
if a.limit: rows = rows[:a.limit]
- llm = LLM(model=a.model, dtype="bfloat16", tensor_parallel_size=a.tp, max_model_len=a.max_model_len, gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1)),
- enable_prefix_caching=True, limit_mm_per_prompt={"image": 0, "video": 0}, trust_remote_code=True)
+ llm = LLM(model=a.model, dtype="bfloat16", tensor_parallel_size=a.tp, max_model_len=a.max_model_len, gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1), model_dir=a.model),
+ enable_prefix_caching=True, limit_mm_per_prompt={"image": 0, "video": 0}, trust_remote_code=True,
+ **({"max_num_seqs": a.max_num_seqs} if a.max_num_seqs else {}))
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 {}
t0 = time.time()
diff --git a/finetune/eval/generate_vllm_img.py b/finetune/eval/generate_vllm_img.py
index a56141ea..123c682b 100644
--- a/finetune/eval/generate_vllm_img.py
+++ b/finetune/eval/generate_vllm_img.py
@@ -8,12 +8,17 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from extract import extract, summarize
-def auto_gpu_mem(requested, tp=1, headroom_gib=4.0):
+def auto_gpu_mem(requested, tp=1, headroom_gib=4.0, model_dir=None):
"""`gpu_memory_utilization` is a fraction of the card's TOTAL memory, but this box is shared — asking for
- 0.88 of a card that another user already half fills makes vLLM refuse to start. Derive the fraction from what
- is actually free, keeping a little headroom, and never exceed what the caller asked for."""
+ 0.88 of a card that another user already half fills makes vLLM refuse to start, and asking for exactly what
+ is free makes its KV-cache profiling OOM instead. Derive the fraction from what is actually free, and scale
+ the headroom with the model: a 51 GB checkpoint needs far more slack than a 18 GB one."""
try:
- import subprocess
+ import subprocess, glob, os
+ if model_dir and os.path.isdir(model_dir):
+ gib = sum(os.path.getsize(f) for f in glob.glob(os.path.join(model_dir, "*.safetensors"))) / 1024**3
+ if gib > 30:
+ headroom_gib = max(headroom_gib, 10.0)
out = subprocess.run(["nvidia-smi", "--query-gpu=memory.total,memory.used", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=30).stdout.strip().splitlines()
vis = os.environ.get("CUDA_VISIBLE_DEVICES", "")
@@ -24,7 +29,7 @@ def auto_gpu_mem(requested, tp=1, headroom_gib=4.0):
free_gib = (tot - used) / 1024.0
worst = min(worst, max(0.10, (free_gib - headroom_gib) / (tot / 1024.0)))
if worst < requested:
- print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (the card is shared)", flush=True)
+ print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (shared card, {headroom_gib:.0f} GiB headroom)", flush=True)
return round(worst, 2)
except Exception as e:
print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
@@ -37,6 +42,9 @@ def main():
ap.add_argument("--max_new_tokens", type=int, default=32768); 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("--tp", type=int, default=1); ap.add_argument("--gpu_mem", type=float, default=0.88)
+ # Qwen3.5/3.8 carry linear-attention layers and vLLM needs one Mamba cache block per concurrent sequence;
+ # the default 1024 exceeds the blocks a 27B leaves free and the engine refuses to start
+ ap.add_argument("--max_num_seqs", type=int, default=None)
ap.add_argument("--presence_penalty", type=float, default=0.0)
ap.add_argument("--repetition_penalty", type=float, default=1.0)
ap.add_argument("--dialect", default="blender"); ap.add_argument("--limit", type=int, default=None)
@@ -47,7 +55,8 @@ def main():
if a.limit: rows = rows[:a.limit]
os.makedirs(a.out, exist_ok=True)
llm = LLM(model=a.model, dtype="bfloat16", tensor_parallel_size=a.tp, max_model_len=a.max_model_len,
- gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1)), limit_mm_per_prompt={"image": 4, "video": 0}, trust_remote_code=True)
+ gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1), model_dir=a.model), limit_mm_per_prompt={"image": 4, "video": 0}, trust_remote_code=True,
+ **({"max_num_seqs": a.max_num_seqs} if a.max_num_seqs else {}))
sp = SamplingParams(temperature=a.temperature, top_p=0.95 if a.temperature > 0 else 1.0,
presence_penalty=a.presence_penalty, repetition_penalty=a.repetition_penalty,
max_tokens=a.max_new_tokens, seed=a.seed)
diff --git a/finetune/scripts/queue.txt b/finetune/scripts/queue.txt
index 3e1620da..4b2c169b 100644
--- a/finetune/scripts/queue.txt
+++ b/finetune/scripts/queue.txt
@@ -10,3 +10,5 @@ mm1_singleview|bash scripts/run_9b_mm1.sh
mmmix2_eval|bash scripts/run_mmmix2_eval.sh
noise_profile|bash scripts/run_noise_profile.sh
27b_mm_eval|bash scripts/run_27b_mm_eval.sh
+bal9b|bash scripts/run_9b_balanced.sh
+stopdpo_train|bash scripts/run_stop_dpo_train.sh
diff --git a/finetune/scripts/run_27b_mm_eval.sh b/finetune/scripts/run_27b_mm_eval.sh
index 439fd285..77a0928a 100755
--- a/finetune/scripts/run_27b_mm_eval.sh
+++ b/finetune/scripts/run_27b_mm_eval.sh
@@ -8,13 +8,16 @@ if [ ! -d $RUN/merged ]; then
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_mm.yaml
scripts/lf_export.sh configs/lf/export_27b_mm.yaml > logs/export_27b_mm.log 2>&1 || { echo "[27bmmeval] EXPORT FAILED"; exit 0; }
fi
-G=""; for _ in $(seq 1 60); do G=${GPUS:-$(scripts/free_gpus.sh 70000 | cut -d, -f1)}; [ -n "$G" ] && break; sleep 60; done
-[ -z "$G" ] && { echo "[27bmmeval] skipped: a 27B needs ~70 GB free and no card had it"; exit 0; }
+# 51 GB of weights will not sit on one shared card: single-GPU died in KV-cache profiling with 788 MB left.
+# Two-way tensor parallel puts 25.5 GB on each card, which fits what this box actually has free.
+G=${GPUS:-$(scripts/free_gpus.sh 45000 | cut -d, -f1,2)}
+TP=$(echo "$G" | awk -F, '{print NF}')
+[ -z "$G" ] || [ "$TP" -lt 2 ] && { echo "[27bmmeval] skipped: need two cards with 45 GB free, got [$G]"; exit 0; }
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=$G
OUT=eval/out/q27b_mm_img_text_bench; mkdir -p $OUT
python eval/generate_vllm_img.py --model $RUN/merged --prompts eval/out/_img4text_bench_prompts.jsonl --out $OUT \
- --max_new_tokens 32768 --max_model_len 40960 2>&1 | tail -1
+ --tp $TP --max_num_seqs 64 --max_new_tokens 32768 --max_model_len 40960 > logs/gen_27b_mm.log 2>&1; tail -3 logs/gen_27b_mm.log
N=$(ls $OUT | grep -vc extract_stats.json || true)
[ "${N:-0}" -lt 5 ] && { echo "[27bmmeval] GENERATION PRODUCED NOTHING — not scoring"; exit 0; }
conda activate llmft
diff --git a/finetune/scripts/run_9b_balanced.sh b/finetune/scripts/run_9b_balanced.sh
new file mode 100755
index 00000000..01153280
--- /dev/null
+++ b/finetune/scripts/run_9b_balanced.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+# Fine-tuning has been destroying two of the six dialects: the base 9B scores 46% on OpenSCAD and 77.5% on
+# three.js without thinking, and every fine-tune so far lands at 2-6% and 32-52%. The training mix is why they
+# were suspected -- OpenSCAD is 0.6% of it and three.js 0.2%, against CadQuery's 53.6% -- but every mix tried so
+# far, large or small, gave the same 2-6%. So this runs the same balanced data at two learning rates: if only the
+# ratio mattered, both recover; if drift from the base is what breaks them, only the low rate does.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+for TAG in lr1e4 lr3e5; do
+ RUN=runs/lf_qwen35_9b_bal_$TAG
+ G=""; for _ in $(seq 1 90); do G=${GPUS:-$(scripts/free_gpus.sh)}; [ -n "$G" ] && break; sleep 60; done
+ [ -z "$G" ] && { echo "[bal-$TAG] skipped: no GPU with room after 90 min"; continue; }
+ echo "[bal-$TAG] $(date) train on GPUs $G"
+ GPUS=$G scripts/lf_train.sh configs/lf/lora_9b_bal_$TAG.yaml > logs/train_bal_$TAG.log 2>&1
+ [ -f $RUN/train_results.json ] || { echo "[bal-$TAG] TRAIN FAILED: $(grep -iE 'out of memory|Error|Traceback' logs/train_bal_$TAG.log | grep -v errors | tail -1 | cut -c1-190)"; continue; }
+ echo "[bal-$TAG] train done: $(tr -d '\n' < $RUN/train_results.json | cut -c1-130)"
+ 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_bal_$TAG.yaml
+ scripts/lf_export.sh configs/lf/export_bal_$TAG.yaml > logs/export_bal_$TAG.log 2>&1 || { echo "[bal-$TAG] EXPORT FAILED"; continue; }
+ G1=""; for _ in $(seq 1 60); do G1=$(scripts/free_gpus.sh 40000 | cut -d, -f1); [ -n "$G1" ] && break; sleep 30; done
+ [ -z "$G1" ] && { echo "[bal-$TAG] eval skipped: no GPU with 40 GB free"; continue; }
+ echo "[bal-$TAG] $(date) six suites on GPU $G1"
+ # all six, because the point of this run is what happens to the dialects the earlier ones broke
+ GPUS=$G1 TP=1 bash eval/eval_all_run2.sh $RUN/merged q9b_bal_${TAG}_all 2>&1 | tail -12
+ echo "[bal-$TAG] DONE"
+done
+python - <<'PY'
+import json, os
+suites = ["bench", "blender", "cadquery", "openscad", "glsl", "threejs"]
+names = [("base (no-think)", "q9b_nothink"), ("mmmix2", "q9b_mmmix2_all"),
+ ("balanced lr1e-4", "q9b_bal_lr1e4_all"), ("balanced lr3e-5", "q9b_bal_lr3e5_all")]
+print(f" {'model':18s}" + "".join(f"{s[:8]:>9s}" for s in suites))
+for label, n in names:
+ p = f"eval/out/{n}_report.json"
+ if not os.path.exists(p):
+ print(f" {label:18s} (no report)"); continue
+ d = {s["suite"]: s["exec_rate"] * 100 for s in json.load(open(p))["suites"]}
+ print(f" {label:18s}" + "".join(f"{d[s]:9.1f}" if s in d else f"{'-':>9s}" for s in suites))
+PY
+echo "[bal] ALL DONE"
diff --git a/finetune/scripts/run_decoding_dialects.sh b/finetune/scripts/run_decoding_dialects.sh
new file mode 100755
index 00000000..098e2561
--- /dev/null
+++ b/finetune/scripts/run_decoding_dialects.sh
@@ -0,0 +1,29 @@
+#!/bin/bash
+# T=0.7 took the image-only model from 35.8% to 48.6% and cut unfinished generations from 93 to 21. Every
+# fine-tuned model's 2-6% on OpenSCAD and 32-52% on three.js was measured with GREEDY. If those collapses are the
+# same pathology, they are a decoding artifact and the training data was never the problem. Test it on the best
+# model we have before redesigning any mix.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+M=runs/lf_qwen35_9b_mmmix2/merged
+[ -d "$M" ] || { echo "[decdia] no model"; exit 0; }
+G=""; for _ in $(seq 1 60); do G=${GPUS:-$(scripts/free_gpus.sh 40000 | cut -d, -f1)}; [ -n "$G" ] && break; sleep 30; done
+[ -z "$G" ] && { echo "[decdia] no GPU with 40 GB free"; exit 0; }
+echo "[decdia] $(date) on GPU $G"
+# greedy numbers already exist as q9b_mmmix2_all; this adds the sampled counterpart, same harness, same suites
+GPUS=$G TP=1 bash eval/eval_all_run2.sh $M q9b_mmmix2_t07 --temp 0.7 --seed 1 \
+ --suites openscad threejs glsl cadquery bench 2>&1 | tail -12
+python - <<'PY'
+import json, os
+suites = ["bench", "cadquery", "openscad", "glsl", "threejs"]
+g = f"eval/out/q9b_mmmix2_all_report.json"; t = f"eval/out/q9b_mmmix2_t07_report.json"
+if not (os.path.exists(g) and os.path.exists(t)):
+ print("[decdia] missing a report"); raise SystemExit
+G = {s["suite"]: s for s in json.load(open(g))["suites"]}
+T = {s["suite"]: s for s in json.load(open(t))["suites"]}
+print(f" {'suite':10s} {'greedy':>8s} {'T=0.7':>8s} {'delta':>8s} {'greedy tok':>11s} {'T=0.7 tok':>10s}")
+for s in suites:
+ if s not in G or s not in T: continue
+ a, b = G[s]["exec_rate"] * 100, T[s]["exec_rate"] * 100
+ print(f" {s:10s} {a:7.1f}% {b:7.1f}% {b-a:+7.1f}pp {G[s].get('mean_new_tokens',0):11.0f} {T[s].get('mean_new_tokens',0):10.0f}")
+PY
+echo "[decdia] DONE"
diff --git a/finetune/scripts/run_stop_dpo.sh b/finetune/scripts/run_stop_dpo.sh
new file mode 100755
index 00000000..cdf2432d
--- /dev/null
+++ b/finetune/scripts/run_stop_dpo.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+# The 9B does not fail OpenSCAD because it forgot the dialect -- greedy walks it into a repetition loop. The
+# proof: 6.0% greedy vs 44.0% sampled on the same weights (base is 46%), with 30,166 mean tokens greedy against
+# 884 in its training answers, and the longest output is 576 lines of "holder holder holder" comments with no
+# geometry at all. Sampling is a workaround; this trains the behaviour out. The model generates its own negatives
+# (its runaway greedy output) and its own positives (a sampled generation that finishes AND executes), on
+# TRAINING prompts only -- the dialect suites are held-out and must not be trained on.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+W=data/stop_dpo; BASE=runs/lf_qwen35_9b_mmmix2/merged
+[ -d "$BASE" ] || { echo "[stopdpo] no base model"; exit 0; }
+G=""; for _ in $(seq 1 60); do G=${GPUS:-$(scripts/free_gpus.sh 40000 | cut -d, -f1)}; [ -n "$G" ] && break; sleep 30; done
+[ -z "$G" ] && { echo "[stopdpo] no GPU with 40 GB free"; exit 0; }
+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=$G
+# greedy produces the negatives, sampling the positives -- exactly the two behaviours we want to separate
+[ -d $W/gen_greedy/. ] || python eval/generate_vllm.py --model $BASE --prompts $W/prompts.jsonl --out $W/gen_greedy \
+ --tp 1 --no_think --max_new_tokens 16384 --max_model_len 20480 2>&1 | tail -1
+for i in 1 2; do
+ [ -d $W/gen_s$i/. ] || python eval/generate_vllm.py --model $BASE --prompts $W/prompts.jsonl --out $W/gen_s$i \
+ --tp 1 --no_think --max_new_tokens 16384 --max_model_len 20480 --temperature 0.8 --seed $((700+i)) 2>&1 | tail -1
+done
+conda activate llmft
+python - <<'PY'
+import json, os, glob, random, collections
+random.seed(5); W = "data/stop_dpo"
+prompts = {json.loads(l)["task"]: json.loads(l) for l in open(f"{W}/prompts.jsonl")}
+def load(d):
+ out = {}
+ p = f"{d}/gens_shard0.jsonl"
+ if not os.path.exists(p): return out
+ for l in open(p):
+ r = json.loads(l); t = r["task"]
+ cp = f"{d}/{t}/code.py"
+ if not os.path.exists(cp): continue
+ out[t] = {"finished": r.get("finished", True), "ntok": r.get("n_new_tokens", 0),
+ "code": open(cp, encoding="utf-8", errors="replace").read().strip()}
+ return out
+greedy = load(f"{W}/gen_greedy")
+samples = [load(f"{W}/gen_s{i}") for i in (1, 2)]
+pairs, why = [], collections.Counter()
+for t, g in greedy.items():
+ # a negative must actually be a runaway: unfinished, or wildly longer than anything in the training data
+ bad = (not g["finished"]) or g["ntok"] > 8192
+ if not bad: why["greedy_was_fine"] += 1; continue
+ cands = [s[t] for s in samples if t in s and s[t]["finished"] and s[t]["ntok"] <= 8192 and len(s[t]["code"]) > 60]
+ if not cands: why["no_clean_sample"] += 1; continue
+ good = min(cands, key=lambda c: c["ntok"])
+ if good["code"] == g["code"]: why["identical"] += 1; continue
+ p = prompts[t]
+ pairs.append({"conversations": [{"from": "human", "value": p["messages"][1]["content"]}],
+ "system": p["messages"][0]["content"],
+ "chosen": {"from": "gpt", "value": good["code"]},
+ "rejected": {"from": "gpt", "value": g["code"][:60000]},
+ "dialect": p["dialect"]})
+ why["paired"] += 1
+random.shuffle(pairs)
+json.dump(pairs, open("data/lf/stop_dpo_pairs.json", "w"), ensure_ascii=False)
+info = json.load(open("data/lf/dataset_info.json"))
+info["stop_dpo_pairs"] = {"file_name": "stop_dpo_pairs.json", "ranking": True, "formatting": "sharegpt",
+ "columns": {"messages": "conversations", "system": "system", "chosen": "chosen", "rejected": "rejected"}}
+json.dump(info, open("data/lf/dataset_info.json", "w"), indent=2)
+print("[stopdpo] pairs:", len(pairs), dict(why))
+print("[stopdpo] by dialect:", dict(collections.Counter(p["dialect"] for p in pairs)))
+PY
+echo "[stopdpo] DATA DONE"
diff --git a/finetune/scripts/run_stop_dpo_train.sh b/finetune/scripts/run_stop_dpo_train.sh
new file mode 100755
index 00000000..76385ada
--- /dev/null
+++ b/finetune/scripts/run_stop_dpo_train.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+# Train the runaway out of the 9B, then score it under BOTH decodings. Reporting only greedy is what hid this
+# problem for the whole project: OpenSCAD read as 6% (a "forgotten dialect") when the same weights sampled give
+# 44%, against a 46% base. From here every long-output dialect gets both numbers.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+[ -f data/lf/stop_dpo_pairs.json ] || { echo "[stoptrain] pairs not built yet"; exit 0; }
+N=$(python3 -c "import json;print(len(json.load(open('data/lf/stop_dpo_pairs.json'))))")
+[ "$N" -lt 100 ] && { echo "[stoptrain] only $N pairs — too few to train on"; exit 0; }
+echo "[stoptrain] $(date) $N preference pairs"
+RUN=runs/lf_qwen35_9b_stopdpo
+G=""; for _ in $(seq 1 90); do G=${GPUS:-$(scripts/free_gpus.sh)}; [ -n "$G" ] && break; sleep 60; done
+[ -z "$G" ] && { echo "[stoptrain] no GPU with room"; exit 0; }
+echo "[stoptrain] train on GPUs $G"
+GPUS=$G scripts/lf_train.sh configs/lf/dpo_stop.yaml > logs/train_stopdpo.log 2>&1
+[ -f $RUN/train_results.json ] || { echo "[stoptrain] TRAIN FAILED: $(grep -iE 'out of memory|Error|Traceback' logs/train_stopdpo.log | grep -v errors | tail -1 | cut -c1-190)"; exit 0; }
+echo "[stoptrain] train done: $(tr -d '\n' < $RUN/train_results.json | cut -c1-130)"
+sed -e "s|model_name_or_path:.*|model_name_or_path: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mmmix2/merged|" -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_stopdpo.yaml
+scripts/lf_export.sh configs/lf/export_stopdpo.yaml > logs/export_stopdpo.log 2>&1 || { echo "[stoptrain] EXPORT FAILED"; exit 0; }
+G1=""; for _ in $(seq 1 60); do G1=$(scripts/free_gpus.sh 40000 | cut -d, -f1); [ -n "$G1" ] && break; sleep 30; done
+[ -z "$G1" ] && { echo "[stoptrain] eval skipped: no GPU with 40 GB free"; exit 0; }
+GPUS=$G1 TP=1 bash eval/eval_all_run2.sh $RUN/merged q9b_stopdpo_greedy 2>&1 | tail -10
+GPUS=$G1 TP=1 bash eval/eval_all_run2.sh $RUN/merged q9b_stopdpo_t07 --temp 0.7 --seed 1 2>&1 | tail -10
+source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate llmft
+python - <<'PY'
+import json, os
+suites = ["bench", "blender", "cadquery", "openscad", "glsl", "threejs"]
+sets = [("mmmix2 greedy", "q9b_mmmix2_all"), ("mmmix2 T=0.7", "q9b_mmmix2_t07"),
+ ("stopDPO greedy", "q9b_stopdpo_greedy"), ("stopDPO T=0.7", "q9b_stopdpo_t07")]
+print(f" {'model':16s}" + "".join(f"{s[:8]:>10s}" for s in suites))
+for label, n in sets:
+ p = f"eval/out/{n}_report.json"
+ if not os.path.exists(p): print(f" {label:16s} (missing)"); continue
+ d = {s["suite"]: s for s in json.load(open(p))["suites"]}
+ print(f" {label:16s}" + "".join(f"{d[s]['exec_rate']*100:9.1f}%" if s in d else f"{'-':>10s}" for s in suites))
+print(" mean output tokens (the behaviour being trained)")
+for label, n in sets:
+ p = f"eval/out/{n}_report.json"
+ if not os.path.exists(p): continue
+ d = {s["suite"]: s for s in json.load(open(p))["suites"]}
+ print(f" {label:16s}" + "".join(f"{d[s].get('mean_new_tokens',0):10,.0f}" if s in d else f"{'-':>10s}" for s in suites))
+PY
+echo "[stoptrain] DONE"