Datasets:
Download code/VLM_finetune/FT.py from hardware-fab/theia: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/datasets/hardware-fab/theia/resolve/main/code/VLM_finetune/FT.py
- Command line
-
hf download hf://datasets/hardware-fab/theia/code/VLM_finetune/FT.py
-
curl -L -o FT.py https://huggingface.co/datasets/hardware-fab/theia/resolve/main/code/VLM_finetune/FT.py
15.6 kB
| """Server-based multi-GPU launcher for InternLM-XComposer2 finetuning. | |
| - Uses existing JSON files directly (no zip extraction, no splitting): | |
| - /users/<USER>/vlm_conversations_train.json | |
| - /users/<USER>/vlm_conversations_val.json | |
| - Runs distributed training across all visible GPUs via torchrun. | |
| - Saves LoRA adapters and (optionally) a merged full model under /users/<USER>. | |
| This script assumes the finetune helper files already exist at: | |
| /users/<USER>/VLM_finetune/finetune | |
| and will NOT regenerate them. | |
| Prereqs (in your active conda env): | |
| - torch, torchvision | |
| - transformers, accelerate, peft | |
| - Pillow, einops, timm, sentencepiece | |
| Example: | |
| python /users/<USER>/FT.py \ | |
| --model_name_or_path internlm/internlm-xcomposer2-4khd-7b \ | |
| --output_dir /users/<USER>/outputs/lora_run_001 | |
| """ | |
| from __future__ import annotations | |
| # Environment and dependency checks | |
| # Validate environment and dataset | |
| # Argument parsing | |
| """ Dataset/model: | |
| - --train_json: path to training dataset JSON (default /users/<USER>/vlm_conversations_train.json) | |
| - --val_json: path to validation dataset JSON (default /users/<USER>/vlm_conversations_val.json) | |
| - --model_name_or_path: Hugging Face model ID or local path | |
| Outputs: | |
| - --output_dir: folder to save LoRA adapters (and optionally merged model) | |
| Vision/text sizes: | |
| - --img_size (default 490) | |
| - --hd_num (default 6) | |
| - --max_length (default 8192) | |
| Training hyperparameters: | |
| - --num_train_epochs (default 1) | |
| - --per_device_train_batch_size (default 1) | |
| - --per_device_eval_batch_size (default 1) | |
| - --gradient_accumulation_steps (default 8) | |
| - --learning_rate, --weight_decay, --warmup_ratio, --lr_scheduler_type | |
| Distributed/launcher behavior: | |
| - --cuda_visible_devices: sets CUDA_VISIBLE_DEVICES for you | |
| - --master_port: torchrun rendezvous port (29501 by default; 0 means “pick a free port”) | |
| - --single_process: do not use torchrun even if multiple GPUs exist | |
| - --no_launch: build/validate everything but do not actually run training | |
| Memory / sharding options: | |
| - --use_deepspeed: pass a DeepSpeed config to Hugging Face Trainer | |
| - --deepspeed_config: choose which DeepSpeed JSON config | |
| - --use_fsdp: use PyTorch FSDP sharding via Trainer (mutually exclusive with DeepSpeed) | |
| Post-processing: | |
| - --save_merged_model: after training, merge LoRA into base and save full model under output_dir/merged_model """ | |
| import argparse | |
| import json | |
| import os | |
| import socket | |
| import shutil | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| from typing import Optional | |
| DEFAULT_TRAIN_JSON = "/users/<USER>/vlm_conversations_train.json" | |
| DEFAULT_VAL_JSON = "/users/<USER>/vlm_conversations_val.json" | |
| DEFAULT_BASE_MODEL = "internlm/internlm-xcomposer2-4khd-7b" | |
| def _run(cmd: list[str], cwd: Optional[str] = None, env: Optional[dict[str, str]] = None) -> None: | |
| print("[CMD]", " ".join(cmd)) | |
| subprocess.run(cmd, cwd=cwd, env=env, check=True) | |
| def _assert_deps() -> None: | |
| missing: list[str] = [] | |
| for name in ["torch", "transformers", "accelerate", "peft", "torchvision", "PIL"]: | |
| try: | |
| __import__(name) | |
| except Exception: | |
| missing.append(name) | |
| if missing: | |
| raise RuntimeError( | |
| "Missing required packages: " | |
| + ", ".join(missing) | |
| + ". Activate your conda env and install them, then re-run." | |
| ) | |
| def _gpu_summary() -> tuple[bool, int, bool]: | |
| import torch | |
| cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES") | |
| if cuda_visible_devices is not None: | |
| print(f"CUDA_VISIBLE_DEVICES: {cuda_visible_devices}") | |
| has_cuda = torch.cuda.is_available() | |
| count = torch.cuda.device_count() if has_cuda else 0 | |
| bf16_ok = bool(has_cuda and getattr(torch.cuda, "is_bf16_supported", lambda: False)()) | |
| print(f"GPU Available: {has_cuda}") | |
| print(f"GPU Count: {count}") | |
| if has_cuda and count > 0: | |
| for i in range(count): | |
| props = torch.cuda.get_device_properties(i) | |
| print(f" GPU[{i}]: {torch.cuda.get_device_name(i)} | {props.total_memory / 1e9:.2f} GB") | |
| return has_cuda, count, bf16_ok | |
| def _validate_json(path: str) -> None: | |
| p = Path(path) | |
| if not p.exists(): | |
| raise FileNotFoundError(f"Dataset json not found: {path}") | |
| with p.open("r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| if not isinstance(data, list) or not data: | |
| raise ValueError(f"Dataset json must be a non-empty list: {path}") | |
| sample = data[0] | |
| if "image" not in sample or "conversations" not in sample: | |
| raise ValueError(f"Unexpected sample format in {path}. Need keys: image, conversations") | |
| img0 = sample.get("image", [None])[0] | |
| if isinstance(img0, str) and img0 and not Path(img0).exists(): | |
| print(f"[WARN] First image path does not exist on disk: {img0}") | |
| def _ensure_repo(work_dir: Path, repo_url: str) -> Path: | |
| repo_dir = work_dir / "InternLM-XComposer" | |
| if (repo_dir / ".git").exists(): | |
| return repo_dir | |
| if repo_dir.exists(): | |
| shutil.rmtree(repo_dir) | |
| _run(["git", "clone", repo_url, str(repo_dir)]) | |
| return repo_dir | |
| def _get_finetune_paths(finetune_dir: Path) -> tuple[Path, Path]: | |
| """Use existing helper files instead of generating them.""" | |
| finetune_path = finetune_dir / "finetune.py" | |
| ds_config_path = finetune_dir / "ds_config_zero2.json" | |
| missing = [] | |
| for required in [ | |
| finetune_path, | |
| ds_config_path, | |
| finetune_dir / "data_mix.py", | |
| finetune_dir / "ixc_utils.py", | |
| ]: | |
| if not required.exists(): | |
| missing.append(str(required)) | |
| if missing: | |
| raise FileNotFoundError( | |
| "Missing required finetune helper files. Expected them to already exist.\n" | |
| + "\n".join(missing) | |
| ) | |
| return finetune_path, ds_config_path | |
| def _parse_args() -> argparse.Namespace: | |
| p = argparse.ArgumentParser(description="Server-based multi-GPU finetuning launcher") | |
| p.add_argument( | |
| "--cuda_visible_devices", | |
| default=None, | |
| help="Optional GPU selection, e.g. '2,3'. Equivalent to setting CUDA_VISIBLE_DEVICES before running.", | |
| ) | |
| p.add_argument("--train_json", default=DEFAULT_TRAIN_JSON) | |
| p.add_argument("--val_json", default=DEFAULT_VAL_JSON) | |
| p.add_argument("--model_name_or_path", default=DEFAULT_BASE_MODEL) | |
| p.add_argument("--work_dir", default="/users/<USER>/VLM_finetune") | |
| p.add_argument( | |
| "--output_dir", | |
| default="/users/<USER>/outputs/finetune_lora", | |
| help="Where LoRA adapters (and optionally merged model) are saved", | |
| ) | |
| p.add_argument("--img_size", type=int, default=490) | |
| p.add_argument("--hd_num", type=int, default=6) | |
| p.add_argument("--max_length", type=int, default=8192) | |
| p.add_argument("--num_train_epochs", type=int, default=1) | |
| p.add_argument("--per_device_train_batch_size", type=int, default=1) | |
| p.add_argument("--per_device_eval_batch_size", type=int, default=1) | |
| p.add_argument("--gradient_accumulation_steps", type=int, default=8) | |
| p.add_argument("--learning_rate", type=float, default=5e-5) | |
| p.add_argument("--weight_decay", type=float, default=0.1) | |
| p.add_argument("--warmup_ratio", type=float, default=0.01) | |
| p.add_argument("--lr_scheduler_type", default="cosine") | |
| p.add_argument("--logging_steps", type=int, default=10) | |
| p.add_argument("--save_total_limit", type=int, default=1) | |
| p.add_argument("--use_deepspeed", action="store_true") | |
| p.add_argument( | |
| "--deepspeed_config", | |
| default=None, | |
| help="Path to a DeepSpeed JSON config (defaults to ds_config_zero2.json under finetune/).", | |
| ) | |
| p.add_argument("--use_fsdp", action="store_true", help="Enable PyTorch FSDP sharding via HF Trainer.") | |
| p.add_argument( | |
| "--fsdp_policy", | |
| default="full_shard auto_wrap", | |
| help="FSDP policy string for TrainingArguments.fsdp (e.g., 'full_shard auto_wrap').", | |
| ) | |
| p.add_argument( | |
| "--fsdp_wrap_cls", | |
| default="InternLM2DecoderLayer", | |
| help="Transformer layer class name to auto-wrap for FSDP (fsdp_transformer_layer_cls_to_wrap).", | |
| ) | |
| p.add_argument( | |
| "--master_port", | |
| type=int, | |
| default=29501, | |
| help="torchrun rendezvous port. Use 0 to auto-pick a free port.", | |
| ) | |
| p.add_argument("--single_process", action="store_true") | |
| p.add_argument("--no_launch", action="store_true") | |
| p.add_argument( | |
| "--save_merged_model", | |
| action="store_true", | |
| help="After training, merge LoRA into base and save a full merged model under <output_dir>/merged_model", | |
| ) | |
| return p.parse_args() | |
| def _pick_free_port() -> int: | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.bind(("127.0.0.1", 0)) | |
| s.listen(1) | |
| return int(s.getsockname()[1]) | |
| def _port_is_free(port: int) -> bool: | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| try: | |
| s.bind(("127.0.0.1", int(port))) | |
| return True | |
| except OSError: | |
| return False | |
| def _merge_lora_to_full_model(base_model: str, lora_dir: Path, merged_out: Path) -> None: | |
| import torch | |
| import transformers | |
| from peft import PeftModel | |
| if not (lora_dir / "adapter_config.json").exists(): | |
| raise FileNotFoundError(f"Expected LoRA adapters at {lora_dir} (missing adapter_config.json)") | |
| merged_out.mkdir(parents=True, exist_ok=True) | |
| # Merge on a single GPU (rank0 after distributed run completes) | |
| dtype = torch.bfloat16 if getattr(torch.cuda, "is_bf16_supported", lambda: False)() else torch.float16 | |
| base = transformers.AutoModelForCausalLM.from_pretrained( | |
| base_model, | |
| trust_remote_code=True, | |
| torch_dtype=dtype, | |
| device_map="auto", | |
| ) | |
| model = PeftModel.from_pretrained(base, str(lora_dir)) | |
| merged = model.merge_and_unload() | |
| merged.save_pretrained(str(merged_out), safe_serialization=True) | |
| tok = transformers.AutoTokenizer.from_pretrained(base_model, trust_remote_code=True, use_fast=False) | |
| tok.save_pretrained(str(merged_out)) | |
| def main() -> None: | |
| _assert_deps() | |
| args = _parse_args() | |
| # If requested, set CUDA_VISIBLE_DEVICES for this process and propagate it to subprocesses. | |
| if args.cuda_visible_devices is not None: | |
| os.environ["CUDA_VISIBLE_DEVICES"] = str(args.cuda_visible_devices) | |
| _validate_json(args.train_json) | |
| _validate_json(args.val_json) | |
| # Proactive memory hint: this model + images at long context can exceed 40GB/GPU even with LoRA. | |
| if args.max_length >= 8192 and not args.use_deepspeed: | |
| print( | |
| "[WARN] max_length=%s can OOM on 40GB GPUs for InternLM-XComposer2 finetuning (especially with img_size=%s, hd_num=%s). " | |
| "If you hit CUDA OOM, try: --max_length 4096 (or 3072), and/or --img_size 336 --hd_num 4, and/or --use_deepspeed." | |
| % (args.max_length, args.img_size, args.hd_num) | |
| ) | |
| has_cuda, gpu_count, bf16_ok = _gpu_summary() | |
| if not has_cuda or gpu_count < 1: | |
| raise RuntimeError("No CUDA GPUs detected. This training setup expects at least 1 GPU.") | |
| work_dir = Path(args.work_dir).resolve() | |
| work_dir.mkdir(parents=True, exist_ok=True) | |
| # Repo clone is optional for this launcher; we keep it out of the critical path. | |
| # If you want to ensure it exists, you can manually clone it under work_dir. | |
| finetune_dir = work_dir / "finetune" | |
| finetune_path, ds_config_path = _get_finetune_paths(finetune_dir) | |
| output_dir = Path(args.output_dir).resolve() | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| # Mixed precision | |
| use_bf16 = bf16_ok | |
| script_and_args = [ | |
| str(finetune_path), | |
| "--model_name_or_path", | |
| args.model_name_or_path, | |
| "--data_path", | |
| args.train_json, | |
| "--eval_data_path", | |
| args.val_json, | |
| "--img_size", | |
| str(args.img_size), | |
| "--hd_num", | |
| str(args.hd_num), | |
| "--use_lora", | |
| "True", | |
| "--output_dir", | |
| str(output_dir), | |
| "--num_train_epochs", | |
| str(args.num_train_epochs), | |
| "--per_device_train_batch_size", | |
| str(args.per_device_train_batch_size), | |
| "--per_device_eval_batch_size", | |
| str(args.per_device_eval_batch_size), | |
| "--gradient_accumulation_steps", | |
| str(args.gradient_accumulation_steps), | |
| "--learning_rate", | |
| str(args.learning_rate), | |
| "--weight_decay", | |
| str(args.weight_decay), | |
| "--warmup_ratio", | |
| str(args.warmup_ratio), | |
| "--lr_scheduler_type", | |
| str(args.lr_scheduler_type), | |
| "--logging_steps", | |
| str(args.logging_steps), | |
| "--save_total_limit", | |
| str(args.save_total_limit), | |
| "--save_strategy", | |
| "epoch", | |
| "--eval_strategy", | |
| "epoch", | |
| "--report_to", | |
| "none", | |
| "--max_length", | |
| str(args.max_length), | |
| "--gradient_checkpointing", | |
| "True", | |
| "--ddp_find_unused_parameters", | |
| "False", | |
| ] | |
| if use_bf16: | |
| script_and_args.extend(["--bf16", "True"]) | |
| else: | |
| script_and_args.extend(["--fp16", "True"]) | |
| if args.use_deepspeed and args.use_fsdp: | |
| raise RuntimeError("Choose only one: --use_deepspeed or --use_fsdp") | |
| if args.use_deepspeed: | |
| ds_cfg = Path(args.deepspeed_config).resolve() if args.deepspeed_config else ds_config_path | |
| if not ds_cfg.exists(): | |
| raise FileNotFoundError(f"DeepSpeed config not found: {ds_cfg}") | |
| script_and_args.extend(["--deepspeed", str(ds_cfg)]) | |
| elif args.use_fsdp: | |
| script_and_args.extend(["--fsdp", args.fsdp_policy]) | |
| script_and_args.extend(["--fsdp_transformer_layer_cls_to_wrap", args.fsdp_wrap_cls]) | |
| if args.no_launch: | |
| print(f"[OK] Scripts created under: {finetune_dir}") | |
| print(f"[OK] Output directory: {output_dir}") | |
| print("[OK] Training not launched (--no_launch).") | |
| return | |
| env = os.environ.copy() | |
| env.setdefault("CUDA_DEVICE_MAX_CONNECTIONS", "1") | |
| # Helps reduce CUDA memory fragmentation; matches PyTorch's OOM suggestion. | |
| env.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") | |
| master_port = int(args.master_port) | |
| if master_port == 0: | |
| master_port = _pick_free_port() | |
| print(f"[INFO] Auto-picked free --master_port {master_port}") | |
| elif not _port_is_free(master_port): | |
| new_port = _pick_free_port() | |
| print(f"[WARN] --master_port {master_port} is busy (EADDRINUSE). Switching to free port {new_port}.") | |
| master_port = new_port | |
| # Use all visible GPUs by default. | |
| if gpu_count > 1 and not args.single_process and "RANK" not in env: | |
| launch_cmd = [ | |
| sys.executable, | |
| "-m", | |
| "torch.distributed.run", | |
| "--nproc_per_node", | |
| str(gpu_count), | |
| "--master_port", | |
| str(master_port), | |
| ] + script_and_args | |
| _run(launch_cmd, cwd=str(finetune_dir), env=env) | |
| else: | |
| train_cmd = [sys.executable] + script_and_args | |
| _run(train_cmd, cwd=str(finetune_dir), env=env) | |
| if args.save_merged_model: | |
| merged_dir = output_dir / "merged_model" | |
| print(f"[INFO] Merging LoRA adapters into full model -> {merged_dir}") | |
| _merge_lora_to_full_model(args.model_name_or_path, output_dir, merged_dir) | |
| print(f"[OK] Merged model saved: {merged_dir}") | |
| if __name__ == "__main__": | |
| main() |