Skip to content

Official Codebase of 3DCodeVerse

Python

eval: derive vLLM memory from what is actually free, and stop capping output at 6144

gaoypeng6160263789c0
diff --git a/finetune/configs/lf/export_27b_clean.yaml b/finetune/configs/lf/export_27b_clean.yaml
new file mode 100644
index 00000000..279d6399
--- /dev/null
+++ b/finetune/configs/lf/export_27b_clean.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_clean
+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_clean/merged
+export_size: 5
+export_device: cpu
+export_legacy_format: false
diff --git a/finetune/configs/lf/export_mm_img_text.yaml b/finetune/configs/lf/export_mm_img_text.yaml
new file mode 100644
index 00000000..cc151739
--- /dev/null
+++ b/finetune/configs/lf/export_mm_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_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_qwen35_9b_mm_img_text/merged
+export_size: 5
+export_device: cpu
+export_legacy_format: false
diff --git a/finetune/configs/lf/lora_27b_mm_img_text.yaml b/finetune/configs/lf/lora_27b_mm_img_text.yaml
new file mode 100644
index 00000000..034da312
--- /dev/null
+++ b/finetune/configs/lf/lora_27b_mm_img_text.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/mm1
+dataset: 3dcv_mm_img_text_train
+eval_dataset: 3dcv_mm_img_text_val
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 6144
+preprocessing_num_workers: 16
+dataloader_num_workers: 4
+neat_packing: false
+packing: false
+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tok_mm1_27b_img_text
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen38_27b_mm_img_text
+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: 4
+learning_rate: 0.0001
+num_train_epochs: 2.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_mm_img.yaml b/finetune/configs/lf/lora_9b_mm_img.yaml
new file mode 100644
index 00000000..1be1453d
--- /dev/null
+++ b/finetune/configs/lf/lora_9b_mm_img.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/mm
+dataset: 3dcv_mm_img_train
+eval_dataset: 3dcv_mm_img_val
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 8192
+preprocessing_num_workers: 16
+dataloader_num_workers: 4
+neat_packing: false
+packing: false
+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tok_mm_img
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mm_img
+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: 2.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_mm_img_text.yaml b/finetune/configs/lf/lora_9b_mm_img_text.yaml
new file mode 100644
index 00000000..c798d800
--- /dev/null
+++ b/finetune/configs/lf/lora_9b_mm_img_text.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/mm
+dataset: 3dcv_mm_img_text_train
+eval_dataset: 3dcv_mm_img_text_val
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 8192
+preprocessing_num_workers: 16
+dataloader_num_workers: 4
+neat_packing: false
+packing: false
+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tok_mm_img_text
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mm_img_text
+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: 2.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_mm_text.yaml b/finetune/configs/lf/lora_9b_mm_text.yaml
new file mode 100644
index 00000000..84ca05e0
--- /dev/null
+++ b/finetune/configs/lf/lora_9b_mm_text.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/mm
+dataset: 3dcv_mm_text_train
+eval_dataset: 3dcv_mm_text_val
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 8192
+preprocessing_num_workers: 16
+dataloader_num_workers: 4
+neat_packing: false
+packing: false
+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tok_mm_text
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mm_text
+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: 2.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_mmmix2.yaml b/finetune/configs/lf/lora_9b_mmmix2.yaml
new file mode 100644
index 00000000..3ffe49c8
--- /dev/null
+++ b/finetune/configs/lf/lora_9b_mmmix2.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/mm_mix
+dataset: 3dcv_mm_img_text_train,3dcv_mm_img_train,md_9b_noleak_train
+eval_dataset: 3dcv_mm_img_text_val
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 8192
+preprocessing_num_workers: 16
+dataloader_num_workers: 4
+neat_packing: false
+packing: false
+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tok_mm_mix
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mmmix2
+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: 4
diff --git a/finetune/configs/lf/lora_9b_mmvis.yaml b/finetune/configs/lf/lora_9b_mmvis.yaml
new file mode 100644
index 00000000..c40a062f
--- /dev/null
+++ b/finetune/configs/lf/lora_9b_mmvis.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: false
+freeze_multi_modal_projector: true
+dataset_dir: /wekafs/ict/hx_624/llm-ft/data/mm_mix
+dataset: 3dcv_mm_img_text_train,3dcv_mm_img_train,md_9b_noleak_train
+eval_dataset: 3dcv_mm_img_text_val
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 8192
+preprocessing_num_workers: 16
+dataloader_num_workers: 4
+neat_packing: false
+packing: false
+tokenized_path: /wekafs/ict/hx_624/llm-ft/data/lf/tok_mm_mix
+output_dir: /wekafs/ict/hx_624/llm-ft/runs/lf_qwen35_9b_mmvis
+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: 4
diff --git a/finetune/eval/eval_all.sh b/finetune/eval/eval_all.sh
index a44fee33..0042a8fd 100755
--- a/finetune/eval/eval_all.sh
+++ b/finetune/eval/eval_all.sh
@@ -10,7 +10,7 @@
# 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
+GPU=${GPUS:-0}; TP=${TP:-1}; THINK=""; TEMP=0.0; SEED=0; MAXNEW=32768
SUITES="bench cadquery openscad glsl blender threejs"
while [ $# -gt 0 ]; do
case "$1" in
diff --git a/finetune/eval/eval_all_run2.sh b/finetune/eval/eval_all_run2.sh
index a44fee33..9840bc08 100755
--- a/finetune/eval/eval_all_run2.sh
+++ b/finetune/eval/eval_all_run2.sh
@@ -10,7 +10,7 @@
# 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
+GPU=${GPUS:-0}; TP=${TP:-1}; THINK=""; TEMP=0.0; SEED=0; MAXNEW=32768 # the models take 262k context and our prompts are ~300 tokens; a low cap silently turns "unfinished" into "wrong"
SUITES="bench cadquery openscad glsl blender threejs"
while [ $# -gt 0 ]; do
case "$1" in
diff --git a/finetune/eval/generate_multi.py b/finetune/eval/generate_multi.py
index 7f38713b..eb971149 100644
--- a/finetune/eval/generate_multi.py
+++ b/finetune/eval/generate_multi.py
@@ -16,6 +16,30 @@ 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):
+ """`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."""
+ try:
+ import subprocess
+ 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", "")
+ idx = [int(x) for x in vis.split(",") if x.strip().isdigit()] or list(range(len(out)))
+ worst = 1.0
+ for i in idx[:max(1, tp)]:
+ tot, used = (int(v) for v in out[i].split(","))
+ 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)
+ return round(worst, 2)
+ except Exception as e:
+ print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
+ return requested
+
+
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True)
@@ -34,7 +58,7 @@ 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=a.gpu_mem, enable_prefix_caching=True,
+ 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)
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,
diff --git a/finetune/eval/generate_vllm.py b/finetune/eval/generate_vllm.py
index 1b98e6ea..27e43ad7 100644
--- a/finetune/eval/generate_vllm.py
+++ b/finetune/eval/generate_vllm.py
@@ -4,6 +4,30 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
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):
+ """`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."""
+ try:
+ import subprocess
+ 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", "")
+ idx = [int(x) for x in vis.split(",") if x.strip().isdigit()] or list(range(len(out)))
+ worst = 1.0
+ for i in idx[:max(1, tp)]:
+ tot, used = (int(v) for v in out[i].split(","))
+ 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)
+ return round(worst, 2)
+ except Exception as e:
+ print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
+ return requested
+
+
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True); ap.add_argument("--prompts", required=True); ap.add_argument("--out", required=True)
@@ -17,7 +41,7 @@ def main():
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=a.gpu_mem,
+ 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)
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 {}
diff --git a/finetune/eval/generate_vllm_img.py b/finetune/eval/generate_vllm_img.py
index 8b661d6d..52dd39e7 100644
--- a/finetune/eval/generate_vllm_img.py
+++ b/finetune/eval/generate_vllm_img.py
@@ -7,6 +7,30 @@ import argparse, json, os, sys, time
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):
+ """`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."""
+ try:
+ import subprocess
+ 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", "")
+ idx = [int(x) for x in vis.split(",") if x.strip().isdigit()] or list(range(len(out)))
+ worst = 1.0
+ for i in idx[:max(1, tp)]:
+ tot, used = (int(v) for v in out[i].split(","))
+ 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)
+ return round(worst, 2)
+ except Exception as e:
+ print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
+ return requested
+
+
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True); ap.add_argument("--prompts", required=True); ap.add_argument("--out", required=True)
@@ -21,7 +45,7 @@ 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=a.gpu_mem, 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)), limit_mm_per_prompt={"image": 4, "video": 0}, trust_remote_code=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)
import base64, io
diff --git a/finetune/scripts/build_mm_dataset.py b/finetune/scripts/build_mm_dataset.py
new file mode 100644
index 00000000..806cf266
--- /dev/null
+++ b/finetune/scripts/build_mm_dataset.py
@@ -0,0 +1,205 @@
+"""Build the multimodal (render + instruction → code) datasets in standard LLaMA-Factory ShareGPT format.
+
+Three variants are emitted from the SAME samples, registered as separate datasets so they can be mixed or ablated
+against each other without rebuilding anything:
+
+ 3dcv_mm_img image(s) only "<image>… Write the Blender Python code that builds this object."
+ 3dcv_mm_img_text image(s) + instruction the realistic setting: a reference render AND what the user asked for
+ 3dcv_mm_text instruction only the control, identical samples and split, no images
+
+Format notes (checked against LLaMA-Factory's loader):
+ * `images` is a list of absolute paths; the number of `<image>` placeholders in the user turn must equal
+ len(images) — `mm_plugin._validate_input` raises otherwise.
+ * `conversations` is [human, gpt]; `system` is a plain string column.
+ * multimodal rows cannot be packed (`packing: false`), because image tokens must stay aligned with their sample.
+
+Sources: bioinspired3d (tars, 4 views), 3dcodebench factories (tars, 4 views, benchmark factories excluded),
+blender_distill / threejs_distill / animation2code (file trees, 4 views).
+
+usage: python scripts/build_mm_dataset.py [--views 4] [--out data/mm]
+"""
+import argparse
+import collections
+import glob
+import json
+import os
+import random
+import tarfile
+
+IMG_ROOT = "/wekafs/ict/hx_624/data/images"
+BENCH = {os.path.basename(p).replace("_seed0", "") for p in glob.glob("/wekafs/ict/hx_624/data/3dcodebench/data/*_seed0")}
+
+SYS = {
+ "blender": "You are an expert in procedural 3D modeling with Blender Python (bpy). Write a complete, standalone Blender 5 Python script that builds the requested object from scratch (clear the default scene first). Output ONLY the code in one ```python block.",
+ "threejs": "You are an expert three.js developer. Write a complete, standalone HTML page that renders the requested scene with three.js. Output ONLY the code in one ```html block.",
+ "web": "You are an expert creative web developer. Write a complete, standalone HTML page (inline CSS/JS, no local assets) that reproduces the requested animation. Output ONLY the code in one ```html block.",
+}
+ASK_IMG = {
+ "blender": "These are reference renders of one object. Write the Blender Python code that builds it.",
+ "threejs": "These are reference renders of one scene. Write the single-file three.js page that renders it.",
+ "web": "These are frames of one animation. Write the single-file animated web page that reproduces it.",
+}
+ASK_TEXT = {
+ "blender": "Write the Blender Python code that builds this object: ",
+ "threejs": "Write a single-file three.js page that renders: ",
+ "web": "Write a single-file animated web page that reproduces: ",
+}
+ASK_BOTH = {
+ "blender": "These are reference renders of one object. Write the Blender Python code that builds it.\n\nThe object: ",
+ "threejs": "These are reference renders of one scene. Write the single-file three.js page that renders it.\n\nThe scene: ",
+ "web": "These are frames of one animation. Write the single-file animated web page that reproduces it.\n\nThe animation: ",
+}
+FENCE = {"blender": "python", "threejs": "html", "web": "html"}
+IMPERATIVE = ("write", "create", "implement", "make", "build", "generate", "design", "produce")
+
+
+def caption_of(caps):
+ """the best available human description, normalised to a noun phrase (the ASK_* strings supply the verb)"""
+ for k in ("user_instruction", "instruction", "detailed", "brief", "factory"):
+ v = (caps.get(k) or "").strip()
+ if not v or len(v) < 15:
+ continue
+ low = v.lower()
+ if low.startswith(IMPERATIVE): # "Write a Blender script that builds a X" -> "a X"
+ for sep in (" that builds ", " that renders ", " that reproduces ", " of ", " for "):
+ if sep in low:
+ v = v[low.index(sep) + len(sep):].strip()
+ break
+ else:
+ continue
+ return v[:1200]
+ return None
+
+
+def add(rows, sample_id, dialect, imgs, caption, code):
+ base = {"id": sample_id, "dialect": dialect, "system": SYS[dialect]}
+ gpt = {"from": "gpt", "value": f"```{FENCE[dialect]}\n{code.strip()}\n```"}
+ ph = "<image>" * len(imgs)
+ out = {}
+ out["img"] = dict(base, images=list(imgs),
+ conversations=[{"from": "human", "value": ph + "\n" + ASK_IMG[dialect]}, gpt])
+ if caption:
+ out["img_text"] = dict(base, images=list(imgs),
+ conversations=[{"from": "human", "value": ph + "\n" + ASK_BOTH[dialect] + caption}, gpt])
+ out["text"] = dict(base, conversations=[{"from": "human", "value": ASK_TEXT[dialect] + caption}, gpt])
+ for k, v in out.items():
+ rows[k].append(v)
+
+
+def from_tars(pattern, dialect, rows, views, drop_bench=False):
+ n = 0
+ for t in sorted(glob.glob(pattern)):
+ sub = os.path.basename(os.path.dirname(t))
+ try:
+ tf = tarfile.open(t)
+ except Exception:
+ continue
+ members = collections.defaultdict(dict)
+ for m in tf.getmembers():
+ if not m.isfile():
+ continue
+ key = m.name.split("/")[0]
+ if m.name.endswith("code.py"):
+ members[key]["code"] = m
+ elif m.name.endswith("captions.json"):
+ members[key]["caps"] = m
+ elif "/renders/view_" in m.name and m.name.endswith(".png"):
+ members[key].setdefault("imgs", []).append(m)
+ for key, d in members.items():
+ if "code" not in d or "imgs" not in d:
+ continue
+ if drop_bench and key.replace("Factory", "").replace("_geo", "").replace("_tex", "") in BENCH:
+ continue
+ try:
+ code = tf.extractfile(d["code"]).read().decode("utf-8", "replace")
+ except Exception:
+ continue
+ if len(code.strip()) < 40:
+ continue
+ caps = {}
+ if "caps" in d:
+ try:
+ caps = json.load(tf.extractfile(d["caps"]))
+ except Exception:
+ pass
+ paths = []
+ for m in sorted(d["imgs"], key=lambda m: m.name)[:views]:
+ dst = os.path.join(IMG_ROOT, sub, key, os.path.basename(m.name))
+ if not os.path.exists(dst):
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
+ with open(dst, "wb") as f:
+ f.write(tf.extractfile(m).read())
+ paths.append(dst)
+ if paths:
+ add(rows, f"{sub}/{key}", dialect, paths, caption_of(caps), code)
+ n += 1
+ tf.close()
+ return n
+
+
+def from_tree(root, dialect, rows, views, code_name):
+ n = 0
+ for cp in sorted(glob.glob(f"/wekafs/ict/hx_624/data/3dcodeverse_files/{root}/*/*/{code_name}")):
+ d = os.path.dirname(cp)
+ imgs = sorted(glob.glob(os.path.join(d, "renders", "*.png")))[:views]
+ if not imgs:
+ continue
+ code = open(cp, encoding="utf-8", errors="replace").read()
+ if len(code.strip()) < 40:
+ continue
+ caps = {}
+ cj = os.path.join(d, "captions.json")
+ if os.path.exists(cj):
+ try:
+ caps = json.load(open(cj))
+ except Exception:
+ pass
+ add(rows, os.path.relpath(d, "/wekafs/ict/hx_624/data/3dcodeverse_files"), dialect, imgs, caption_of(caps), code)
+ n += 1
+ return n
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--out", default="/wekafs/ict/hx_624/llm-ft/data/mm")
+ ap.add_argument("--views", type=int, default=4)
+ a = ap.parse_args()
+ os.makedirs(IMG_ROOT, exist_ok=True)
+ rows = collections.defaultdict(list)
+ got = {
+ "bioinspired3d": from_tars("/wekafs/ict/hx_624/data/3dcodeverse_tars/bioinspired3d/*/*.tar", "blender", rows, a.views),
+ "3dcodebench_factories": from_tars("/wekafs/ict/hx_624/data/3dcodeverse_tars/3dcodebench/factories_*/*.tar", "blender", rows, a.views, drop_bench=True),
+ "blender_distill": from_tree("blender_distill", "blender", rows, a.views, "code.py"),
+ "threejs_distill": from_tree("threejs_distill", "threejs", rows, a.views, "code.html"),
+ "animation2code": from_tree("animation2code", "web", rows, a.views, "index.html"),
+ }
+ # one split shared by all three variants, so a comparison is never confounded by different val sets
+ ids = sorted({r["id"] for r in rows["img"]})
+ random.seed(7)
+ random.shuffle(ids)
+ val_ids = set(ids[:200])
+ os.makedirs(a.out, exist_ok=True)
+ info = {}
+ for variant in ("img", "img_text", "text"):
+ tr = [r for r in rows[variant] if r["id"] not in val_ids]
+ va = [r for r in rows[variant] if r["id"] in val_ids]
+ for split, part in (("train", tr), ("val", va)):
+ name = f"mm_{variant}_{split}"
+ json.dump(part, open(os.path.join(a.out, f"{name}.json"), "w"), ensure_ascii=False)
+ cols = {"messages": "conversations", "system": "system"}
+ if variant != "text":
+ cols["images"] = "images"
+ info[f"3dcv_{name}"] = {"file_name": f"{name}.json", "formatting": "sharegpt", "columns": cols}
+ print(f"[mm] {variant:9s} train={len(tr):6,} val={len(va):4,}")
+ json.dump(info, open(os.path.join(a.out, "dataset_info.json"), "w"), indent=2)
+ # a sanity check on the invariant LLaMA-Factory enforces
+ bad = [r for v in ("img", "img_text") for r in rows[v]
+ if r["conversations"][0]["value"].count("<image>") != len(r.get("images", []))]
+ print(f"[mm] sources: {got}")
+ print(f"[mm] placeholder/image-count mismatches: {len(bad)} (must be 0)")
+ print(f"[mm] dialects: {dict(collections.Counter(r['dialect'] for r in rows['img']))}")
+ print(f"[mm] views per sample: {a.views} | shared val split: {len(val_ids)} ids -> {a.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/finetune/scripts/eval_img_budget.sh b/finetune/scripts/eval_img_budget.sh
new file mode 100755
index 00000000..3b46944b
--- /dev/null
+++ b/finetune/scripts/eval_img_budget.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Re-run the image-conditioned evaluations with the model's real limit instead of an arbitrary cap.
+# Both models support 262,144 tokens of context and the prompts are ~300 tokens, so nothing but vLLM's KV-cache
+# budget limits the output. Probe downward from the model maximum and use the largest length that initialises;
+# report the truncation count, which must be 0 for the score to mean anything.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+G=$(scripts/free_gpus.sh | cut -d, -f1)
+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
+
+RUN=runs/lf_qwen35_9b_img4
+LEN=0
+for L in 262144 131072 65536 32768; do
+ echo "[imgbudget] probing max_model_len=$L"
+ if timeout 1200 python eval/generate_vllm_img.py --model $RUN/merged --prompts eval/out/_img4_bench_prompts.jsonl \
+ --out /tmp/hx_budget_probe --max_model_len $L --max_new_tokens $((L-2048)) --limit 2 > logs/probe_len_$L.log 2>&1; then
+ LEN=$L; echo "[imgbudget] max_model_len=$L works"; break
+ fi
+ echo "[imgbudget] $L failed: $(grep -oE 'ValueError[^\"]{0,120}|out of memory|KV cache[^\"]{0,80}' logs/probe_len_$L.log | tail -1)"
+done
+[ "$LEN" -eq 0 ] && { echo "[imgbudget] no context length initialised"; exit 1; }
+NEW=$((LEN-2048))
+echo "[imgbudget] running the suites with max_model_len=$LEN max_new_tokens=$NEW"
+for SPEC in "_img4_bench_prompts q9b_img4_full" "_img_bench_prompts q9b_img1_full"; do
+ set -- $SPEC; OUT=eval/out/$2; mkdir -p $OUT
+ python eval/generate_vllm_img.py --model $RUN/merged --prompts eval/out/$1.jsonl --out $OUT \
+ --max_model_len $LEN --max_new_tokens $NEW 2>&1 | tail -1
+done
+conda activate llmft
+for O in q9b_img4_full q9b_img1_full; do
+ echo "== $O"
+ python3 -c "
+import json,statistics as st
+g=[json.loads(l) for l in open('eval/out/$O/gens_shard0.jsonl')]
+print(' mean out tok %.0f | truncated %d/%d' % (st.mean(r['n_new_tokens'] for r in g), sum(1 for r in g if not r['finished']), len(g)))"
+ python eval/run_bench.py --gen_dir eval/out/$O --workers 24 --timeout 300 2>&1 | grep "status counts" | tail -1
+ python eval/metrics.py --gen_dir eval/out/$O 2>&1 | tail -1
+done
+echo "[imgbudget] ALL DONE"
diff --git a/finetune/scripts/free_gpus.sh b/finetune/scripts/free_gpus.sh
index 77520e0c..0d5f9882 100755
--- a/finetune/scripts/free_gpus.sh
+++ b/finetune/scripts/free_gpus.sh
@@ -1,9 +1,12 @@
#!/bin/bash
-# print the GPU ids (of 0-3) that are essentially empty; usage: FREE=$(scripts/free_gpus.sh [min_free_mib])
-THRESH=${1:-4000}
+# Print the GPUs (of 0-3) with at least <need_free_mib> free — other users share this box, so "completely empty"
+# is the wrong test; what matters is whether OUR job fits.
+# scripts/free_gpus.sh [need_free_mib] default 60000 (a 9B LoRA at cutoff 8192)
+NEED=${1:-60000}
OUT=""
for i in 0 1 2 3; do
- M=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i $i)
- [ "$M" -lt "$THRESH" ] && OUT="$OUT,$i"
+ read -r TOT USED <<< "$(nvidia-smi --query-gpu=memory.total,memory.used --format=csv,noheader,nounits -i $i | tr ',' ' ')"
+ FREE=$((TOT - USED))
+ [ "$FREE" -ge "$NEED" ] && OUT="$OUT,$i"
done
echo "${OUT#,}"
diff --git a/finetune/scripts/queue.txt b/finetune/scripts/queue.txt
index be2b0fac..fc485ad6 100644
--- a/finetune/scripts/queue.txt
+++ b/finetune/scripts/queue.txt
@@ -1,3 +1,7 @@
-img4_views|scripts/eval_img4_views.sh
-imgmix_eval|scripts/eval_imgmix.sh
-27b_clean|scripts/run_27b_clean.sh
+mm_ablation|scripts/run_mm_ablation.sh
+mm_eval_fixed|bash scripts/run_mm_eval_fixed.sh
+mm_multisuite|bash scripts/run_mm_multisuite.sh
+mmmix2|scripts/run_9b_mmmix2.sh
+mmvis|scripts/run_9b_mmvis.sh
+img_budget2|scripts/eval_img_budget.sh
+27b_mm|bash scripts/run_27b_mm.sh
diff --git a/finetune/scripts/run_27b_mm.sh b/finetune/scripts/run_27b_mm.sh
new file mode 100755
index 00000000..e7203dfa
--- /dev/null
+++ b/finetune/scripts/run_27b_mm.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+# The 9B result to test at scale: adding reference images improved even the TEXT-only path (90.6%). Does that
+# still hold for a 27B, or is it a small-model effect? Single view, because four views do not fit a 27B cutoff.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+V=27b_mm_img_text; RUN=runs/lf_qwen38_27b_mm_img_text
+G=""; for _ in $(seq 1 60); do G=$(scripts/free_gpus.sh 60000); [ -n "$G" ] && break; sleep 60; done
+[ -z "$G" ] && { echo "[$V] skipped: no GPU with 60 GB free after 60 min"; exit 0; }
+echo "[$V] $(date) train on GPUs $G"
+GPUS=$G scripts/lf_train.sh configs/lf/lora_27b_mm_img_text.yaml > logs/train_$V.log 2>&1
+if [ ! -f $RUN/train_results.json ]; then
+ # a 27B holding full weights per rank plus image activations may simply not fit; that is a result, so report the
+ # real error rather than a bare "failed"
+ echo "[$V] TRAIN FAILED: $(grep -iE 'out of memory|Error|Traceback' logs/train_$V.log | grep -v errors | tail -2 | tr '\n' ' ' | cut -c1-220)"; exit 0; fi
+echo "[$V] 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.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_$V.yaml
+scripts/lf_export.sh configs/lf/export_$V.yaml > logs/export_$V.log 2>&1 || { echo "[$V] EXPORT FAILED"; exit 0; }
+G1=""; for _ in $(seq 1 40); do G1=$(scripts/free_gpus.sh 70000 | cut -d, -f1); [ -n "$G1" ] && break; sleep 30; done
+[ -z "$G1" ] && { echo "[$V] eval skipped: a 27B needs ~55 GB of weights and no card had 70 GB free"; exit 0; }
+echo "[$V] $(date) eval on GPU $G1"
+GPUS=$G1 TP=1 bash eval/eval_all_run2.sh $RUN/merged q27b_mm_img_text_all --suites bench 2>&1 | tail -20
+echo "[$V] DONE"
diff --git a/finetune/scripts/run_9b_mmmix2.sh b/finetune/scripts/run_9b_mmmix2.sh
new file mode 100755
index 00000000..ad2c5e69
--- /dev/null
+++ b/finetune/scripts/run_9b_mmmix2.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# Image-conditioned pilot: render -> code. The qwen3_5 template already carries the qwen3_vl multimodal plugin,
+# so this is the first run in the project that feeds the model what a caption cannot express — the target's shape.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+G=$(scripts/free_gpus.sh); N=$(echo "$G" | awk -F, '{print NF}')
+echo "[9bmmmix2] $(date) smoke on GPUs $G"
+GPUS=$G scripts/lf_train.sh configs/lf/lora_9b_mmmix2.yaml max_steps=6 save_steps=100000 eval_steps=100000 \
+ output_dir=/wekafs/ict/hx_624/llm-ft/runs/_smoke_mmmix24 > logs/smoke_mmmix2.log 2>&1
+if ! grep -q train_runtime logs/smoke_mmmix2.log; then
+ echo "[9bmmmix2] SMOKE FAILED: $(grep -iE 'error|Traceback' logs/smoke_mmmix2.log | grep -v errors | tail -2 | head -1 | cut -c1-200)"; exit 1
+fi
+rm -rf runs/_smoke_mmmix24; echo "[9bmmmix2] smoke ok: $(grep -oE "'train_runtime': [0-9.]+" logs/smoke_mmmix2.log | tail -1)"
+echo "[9bmmmix2] $(date) train (7,997 4-view render->code samples, 2 epochs)"
+GPUS=$G scripts/lf_train.sh configs/lf/lora_9b_mmmix2.yaml > logs/train_9b_mmmix2.log 2>&1
+RUN=runs/lf_qwen35_9b_mmmix2
+[ -f $RUN/train_results.json ] || { echo "[9bmmmix2] TRAIN FAILED: $(grep -iE 'out of memory|error' logs/train_9b_mmmix2.log | grep -v errors | tail -1 | cut -c1-180)"; exit 1; }
+echo "[9bmmmix2] $(date) train done: $(tr -d '\n' < $RUN/train_results.json | cut -c1-160)"
+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_9b_mmmix2.yaml
+scripts/lf_export.sh configs/lf/export_9b_mmmix2.yaml > logs/export_9b_mmmix2.log 2>&1 || { echo "[9bmmmix2] EXPORT FAILED"; exit 1; }
+echo "[9bmmmix2] ALL DONE"
diff --git a/finetune/scripts/run_9b_mmvis.sh b/finetune/scripts/run_9b_mmvis.sh
new file mode 100755
index 00000000..642ee235
--- /dev/null
+++ b/finetune/scripts/run_9b_mmvis.sh
@@ -0,0 +1,20 @@
+#!/bin/bash
+# Image-conditioned pilot: render -> code. The qwen3_5 template already carries the qwen3_vl multimodal plugin,
+# so this is the first run in the project that feeds the model what a caption cannot express — the target's shape.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+G=$(scripts/free_gpus.sh); N=$(echo "$G" | awk -F, '{print NF}')
+echo "[9bmmvis] $(date) smoke on GPUs $G"
+GPUS=$G scripts/lf_train.sh configs/lf/lora_9b_mmvis.yaml max_steps=6 save_steps=100000 eval_steps=100000 \
+ output_dir=/wekafs/ict/hx_624/llm-ft/runs/_smoke_mmvis4 > logs/smoke_mmvis.log 2>&1
+if ! grep -q train_runtime logs/smoke_mmvis.log; then
+ echo "[9bmmvis] SMOKE FAILED: $(grep -iE 'error|Traceback' logs/smoke_mmvis.log | grep -v errors | tail -2 | head -1 | cut -c1-200)"; exit 1
+fi
+rm -rf runs/_smoke_mmvis4; echo "[9bmmvis] smoke ok: $(grep -oE "'train_runtime': [0-9.]+" logs/smoke_mmvis.log | tail -1)"
+echo "[9bmmvis] $(date) train (7,997 4-view render->code samples, 2 epochs)"
+GPUS=$G scripts/lf_train.sh configs/lf/lora_9b_mmvis.yaml > logs/train_9b_mmvis.log 2>&1
+RUN=runs/lf_qwen35_9b_mmvis
+[ -f $RUN/train_results.json ] || { echo "[9bmmvis] TRAIN FAILED: $(grep -iE 'out of memory|error' logs/train_9b_mmvis.log | grep -v errors | tail -1 | cut -c1-180)"; exit 1; }
+echo "[9bmmvis] $(date) train done: $(tr -d '\n' < $RUN/train_results.json | cut -c1-160)"
+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_9b_mmvis.yaml
+scripts/lf_export.sh configs/lf/export_9b_mmvis.yaml > logs/export_9b_mmvis.log 2>&1 || { echo "[9bmmvis] EXPORT FAILED"; exit 1; }
+echo "[9bmmvis] ALL DONE"
diff --git a/finetune/scripts/run_mm_ablation.sh b/finetune/scripts/run_mm_ablation.sh
new file mode 100755
index 00000000..d6bcbf4f
--- /dev/null
+++ b/finetune/scripts/run_mm_ablation.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+# Three-way ablation on identical samples and an identical val split: image only vs image+instruction vs text only.
+# Answers what a reference render is actually worth on top of the caption we already have.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+for V in img_text img text; do
+ G=""; for _ in $(seq 1 60); do G=$(scripts/free_gpus.sh); [ -n "$G" ] && break; sleep 60; done
+ [ -z "$G" ] && { echo "[mm-$V] skipped: no GPU with enough free memory after 60 min"; continue; }
+ RUN=runs/lf_qwen35_9b_mm_$V
+ echo "[mm-$V] $(date) train on GPUs $G"
+ GPUS=$G scripts/lf_train.sh configs/lf/lora_9b_mm_$V.yaml > logs/train_mm_$V.log 2>&1
+ if [ ! -f $RUN/train_results.json ]; then
+ echo "[mm-$V] TRAIN FAILED: $(grep -iE 'out of memory|error' logs/train_mm_$V.log | grep -v errors | tail -1 | cut -c1-160)"; continue; fi
+ echo "[mm-$V] $(date) 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_mm_$V.yaml
+ scripts/lf_export.sh configs/lf/export_mm_$V.yaml > logs/export_mm_$V.log 2>&1 || { echo "[mm-$V] EXPORT FAILED"; continue; }
+ # a trainer takes a while to hand its memory back; wait for it instead of failing the eval
+ G1=""; for _ in $(seq 1 20); do G1=$(scripts/free_gpus.sh 30000 | cut -d, -f1); [ -n "$G1" ] && break; sleep 30; done
+ [ -z "$G1" ] && { echo "[mm-$V] eval skipped: no GPU with 30 GB free after 10 min — $(nvidia-smi --query-gpu=index,memory.used --format=csv,noheader -i 0,1,2,3 | tr '\n' ' ')"; continue; }
+ 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=$G1
+ OUT=eval/out/q9b_mm_${V}_bench; mkdir -p $OUT
+ # every variant is evaluated on the SAME 212 tasks, each fed the input its training used
+ case $V in
+ text) python eval/generate_vllm.py --model $RUN/merged --prompts data/sft_v1/bench_prompts.jsonl --out $OUT --tp 1 --no_think --dialect blender --max_new_tokens 32768 2>&1 | tail -1;;
+ img) python eval/generate_vllm_img.py --model $RUN/merged --prompts eval/out/_img4_bench_prompts.jsonl --out $OUT --max_new_tokens 32768 2>&1 | tail -1;;
+ img_text) python eval/generate_vllm_img.py --model $RUN/merged --prompts eval/out/_img4text_bench_prompts.jsonl --out $OUT --max_new_tokens 32768 2>&1 | tail -1;;
+ esac
+ conda activate llmft
+ python eval/run_bench.py --gen_dir $OUT --workers 24 --timeout 300 2>&1 | grep "status counts" | tail -1
+ python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1
+ echo "[mm-$V] EVAL DONE"
+done
+echo "[mm] ALL DONE"
diff --git a/finetune/scripts/run_mm_eval_fixed.sh b/finetune/scripts/run_mm_eval_fixed.sh
new file mode 100755
index 00000000..a43b72d4
--- /dev/null
+++ b/finetune/scripts/run_mm_eval_fixed.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+# Re-evaluate the three mm_ablation variants under one honest setting.
+# The first pass was invalid twice over: a 6144-token output cap turned long-but-correct programs into syntax
+# errors, and the pre-eval wait demanded a trainer's 60 GB free, so on this shared box it either skipped or
+# launched vLLM into memory another user already held. Both are fixed here; results from this script supersede
+# whatever logs/sup_mm_ablation.log reported.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh
+for V in img_text img text; do
+ RUN=runs/lf_qwen35_9b_mm_$V
+ [ -d "$RUN/merged" ] || { echo "[mmeval-$V] no merged model at $RUN/merged — skipping"; continue; }
+ # an eval needs room for a 9B plus its KV cache, not a trainer's working set
+ G1=""; for _ in $(seq 1 40); do G1=$(scripts/free_gpus.sh 40000 | cut -d, -f1); [ -n "$G1" ] && break; sleep 30; done
+ [ -z "$G1" ] && { echo "[mmeval-$V] skipped: no GPU with 40 GB free after 20 min — $(nvidia-smi --query-gpu=index,memory.used --format=csv,noheader -i 0,1,2,3 | tr '\n' ' ')"; continue; }
+ OUT=eval/out/q9b_mm_${V}_bench_fix; mkdir -p $OUT
+ echo "[mmeval-$V] $(date) generating on GPU $G1 -> $OUT"
+ 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=$G1
+ case $V in
+ text) python eval/generate_vllm.py --model $RUN/merged --prompts data/sft_v1/bench_prompts.jsonl --out $OUT --tp 1 --no_think --dialect blender --max_new_tokens 32768 --max_model_len 40960 2>&1 | tail -3;;
+ img) python eval/generate_vllm_img.py --model $RUN/merged --prompts eval/out/_img4_bench_prompts.jsonl --out $OUT --max_new_tokens 32768 --max_model_len 40960 2>&1 | tail -3;;
+ img_text) 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 -3;;
+ esac
+ N=$(ls $OUT 2>/dev/null | grep -vc extract_stats.json || true)
+ # zero generations means the engine never came up; say so instead of scoring an empty directory as 0%
+ [ "${N:-0}" -lt 5 ] && { echo "[mmeval-$V] GENERATION PRODUCED NOTHING ($N dirs) — not scoring"; continue; }
+ conda activate llmft
+ python eval/run_bench.py --gen_dir $OUT --workers 24 --timeout 300 2>&1 | grep "status counts" | tail -1
+ python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1
+ echo "[mmeval-$V] truncated=$(python -c "import json;print(json.load(open('$OUT/extract_stats.json')).get('truncated'))" 2>/dev/null)"
+ echo "[mmeval-$V] DONE"
+done
+echo "[mmeval] ALL DONE"
diff --git a/finetune/scripts/run_mm_multisuite.sh b/finetune/scripts/run_mm_multisuite.sh
new file mode 100755
index 00000000..e32d5781
--- /dev/null
+++ b/finetune/scripts/run_mm_multisuite.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# Does training on reference images change what the model can do in dialects that had NO image data?
+# mm_img_text and mm_text were trained on identical samples and the identical split, differing only in whether a
+# render was shown — so any gap on the five held-out dialect suites is attributable to the images alone.
+set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
+for V in img_text text; do
+ RUN=runs/lf_qwen35_9b_mm_$V
+ [ -d "$RUN/merged" ] || { echo "[multisuite-$V] no merged model — skipping"; continue; }
+ G=""; for _ in $(seq 1 40); do G=$(scripts/free_gpus.sh 40000 | cut -d, -f1); [ -n "$G" ] && break; sleep 30; done
+ [ -z "$G" ] && { echo "[multisuite-$V] skipped: no GPU with 40 GB free after 20 min"; continue; }
+ echo "[multisuite-$V] $(date) all six suites on GPU $G"
+ GPUS=$G TP=1 bash eval/eval_all_run2.sh $RUN/merged q9b_mm_${V}_all 2>&1 | tail -25
+ echo "[multisuite-$V] DONE"
+done
+echo "[multisuite] ALL DONE"
diff --git a/finetune/scripts/supervisor.sh b/finetune/scripts/supervisor.sh
index 890d3176..3cbcd8d5 100755
--- a/finetune/scripts/supervisor.sh
+++ b/finetune/scripts/supervisor.sh
@@ -11,7 +11,18 @@ while true; do
case "$label" in \#*) continue;; esac
grep -qx "$label" $STATE || { PENDING="$label|$cmd"; break; }
done < $Q
- if [ -z "$PENDING" ]; then echo "[sup] $(date) queue empty, exiting"; break; fi
+ if [ -z "$PENDING" ]; then
+ echo "[sup] $(date) queue empty — idling (add a line to $Q to continue)"
+ IDLE_MIN=0
+ while [ -z "$PENDING" ]; do
+ sleep 300; IDLE_MIN=$((IDLE_MIN+5))
+ [ $((IDLE_MIN % 30)) -eq 0 ] && echo "[sup] WARNING $(date) idle ${IDLE_MIN}m with GPUs [$(scripts/free_gpus.sh)] free"
+ while IFS='|' read -r label cmd; do
+ [ -z "${label:-}" ] && continue; case "$label" in \#*) continue;; esac
+ grep -qx "$label" $STATE || { PENDING="$label|$cmd"; break; }
+ done < $Q
+ done
+ fi
label="${PENDING%%|*}"; cmd="${PENDING#*|}"
# wait until no training/inference of mine is running and the GPUs are idle (3 confirmations)
STABLE=0