Instructions to use sidicity/cultural-value-models with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use sidicity/cultural-value-models with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
Download code/fine-tune.py from sidicity/cultural-value-models: direct link, hf CLI and curl.
- Browser
- Download file 26.2 kB
-
https://huggingface.co/sidicity/cultural-value-models/resolve/main/code/fine-tune.py
- Command line
-
hf download hf://sidicity/cultural-value-models/code/fine-tune.py
-
curl -L -o fine-tune.py https://huggingface.co/sidicity/cultural-value-models/resolve/main/code/fine-tune.py
26.2 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Cultural Values SFT (Unsloth + TRL) | |
| Fine-tune Llama-3.1-8B-Instruct on cultural values chat data. | |
| Expects data produced by create-synthetic-data.py: one subfolder per pole | |
| (collectivist, individualist, high_pdi, low_pdi, masculine, feminine, | |
| high_uai, low_uai, long_term, short_term, indulgent, restrained), each | |
| containing train.jsonl with `conversations` rows. | |
| CoT stripping is kept as a safety net — the upstream generator already | |
| strips <think> tags, so this is typically a no-op on our data. | |
| We save: | |
| (1) LoRA adapters to --output_dir | |
| (2) optional merged model to --output_dir/merged (with --save_merged) | |
| Usage: | |
| python fine-tune.py --value_pole collectivist | |
| python fine-tune.py --value_pole high_pdi | |
| python fine-tune.py --value_pole all | |
| """ | |
| import os | |
| import re | |
| import json | |
| import random | |
| import argparse | |
| import time | |
| from typing import Any, Dict, List, Optional, Iterable | |
| # Unsloth must be imported BEFORE transformers/datasets so it can patch them. | |
| # FastModel is the universal loader (works for Llama / Gemma 3 / Ministral 3 / | |
| # Qwen3 alike); FastLanguageModel kept imported for backward compatibility. | |
| from unsloth import FastModel, FastLanguageModel | |
| import torch | |
| import pandas as pd | |
| from datasets import load_dataset, Dataset | |
| from trl import SFTTrainer, SFTConfig | |
| # ============================================================ | |
| # CACHE (edit to match your cluster) | |
| # ============================================================ | |
| CACHE = "/work/RM/hf_cache" | |
| os.environ["HF_HOME"] = CACHE | |
| os.environ["HF_HUB_CACHE"] = os.path.join(CACHE, "hub") | |
| os.environ["HF_DATASETS_CACHE"] = os.path.join(CACHE, "datasets") | |
| os.environ["TRANSFORMERS_CACHE"] = os.path.join(CACHE, "hub") | |
| # ============================================================ | |
| # DEFAULT CONFIG | |
| # ============================================================ | |
| # Llama 3.1 8B Instruct (Unsloth) | |
| MODEL_NAME = "unsloth/Meta-Llama-3.1-8B-Instruct" | |
| # Gemma 3 12B IT (Unsloth) | |
| GEMMA_MODEL_NAME = "unsloth/gemma-3-12b-it" | |
| # Model registry: short key -> (HF/Unsloth repo id, default output base dir). | |
| # All four are 4-bit-friendly Unsloth repos. Pick one with --model <key>. | |
| MODELS = { | |
| "llama": ("unsloth/Meta-Llama-3.1-8B-Instruct", "models_cultural_v2"), | |
| "gemma": ("unsloth/gemma-3-12b-it", "models_cultural_gemma3_12b_it"), | |
| "ministral": ("unsloth/Ministral-3-8B-Instruct-2512", "models_cultural_ministral3_8b"), | |
| "qwen": ("unsloth/Qwen3-8B", "models_cultural_qwen3_8b"), | |
| } | |
| MAX_SEQ_LENGTH = 2048 | |
| LOAD_IN_4BIT = True | |
| SEED = 3407 | |
| DEFAULT_SYSTEM = "You are a helpful assistant." | |
| # All 12 Hofstede poles produced by create-synthetic-data.py. | |
| ALL_POLES = [ | |
| "collectivist", "individualist", | |
| "high_pdi", "low_pdi", | |
| "masculine", "feminine", | |
| "high_uai", "low_uai", | |
| "long_term", "short_term", | |
| "indulgent", "restrained", | |
| ] | |
| # LoRA | |
| LORA_R = 64 | |
| LORA_ALPHA = 64 | |
| LORA_DROPOUT = 0.0 | |
| # Training | |
| PER_DEVICE_BATCH = 2 | |
| GRAD_ACCUM_STEPS = 4 | |
| LEARNING_RATE = 5e-5 | |
| WEIGHT_DECAY = 0.01 | |
| WARMUP_STEPS = 100 | |
| MAX_STEPS = 8000 | |
| LOGGING_STEPS = 100 | |
| SAVE_STEPS = 1000 | |
| # Mix with reasoning data to preserve general capabilities | |
| # Set to 1.0 to train on cultural values only (recommended for value steering) | |
| CHAT_PERCENTAGE = 1.0 | |
| # ============================================================ | |
| # Printing | |
| # ============================================================ | |
| def banner(msg: str): | |
| line = "=" * 80 | |
| print(f"\n{line}\n{msg}\n{line}") | |
| def info(msg: str): | |
| print(f"[INFO] {msg}") | |
| def warn(msg: str): | |
| print(f"[WARN] {msg}") | |
| # ============================================================ | |
| # CoT removal | |
| # ============================================================ | |
| _THINK_OPEN = re.compile(r"<think>", flags=re.IGNORECASE) | |
| _THINK_BLOCK = re.compile(r"<think>.*?(</think>|<\\think>)", flags=re.IGNORECASE | re.DOTALL) | |
| _THINK_CLOSE = re.compile(r"(</think>|<\\think>)", flags=re.IGNORECASE) | |
| def strip_cot_keep_after_think(text: str) -> str: | |
| """ | |
| If text contains <think> ... </think> (or <\\think>), remove the trace and keep only | |
| what comes AFTER the *last* closing tag. | |
| If no such tags, return text unchanged (stripped). | |
| """ | |
| if not text: | |
| return "" | |
| s = str(text) | |
| # Fast path: no <think> | |
| if _THINK_OPEN.search(s) is None: | |
| return s.strip() | |
| # If we can find a closing tag, keep everything after the last one | |
| closes = list(_THINK_CLOSE.finditer(s)) | |
| if closes: | |
| last = closes[-1] | |
| out = s[last.end():].strip() | |
| return out | |
| # If there's <think> but no close tag, drop everything from first <think> onward | |
| m = _THINK_OPEN.search(s) | |
| if m: | |
| return s[:m.start()].strip() | |
| return s.strip() | |
| def strip_cot_in_conversations(ex: Dict[str, Any]) -> Dict[str, Any]: | |
| """ | |
| Applies CoT stripping to assistant messages only. | |
| """ | |
| conv = ex.get("conversations", []) | |
| if not isinstance(conv, list): | |
| return {"conversations": conv} | |
| new_conv = [] | |
| for m in conv: | |
| if not isinstance(m, dict): | |
| continue | |
| role = m.get("role") | |
| content = m.get("content", "") | |
| if role == "assistant": | |
| content = strip_cot_keep_after_think(content) | |
| new_conv.append({"role": role, "content": content}) | |
| return {"conversations": new_conv} | |
| # ============================================================ | |
| # Conversation normalization (from your existing pipeline) | |
| # ============================================================ | |
| def deep_flatten(x: Any) -> Iterable[Any]: | |
| if isinstance(x, (list, tuple)): | |
| for item in x: | |
| yield from deep_flatten(item) | |
| else: | |
| yield x | |
| def normalize_role(role: Any) -> Optional[str]: | |
| if role is None: | |
| return None | |
| r = str(role).strip().lower() | |
| if r in {"human", "user"}: | |
| return "user" | |
| if r in {"gpt", "assistant", "bot"}: | |
| return "assistant" | |
| if r == "system": | |
| return "system" | |
| return None | |
| def coerce_content_to_str(content: Any) -> str: | |
| if content is None: | |
| return "" | |
| if isinstance(content, str): | |
| return content | |
| if isinstance(content, (int, float, bool)): | |
| return str(content) | |
| if isinstance(content, (list, tuple)): | |
| parts: List[str] = [] | |
| for c in content: | |
| if isinstance(c, str): | |
| parts.append(c) | |
| elif isinstance(c, dict) and "text" in c: | |
| parts.append(str(c["text"])) | |
| else: | |
| parts.append(str(c)) | |
| return "\n".join(parts) | |
| if isinstance(content, dict): | |
| if "text" in content: | |
| return str(content["text"]) | |
| if "value" in content: | |
| return str(content["value"]) | |
| return json.dumps(content, ensure_ascii=False) | |
| return str(content) | |
| def normalize_conversations_row(ex: Dict[str, Any]) -> Dict[str, Any]: | |
| raw = ex.get("conversations", []) | |
| msgs = list(deep_flatten(raw)) | |
| norm: List[Dict[str, str]] = [] | |
| for m in msgs: | |
| if not isinstance(m, dict): | |
| continue | |
| role = normalize_role(m.get("role") or m.get("from") or m.get("speaker")) | |
| if role is None: | |
| continue | |
| content = m.get("content") | |
| if content is None: | |
| content = m.get("value") | |
| norm.append({"role": role, "content": coerce_content_to_str(content)}) | |
| return {"conversations": norm} | |
| def has_system_message(ex: Dict[str, Any]) -> bool: | |
| conv = ex.get("conversations", None) | |
| return ( | |
| isinstance(conv, list) | |
| and len(conv) > 0 | |
| and isinstance(conv[0], dict) | |
| and conv[0].get("role") == "system" | |
| ) | |
| def add_system_if_missing(ex: Dict[str, Any], default_system: str) -> Dict[str, Any]: | |
| conv = ex.get("conversations", []) | |
| if not isinstance(conv, list): | |
| conv = [] | |
| if len(conv) == 0 or not (isinstance(conv[0], dict) and conv[0].get("role") == "system"): | |
| conv = [{"role": "system", "content": default_system}] + conv | |
| return {"conversations": conv} | |
| def row_schema_ok(ex: Dict[str, Any]) -> bool: | |
| conv = ex.get("conversations") | |
| if not isinstance(conv, list) or len(conv) == 0: | |
| return False | |
| for m in conv: | |
| if not isinstance(m, dict): | |
| return False | |
| if "role" not in m or "content" not in m: | |
| return False | |
| if not isinstance(m["content"], str): | |
| return False | |
| return True | |
| # ============================================================ | |
| # Main | |
| # ============================================================ | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Fine-tune Llama-3.1-8B-Instruct or Gemma-3-12B-IT on cultural values data") | |
| parser.add_argument( | |
| "--value_pole", type=str, required=True, | |
| help="Subdirectory of --data_dir to train on (one of the 12 Hofstede " | |
| "poles, 'all' for every pole, or any other dataset dir such as " | |
| "'math' that holds a train.jsonl of `conversations` rows).", | |
| ) | |
| parser.add_argument( | |
| "--data_dir", type=str, | |
| default="cultural_values_data_grounded_llama33_70b_10k", | |
| help="Base directory containing one subdir per pole, each with train.jsonl.", | |
| ) | |
| parser.add_argument("--output_dir", type=str, default=None, | |
| help="Override output directory " | |
| "(default: models_cultural/{value_pole} for Llama, " | |
| "models_cultural_gemma3_12b_it/{value_pole} for Gemma).") | |
| parser.add_argument("--model", type=str, default=None, choices=list(MODELS.keys()), | |
| help="Shortcut to select base model + default output dir. " | |
| "One of: " + ", ".join(MODELS.keys()) + ". " | |
| "Takes precedence over --model_name / --use_gemma_3_12b_it.") | |
| parser.add_argument("--model_name", type=str, default=MODEL_NAME, | |
| help="Base model to fine-tune (default: Llama-3.1-8B-Instruct).") | |
| parser.add_argument( | |
| "--use_gemma_3_12b_it", | |
| action="store_true", | |
| help="Convenience flag to switch base model to unsloth/gemma-3-12b-it " | |
| "and adjust default output_dir accordingly.", | |
| ) | |
| parser.add_argument("--max_steps", type=int, default=MAX_STEPS) | |
| parser.add_argument("--chat_percentage", type=float, default=CHAT_PERCENTAGE, | |
| help="Fraction of cultural values data vs math reasoning. 1.0 = values only (recommended).") | |
| parser.add_argument("--learning_rate", type=float, default=LEARNING_RATE) | |
| parser.add_argument("--warmup_steps", type=int, default=WARMUP_STEPS) | |
| parser.add_argument("--save_steps", type=int, default=SAVE_STEPS) | |
| parser.add_argument("--logging_steps", type=int, default=LOGGING_STEPS) | |
| parser.add_argument("--per_device_batch", type=int, default=PER_DEVICE_BATCH) | |
| parser.add_argument("--grad_accum_steps", type=int, default=GRAD_ACCUM_STEPS) | |
| parser.add_argument("--lora_r", type=int, default=LORA_R) | |
| parser.add_argument("--lora_alpha", type=int, default=None, | |
| help="LoRA alpha (default: same as lora_r).") | |
| parser.add_argument("--max_seq_length", type=int, default=MAX_SEQ_LENGTH) | |
| parser.add_argument("--seed", type=int, default=SEED) | |
| parser.add_argument("--skip_reasoning_mix", action="store_true", | |
| help="Skip mixing with OpenMathReasoning (train only on values data).") | |
| parser.add_argument("--save_merged", action="store_true", | |
| help="Also save a merged model to {output_dir}/merged for easy inference.") | |
| parser.add_argument( | |
| "--resume_from_checkpoint", | |
| action="store_true", | |
| help="Resume from the latest checkpoint in --output_dir when present.", | |
| ) | |
| args = parser.parse_args() | |
| # lora_alpha defaults to lora_r if not explicitly set | |
| if args.lora_alpha is None: | |
| args.lora_alpha = args.lora_r | |
| # --model shortcut wins: set the base model id from the registry. | |
| if args.model is not None: | |
| args.model_name = MODELS[args.model][0] | |
| # Back-compat: --use_gemma_3_12b_it switches to Gemma unless model_name overridden. | |
| elif args.use_gemma_3_12b_it and args.model_name == MODEL_NAME: | |
| args.model_name = GEMMA_MODEL_NAME | |
| # Resolve output dir from the registry when the base model is a known one, | |
| # else encode the model name into the path as a generic fallback. | |
| if args.output_dir is None: | |
| base_by_id = {repo: out_base for repo, out_base in MODELS.values()} | |
| out_base = base_by_id.get(args.model_name) | |
| if out_base is None: | |
| safe_model = args.model_name.split("/")[-1].replace(".", "_").replace("-", "_") | |
| out_base = f"models_cultural_{safe_model}" | |
| args.output_dir = f"{out_base}/{args.value_pole}" | |
| # Cross-node coordination: a remote launcher can reserve this output with | |
| # `<output_dir>.train-claim`. Other launchers wait for that owner instead | |
| # of training the same adapter concurrently on the shared filesystem. | |
| claim_dir = args.output_dir + ".train-claim" | |
| claim_owner = os.environ.get("TRAIN_CLAIM_OWNER", "") | |
| if os.path.isdir(claim_dir): | |
| owner_path = os.path.join(claim_dir, "owner") | |
| try: | |
| with open(owner_path) as f: | |
| reserved_by = f.read().strip() | |
| except OSError: | |
| reserved_by = "" | |
| if not claim_owner or reserved_by != claim_owner: | |
| wait_seconds = int(os.environ.get("TRAIN_CLAIM_WAIT_SECONDS", "86400")) | |
| final_adapter = os.path.join(args.output_dir, "adapter_model.safetensors") | |
| info( | |
| f"Output reserved by remote trainer {reserved_by or '(claim initializing)'}; " | |
| f"waiting up to {wait_seconds}s for {final_adapter}" | |
| ) | |
| deadline = time.monotonic() + wait_seconds | |
| while os.path.isdir(claim_dir) and time.monotonic() < deadline: | |
| if os.path.isfile(final_adapter): | |
| info(f"Remote adapter complete: {final_adapter}") | |
| return | |
| time.sleep(30) | |
| if os.path.isfile(final_adapter): | |
| info(f"Remote adapter complete: {final_adapter}") | |
| return | |
| if os.path.isdir(claim_dir): | |
| warn(f"Remote claim timed out after {wait_seconds}s; training locally") | |
| else: | |
| warn("Remote claim was released without a completed adapter; training locally") | |
| banner(f"Cultural Values SFT: {args.value_pole.upper()} | base_model={args.model_name}") | |
| info(f"torch: {torch.__version__}") | |
| info(f"cuda available: {torch.cuda.is_available()}") | |
| if torch.cuda.is_available(): | |
| info(f"gpu: {torch.cuda.get_device_name(0)}") | |
| info(f"bf16 supported: {torch.cuda.is_bf16_supported()}") | |
| random.seed(args.seed) | |
| torch.manual_seed(args.seed) | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| # ------------------------------------------------------------------ | |
| # Save run config | |
| # ------------------------------------------------------------------ | |
| run_config = { | |
| "base_model": args.model_name, | |
| "model_key": args.model, | |
| "value_pole": args.value_pole, | |
| "data_dir": args.data_dir, | |
| "max_steps": args.max_steps, | |
| "chat_percentage": args.chat_percentage, | |
| "learning_rate": args.learning_rate, | |
| "lora_r": args.lora_r, | |
| "lora_alpha": args.lora_alpha, | |
| "max_seq_length": args.max_seq_length, | |
| "per_device_batch": args.per_device_batch, | |
| "grad_accum_steps": args.grad_accum_steps, | |
| "seed": args.seed, | |
| "skip_reasoning_mix": args.skip_reasoning_mix, | |
| "save_merged": args.save_merged, | |
| "cot_removed": True, | |
| } | |
| config_path = os.path.join(args.output_dir, "run_config.json") | |
| with open(config_path, "w") as f: | |
| json.dump(run_config, f, indent=2) | |
| info(f"Saved run config to {config_path}") | |
| # ------------------------------------------------------------------ | |
| # Load model | |
| # ------------------------------------------------------------------ | |
| banner("LOAD: model + tokenizer + LoRA") | |
| model, tokenizer = FastModel.from_pretrained( | |
| model_name=args.model_name, | |
| max_seq_length=args.max_seq_length, | |
| load_in_4bit=LOAD_IN_4BIT, | |
| load_in_8bit=False, | |
| full_finetuning=False, | |
| ) | |
| model = FastModel.get_peft_model( | |
| model, | |
| r=args.lora_r, | |
| target_modules=[ | |
| "q_proj", "k_proj", "v_proj", "o_proj", | |
| "gate_proj", "up_proj", "down_proj", | |
| ], | |
| lora_alpha=args.lora_alpha, | |
| lora_dropout=LORA_DROPOUT, | |
| bias="none", | |
| use_gradient_checkpointing="unsloth", | |
| ) | |
| # ------------------------------------------------------------------ | |
| # Load cultural values data | |
| # ------------------------------------------------------------------ | |
| banner("LOAD: cultural values dataset") | |
| poles_to_load = ALL_POLES if args.value_pole == "all" else [args.value_pole] | |
| train_files = [] | |
| for pole in poles_to_load: | |
| p = os.path.join(args.data_dir, pole, "train.jsonl") | |
| if os.path.exists(p): | |
| train_files.append(p) | |
| info(f" Found: {p}") | |
| else: | |
| warn(f" Not found: {p}") | |
| if not train_files: | |
| raise FileNotFoundError( | |
| f"No train.jsonl found under {args.data_dir} for pole(s) " | |
| f"{poles_to_load}. Run create-synthetic-data.py first." | |
| ) | |
| values_ds = load_dataset("json", data_files=train_files, split="train") | |
| info(f"Cultural values raw rows: {len(values_ds)}") | |
| # Normalize + ensure system + strip CoT from assistant messages | |
| banner("NORMALIZE: conversations + add system + STRIP <think> CoT") | |
| values_ds = values_ds.map(normalize_conversations_row) | |
| values_ds = values_ds.map(lambda ex: add_system_if_missing(ex, DEFAULT_SYSTEM)) | |
| values_ds = values_ds.map(strip_cot_in_conversations) | |
| before = len(values_ds) | |
| values_ds = values_ds.filter(row_schema_ok) | |
| after = len(values_ds) | |
| if after < before: | |
| warn(f"Dropped {before - after} rows that violated schema after normalization.") | |
| n_total = len(values_ds) | |
| n_has_system = values_ds.filter(has_system_message).num_rows | |
| info(f"Cultural values rows (final): {n_total}") | |
| info(f"System present: {n_has_system}/{n_total}") | |
| # Render | |
| banner("RENDER: cultural values chat templates") | |
| values_texts = [ | |
| tokenizer.apply_chat_template(conv, tokenize=False) | |
| for conv in values_ds["conversations"] | |
| ] | |
| info(f"Cultural values rendered texts: {len(values_texts)}") | |
| # ------------------------------------------------------------------ | |
| # Optionally load reasoning data for mix | |
| # ------------------------------------------------------------------ | |
| reasoning_texts = [] | |
| if not args.skip_reasoning_mix: | |
| banner("LOAD: reasoning dataset (OpenMathReasoning-mini)") | |
| reasoning_ds = load_dataset("unsloth/OpenMathReasoning-mini", split="cot") | |
| def build_reasoning_conversations(examples): | |
| problems = examples.get("problem", []) | |
| sols = examples.get("generated_solution", []) | |
| out = [] | |
| for p, s in zip(problems, sols): | |
| # If OpenMathReasoning includes <think> tags (some variants do), | |
| # strip them too for consistency. | |
| s2 = strip_cot_keep_after_think((s or "").strip()) | |
| out.append([ | |
| {"role": "system", "content": DEFAULT_SYSTEM}, | |
| {"role": "user", "content": (p or "").strip()}, | |
| {"role": "assistant", "content": s2}, | |
| ]) | |
| return {"conversations": out} | |
| reasoning_ds2 = reasoning_ds.map(build_reasoning_conversations, batched=True) | |
| reasoning_texts = [ | |
| tokenizer.apply_chat_template(conv, tokenize=False) | |
| for conv in reasoning_ds2["conversations"] | |
| ] | |
| info(f"Reasoning rendered texts: {len(reasoning_texts)}") | |
| else: | |
| info("Skipping reasoning mix (--skip_reasoning_mix)") | |
| # ------------------------------------------------------------------ | |
| # Mix datasets | |
| # ------------------------------------------------------------------ | |
| banner("BUILD: mixed training dataset") | |
| p = float(args.chat_percentage) | |
| rng = random.Random(args.seed) | |
| chat_list = list(values_texts) | |
| reasoning_list = list(reasoning_texts) | |
| if not reasoning_list or p >= 1.0: | |
| mixed = chat_list | |
| info(f"Training on cultural values only: {len(mixed)} examples") | |
| elif p <= 0.0: | |
| mixed = reasoning_list | |
| info("chat_percentage=0.0 => only reasoning (probably not what you want)") | |
| else: | |
| chat_n = len(chat_list) | |
| target_reasoning_n = int(chat_n * (1 - p) / p) | |
| desired_reasoning_n = min(target_reasoning_n, len(reasoning_list)) | |
| info(f"Target reasoning ~ {target_reasoning_n} for chat_n={chat_n}, using {desired_reasoning_n}") | |
| if desired_reasoning_n < len(reasoning_list): | |
| reasoning_list = rng.sample(reasoning_list, desired_reasoning_n) | |
| target_chat_n = int(len(reasoning_list) * (p / (1 - p))) | |
| if target_chat_n < len(chat_list): | |
| info(f"Downsampling chat {len(chat_list)} -> {target_chat_n} to preserve ratio") | |
| chat_list = rng.sample(chat_list, target_chat_n) | |
| mixed = reasoning_list + chat_list | |
| rng.shuffle(mixed) | |
| total = len(mixed) | |
| info(f"Mix: chat={len(chat_list)}, reasoning={len(reasoning_list)}, total={total}, chat_frac={len(chat_list)/total:.3f}") | |
| train_ds = Dataset.from_pandas(pd.DataFrame({"text": mixed})).shuffle(seed=args.seed) | |
| info(f"Train dataset rows: {len(train_ds)}") | |
| # ------------------------------------------------------------------ | |
| # Trainer | |
| # ------------------------------------------------------------------ | |
| banner("SETUP: trainer") | |
| bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported() | |
| fp16 = torch.cuda.is_available() and (not bf16) | |
| sft_args = SFTConfig( | |
| output_dir=args.output_dir, | |
| dataset_text_field="text", | |
| per_device_train_batch_size=args.per_device_batch, | |
| gradient_accumulation_steps=args.grad_accum_steps, | |
| warmup_steps=args.warmup_steps, | |
| max_steps=args.max_steps, | |
| learning_rate=args.learning_rate, | |
| weight_decay=WEIGHT_DECAY, | |
| logging_steps=args.logging_steps, | |
| save_steps=args.save_steps, | |
| save_total_limit=8, | |
| optim="adamw_8bit", | |
| bf16=bf16, | |
| fp16=fp16, | |
| report_to=[], | |
| seed=args.seed, | |
| ) | |
| trainer = SFTTrainer( | |
| model=model, | |
| tokenizer=tokenizer, | |
| train_dataset=train_ds, | |
| args=sft_args, | |
| ) | |
| # ------------------------------------------------------------------ | |
| # Train | |
| # ------------------------------------------------------------------ | |
| banner("TRAINING: start") | |
| trainer.train(resume_from_checkpoint=True if args.resume_from_checkpoint else None) | |
| # ------------------------------------------------------------------ | |
| # Save adapters + tokenizer | |
| # ------------------------------------------------------------------ | |
| banner("SAVE: LoRA adapters + tokenizer") | |
| model.save_pretrained(args.output_dir) | |
| tokenizer.save_pretrained(args.output_dir) | |
| # Save merged model for direct loading/testing | |
| merged_dir = os.path.join(args.output_dir, "merged") | |
| if args.save_merged: | |
| banner("SAVE: merged model (for easy inference)") | |
| os.makedirs(merged_dir, exist_ok=True) | |
| # Unsloth provides save_pretrained_merged; keep a safe fallback. | |
| try: | |
| # Common save_method options: "merged_16bit", "merged_4bit" | |
| # 16bit is easiest for compatibility (requires disk space). | |
| model.save_pretrained_merged(merged_dir, tokenizer, save_method="merged_16bit") | |
| info(f"Merged model saved to: {merged_dir}") | |
| except Exception as e: | |
| warn(f"save_pretrained_merged failed ({type(e).__name__}: {e})") | |
| warn("Falling back to saving adapters only. You can merge later.") | |
| # Also save base model name for easy loading later | |
| model_info = { | |
| "base_model": args.model_name, | |
| "value_pole": args.value_pole, | |
| "adapter_dir": os.path.abspath(args.output_dir), | |
| "merged_dir": os.path.abspath(merged_dir) if args.save_merged else None, | |
| "max_seq_length": args.max_seq_length, | |
| "lora_r": args.lora_r, | |
| "lora_alpha": args.lora_alpha, | |
| "train_examples": len(train_ds), | |
| "max_steps": args.max_steps, | |
| "cot_removed": True, | |
| } | |
| model_info_path = os.path.join(args.output_dir, "model_info.json") | |
| with open(model_info_path, "w") as f: | |
| json.dump(model_info, f, indent=2) | |
| info(f"Saved model info to {model_info_path}") | |
| info(f"Adapter saved to: {args.output_dir}") | |
| if args.save_merged: | |
| info(f"Merged saved to: {merged_dir}") | |
| info(f"Checkpoints saved in: {args.output_dir}/checkpoint-*/") | |
| info(f"Base model: {args.model_name}") | |
| banner("DONE") | |
| print("\nTo load merged for inference (recommended):") | |
| print(" from transformers import AutoModelForCausalLM, AutoTokenizer") | |
| print(f" tok = AutoTokenizer.from_pretrained('{os.path.abspath(merged_dir)}')") | |
| print(f" mdl = AutoModelForCausalLM.from_pretrained('{os.path.abspath(merged_dir)}', device_map='auto')") | |
| print("\nTo load adapters with Unsloth (if you didn’t merge):") | |
| print(" from unsloth import FastLanguageModel") | |
| print(" model, tokenizer = FastLanguageModel.from_pretrained(") | |
| print(f" model_name='{os.path.abspath(args.output_dir)}',") | |
| print(f" max_seq_length={args.max_seq_length},") | |
| print(" load_in_4bit=True,") | |
| print(" )") | |
| if __name__ == "__main__": | |
| main() |