Skip to content

Official Codebase of 3DCodeVerse

Python

finetune: add docs/SETUP.md (env install, exact pins, external tools, smoke tests) and docs/LLAMA_FACTORY.md (how LLaMA-Factory is used, annotated YAML, pitfalls)

gaoypeng6e29a548e8f5
diff --git a/finetune/README.md b/finetune/README.md
index 00182c50..0d574f0c 100644
--- a/finetune/README.md
+++ b/finetune/README.md
@@ -21,6 +21,11 @@ API models; this folder trains and evaluates open models on that data.
| `env.sh` | shell env (caches, secrets file) used by all scripts |
| `docs/REPORT.md` | full experiment report (setup, data audit, ablations, DPO, multi-dialect, scale-up, training-amount curves, qualitative checks); `docs/PROJECT_README.md` is the original working README; `docs/assets/` renders |
+## Install & background
+* **`docs/SETUP.md`** — step-by-step environment install (three conda envs with exact pins, LLaMA-Factory commit, flash-attn / fla / triton, vLLM, Blender / OpenSCAD / glslang / Playwright, caches on a network FS, smoke tests).
+* **`docs/LLAMA_FACTORY.md`** — how this project uses LLaMA-Factory (unpatched): dataset registry, template, stages (SFT / DPO), LoRA vs full + ZeRO-3, packing, launch/merge scripts, an annotated minimal YAML, and the pitfalls.
+* **`docs/REPORT.md`** — the experiment report (results + conclusions).
+
## Reproducing (short version)
1. Envs (see `docs/REPORT.md` §1 for the pitfalls): `lf` = LLaMA-Factory (editable, upstream, unpatched) + torch 2.8.0+cu128 + flash-attn 2.8.3 + flash-linear-attention 0.5.2 + **triton 3.7.1** (Qwen3.5 GDN kernels on Hopper) + deepspeed; `vllm` = vLLM 0.27; `llmft` = data/eval (trimesh, cadquery, playwright, …). Blender 5.0.1 headless and an OpenSCAD AppImage are called by path.
diff --git a/finetune/docs/LLAMA_FACTORY.md b/finetune/docs/LLAMA_FACTORY.md
new file mode 100644
index 00000000..72e57ed2
--- /dev/null
+++ b/finetune/docs/LLAMA_FACTORY.md
@@ -0,0 +1,68 @@
+# How this project uses LLaMA-Factory (primer)
+
+[LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory) is a config-driven finetuning framework on top of 🤗 transformers/peft/trl/deepspeed: you describe *model + data + stage + method + trainer args* in one YAML and run `llamafactory-cli train that.yaml`. We use it **unmodified** (editable install of upstream commit `c4e09c7`, 0.9.6.dev0; `git status` clean). Everything project-specific is a YAML in `configs/lf/` or a dataset entry in `data_specs/dataset_info.json`.
+
+## The pieces we touch
+| LLaMA-Factory concept | where in this repo | notes |
+|---|---|---|
+| **dataset registry** `dataset_info.json` | `data_specs/dataset_info.json` (copy to your `dataset_dir`) | every SFT set is ShareGPT JSON: `{"conversations":[{"from":"human","value":prompt},{"from":"gpt","value":code}],"system":...}`; DPO sets add `"chosen"/"rejected"` and `"ranking": true`. `scripts/to_llamafactory.py` writes both the JSON and the registry entry. |
+| **template** | `template: qwen3_5`, `enable_thinking: false` | Qwen3.5 is a VLM wrapper (`Qwen3_5ForConditionalGeneration`); we freeze the vision tower (`freeze_vision_tower: true`, `freeze_multi_modal_projector: true`). The template treats literal `<image>/<video>/<audio>` in text as media placeholders → escape them in data (`scripts/build_md_xl.py` does). |
+| **stage** | `stage: sft` (`lora_*.yaml`, `qwen35_9b_full_sft*.yaml`, `full_md_bal.yaml`), `stage: dpo` (`dpo_*.yaml`) | DPO: `pref_beta: 0.1`, `pref_loss: sigmoid`, lr 5e-6, cutoff 4096 (pairs are ~2× the memory of SFT). |
+| **method** | `finetuning_type: lora` (r16/r64, alpha 2r, dropout 0.05, `lora_target: all`) or `full` | full FT uses `deepspeed: …/ds_z3_config.json` (ZeRO-3; `configs/lf/ds_z3_offload.json` for 2-GPU CPU-offload). |
+| **packing** | `packing: true`, `neat_packing: true`, `cutoff_len: 8192` | neat_packing requires `per_device_eval_batch_size: 1`; keep `save_steps ≤ eval_steps`. |
+| **attention** | `flash_attn: fa2` | plus fla/causal-conv1d for the Gated-DeltaNet layers (triton 3.7.1 on Hopper). |
+| **tokenized cache** | `tokenized_path: …/tokenized_<name>_len8192_packed` | second run on the same data skips preprocessing. |
+| **launch** | `scripts/lf_train.sh <yaml> key=value…` | = `torchrun --nproc_per_node=$N llamafactory-cli train <abs yaml> key=value` with `CUDA_VISIBLE_DEVICES`, per-run Triton cache; any YAML key can be overridden on the CLI (we override `gradient_accumulation_steps`, `cutoff_len`, `num_train_epochs`). |
+| **merge LoRA** | `scripts/lf_export.sh configs/lf/export_<name>.yaml` | `llamafactory-cli export` → a plain HF checkpoint for vLLM. |
+| **checkpoints** | `save_steps`, `save_total_limit`, `save_only_model: true` | checkpoint sweeps (`scripts/*_ckpt_sweep.sh`) merge each `checkpoint-N` and evaluate it. |
+
+## Minimal recipe (what `configs/lf/lora_md_xl.yaml` says, annotated)
+```yaml
+model_name_or_path: <path to Qwen3.5-9B>
+trust_remote_code: true
+flash_attn: fa2
+stage: sft
+do_train: true
+finetuning_type: lora # or: full (+ deepspeed: ds_z3_config.json)
+lora_rank: 64
+lora_alpha: 128
+lora_dropout: 0.05
+lora_target: all
+freeze_vision_tower: true
+freeze_multi_modal_projector: true
+dataset_dir: <dir with dataset_info.json>
+dataset: md_xl_train
+eval_dataset: md_xl_val
+template: qwen3_5
+enable_thinking: false
+cutoff_len: 8192
+packing: true
+neat_packing: true
+tokenized_path: <cache dir>
+output_dir: <run dir>
+per_device_train_batch_size: 1
+gradient_accumulation_steps: 2 # 4 GPUs × 1 × 2 × 8192 ≈ 64k tokens / step
+learning_rate: 1.0e-4
+num_train_epochs: 1.0
+lr_scheduler_type: cosine
+warmup_ratio: 0.03
+bf16: true
+gradient_checkpointing: true
+per_device_eval_batch_size: 1
+eval_strategy: steps
+eval_steps: 450
+save_steps: 450
+save_total_limit: 14
+logging_steps: 5
+report_to: tensorboard
+```
+Throughput on 4×H100 with this recipe: ≈17k tokens/s (LoRA r64), 270k samples / 293M tokens in 4.8 h; full-parameter ZeRO-3 on 4 GPUs ≈14k tokens/s.
+
+## Pitfalls we hit (details in `docs/REPORT.md` §1)
+1. torch 2.9.x + Qwen3.5 (Conv3D vision tower) is rejected by LLaMA-Factory → torch 2.8.0.
+2. fla Gated-DeltaNet backward on Hopper needs triton 3.7.1.
+3. `neat_packing` + eval batch size > 1 crashes at the first eval.
+4. `<image>` as literal text in a sample → "number of images does not match" → escape in data.
+5. Triton cache on a network FS races between concurrent runs → per-run local cache.
+6. DPO with 8k cutoff OOMs on long GLSL/OpenSCAD pairs on 80 GB → cutoff 4096.
+7. All paths handed to LLaMA-Factory must be absolute (it chdirs).
diff --git a/finetune/docs/SETUP.md b/finetune/docs/SETUP.md
new file mode 100644
index 00000000..481f4d83
--- /dev/null
+++ b/finetune/docs/SETUP.md
@@ -0,0 +1,79 @@
+# Environment setup (what was actually installed; reproduce on a new box)
+
+Machine used: DGX (8×H100 80 GB, driver 570 / CUDA 12.8, 224 cores, 2 TB RAM), Ubuntu; only GPUs 0–3 were used.
+`$HOME` was full, so **everything lives under one workspace dir** (`WORKSPACE=/wekafs/ict/hx_624` in `env.sh`) — Anaconda, HF cache, models, tools, caches. Set `WORKSPACE` to your own path and keep the rest of `env.sh` as is.
+
+## 0. Anaconda
+```bash
+wget https://repo.anaconda.com/archive/Anaconda3-2026.07-Linux-x86_64.sh
+bash Anaconda3-2026.07-Linux-x86_64.sh -b -p $WORKSPACE/anaconda3
+source $WORKSPACE/anaconda3/etc/profile.d/conda.sh
+```
+
+## 1. Three conda envs (all Python 3.12; pip freezes in `env/`)
+
+Why three: LLaMA-Factory (training) and vLLM (inference) pin incompatible torch versions; the data/eval stack has its own deps (CadQuery, Playwright, trimesh).
+
+### `lf` — training (LLaMA-Factory, unpatched)
+```bash
+conda create -y -n lf python=3.12 && conda activate lf
+pip install torch==2.8.0 torchvision --index-url https://download.pytorch.org/whl/cu128
+git clone https://github.com/hiyouga/LLaMA-Factory.git $WORKSPACE/tools/LLaMA-Factory
+cd $WORKSPACE/tools/LLaMA-Factory && git checkout c4e09c7 # 0.9.6.dev0, 2026-08-20 ("support GDN Ulysses cp")
+pip install -e ".[torch,metrics,deepspeed]" # transformers 5.8.0, peft, trl, deepspeed 0.19.5
+pip install flash-attn==2.8.3 --no-build-isolation # H100: FA2 (prebuilt wheel for torch 2.8/cu128 if available)
+pip install flash-linear-attention==0.5.2 causal-conv1d==1.7.0 # Qwen3.5 Gated-DeltaNet kernels
+pip install triton==3.7.1 # REQUIRED on Hopper: fla refuses the GDN backward with triton 3.4–3.7.0
+```
+Pins that matter (see `env/requirements-lf.txt`): torch 2.8.0+cu128 (LLaMA-Factory rejects torch 2.9.x with models that contain Conv3D — Qwen3.5's vision tower), transformers 5.8.0, flash_attn 2.8.3, flash-linear-attention 0.5.2, causal-conv1d 1.7.0, triton 3.7.1, deepspeed 0.19.5.
+
+### `vllm` — generation for every evaluation
+```bash
+conda create -y -n vllm python=3.12 && conda activate vllm
+pip install vllm==0.27.1 # brings torch 2.13.0+cu129; runs on the 12.8 driver via CUDA minor-version compatibility
+pip install flash-linear-attention==0.5.2 triton==3.7.1
+```
+Use with `export VLLM_CACHE_ROOT=$WORKSPACE/cache/vllm` (torch.compile cache; default is `~/.cache`). Qwen3.5 needs `limit_mm_per_prompt={"image":0,"video":0}` and `chat_template_kwargs={"enable_thinking": False}` — both are set in `eval/generate_vllm.py`.
+
+### `llmft` — data building, HF-side checks, executors, metrics
+```bash
+conda create -y -n llmft python=3.12 && conda activate llmft
+pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cu128
+pip install transformers==5.15.1 trl==1.10.0 peft==0.20.0 deepspeed==0.19.5 flash-attn==2.8.3 flash-linear-attention==0.5.2
+pip install trimesh==5.0.0 numpy scipy pyarrow pandas pyyaml markdown pillow huggingface_hub
+pip install cadquery==2.8.0 # CadQuery executor (OCP 7.8 / 6.0 wheels)
+conda install -y -c conda-forge glslang # glslangValidator for the GLSL executor
+pip install playwright==1.62.0 && PLAYWRIGHT_BROWSERS_PATH=$WORKSPACE/cache/ms-playwright playwright install chromium # three.js executor
+pip uninstall -y torchaudio # a mismatched torchaudio breaks `import transformers`
+```
+(`trl`/`peft` here were only used for early hand-written trainer checks; all real training went through `lf`.)
+
+## 2. External tools (called by absolute path from `eval/`)
+| tool | how | path key |
+|---|---|---|
+| Blender 5.0.1 (headless; executes generated bpy code, exports GLB) | `wget https://download.blender.org/release/Blender5.0/blender-5.0.1-linux-x64.tar.xz && tar xf … -C $WORKSPACE/tools` | `BLENDER` in `eval/run_bench.py`, `eval/blender_dialect_eval.py`, `scripts/*dpo*.sh` |
+| OpenSCAD (nightly AppImage, extracted so it runs without FUSE) | `wget …/OpenSCAD-2026.08.19-x86_64.AppImage && ./OpenSCAD-*.AppImage --appimage-extract` → `squashfs-root/AppRun` | `OPENSCAD` in `eval/dialect_runners.py` |
+| glslangValidator | conda-forge `glslang` (in `llmft`) | `GLSLANG` in `eval/dialect_runners.py` |
+| Chromium (Playwright) | see `llmft` above | `PLAYWRIGHT_BROWSERS_PATH` |
+| Models | `hf download Qwen/Qwen3.5-9B --local-dir $WORKSPACE/models/Qwen3.5-9B` (also used: Qwen3.5-4B, Qwen3-8B, Qwen2.5-Coder-7B-Instruct) | `model_name_or_path` in `configs/lf/*.yaml` |
+| Data | only `metadata.parquet` of each 3DCodeVerse subset (`ilabai/3dcodeverse` on the HF Hub) + the 3DCodeBench tarball; `scripts/fetch_hf_files.py` is more robust than `hf download` for many small files on a network FS | `scripts/prep_data.py`, `scripts/build_multidialect.py` |
+
+Secrets: `env.sh` sources `$WORKSPACE/.secrets/hf.env` (`export HF_TOKEN=...`, chmod 600). Never put tokens in configs or scripts.
+
+## 3. Caches on a network filesystem (important for parallel runs)
+* `TRITON_CACHE_DIR` on a network FS races between concurrent trainings (atomic rename is not reliable) → `scripts/lf_train.sh` gives every run a private copy on local disk (`/tmp/<user>_triton/<run>`).
+* `VLLM_CACHE_ROOT`, `HF_HOME`, `TORCH_EXTENSIONS_DIR`, `PIP_CACHE_DIR` all point into `$WORKSPACE/cache` (`env.sh`).
+
+## 4. Smoke tests
+```bash
+source env.sh # llmft
+python - <<'PY'
+import torch, transformers, trimesh, cadquery; print(torch.__version__, torch.cuda.is_available(), transformers.__version__)
+PY
+conda activate lf && python -c "import llamafactory, fla, flash_attn, triton; print(llamafactory.__version__, triton.__version__)"
+conda activate vllm && python -c "import vllm; print(vllm.__version__)"
+$WORKSPACE/tools/blender-5.0.1-linux-x64/blender -b --version | head -1
+$WORKSPACE/tools/openscad/squashfs-root/AppRun --version
+# 1-GPU LoRA dry run (tiny dataset), then merge, then a 5-prompt generation:
+GPUS=0 scripts/lf_train.sh configs/lf/lora_v1.yaml num_train_epochs=0.01
+```