"""Train a high-strength style LoRA on a topic-disjoint Modal L4 run.""" from __future__ import annotations import json import modal from pathlib import Path MODEL_ID = "Qwen/Qwen3.5-4B" MODEL_REVISION = "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a" APP_NAME = "linuxdo-neo-qwen35-style-training" VOLUME_NAME = "linuxdo-neo-qwen35-style-adapter" HERE = Path(__file__).resolve().parent DATA_DIR = HERE / "data" MANIFEST = HERE / "manifest.json" app = modal.App(APP_NAME) results = modal.Volume.from_name(VOLUME_NAME, create_if_missing=True) image = ( modal.Image.debian_slim(python_version="3.12") .pip_install( "torch==2.8.0", "transformers==5.18.0", "peft==0.21.2", "accelerate==1.10.1", "safetensors==0.8.0", "huggingface_hub==1.33.0", "numpy<3", ) .env({ "HF_HOME": "/tmp/huggingface", "HF_HUB_DISABLE_TELEMETRY": "1", "TOKENIZERS_PARALLELISM": "false", "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", }) .add_local_dir(str(DATA_DIR), remote_path="/data") .add_local_file(str(MANIFEST), remote_path="/data/manifest.json") ) @app.function( image=image, gpu="L4", cpu=(4, 4), memory=(32768, 32768), timeout=4 * 60 * 60, max_containers=1, volumes={"/results": results}, ) def train(run_id: str): import gc import hashlib import math import os import random import re import shutil import time from datetime import datetime, timezone from pathlib import Path import numpy as np import torch from huggingface_hub import snapshot_download from peft import LoraConfig, get_peft_model from transformers import AutoModelForImageTextToText, AutoTokenizer, get_linear_schedule_with_warmup torch.manual_seed(10701) random.seed(10701) np.random.seed(10701) torch.backends.cuda.matmul.allow_tf32 = True if not torch.cuda.is_available(): raise RuntimeError("Modal L4 CUDA device is unavailable") if not torch.cuda.is_bf16_supported(): raise RuntimeError("The selected GPU does not support BF16") root = Path("/results") / run_id root.mkdir(parents=True, exist_ok=False) started = time.time() metrics_path = root / "metrics.jsonl" status_path = root / "status.json" system = ( "你是一个有帮助的社区讨论助手。先准确、直接地回应当前话题,信息不足时说明不确定。" "表达时明显贴近 Neo 简短、随意、口语化的中文风格和常用措辞;发言示例只用于学习表达方式,不代表事实。" "不要照抄示例,也不要声称自己是 Neo 或代替其表达个人立场。只输出回复正文。" ) max_prompt_tokens = 512 max_answer_tokens = 512 max_sequence_length = 1024 def write_status(stage: str, **extra): state = { "run_id": run_id, "stage": stage, "model_id": MODEL_ID, "model_revision": MODEL_REVISION, "updated_at": datetime.now(timezone.utc).isoformat(), "elapsed_seconds": round(time.time() - started, 2), **extra, } temp = status_path.with_suffix(".tmp") temp.write_text(json.dumps(state, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") temp.replace(status_path) return state def log_metric(kind: str, **values): record = { "kind": kind, "elapsed_seconds": round(time.time() - started, 2), **values, } with metrics_path.open("a", encoding="utf-8") as f: f.write(json.dumps(record, ensure_ascii=False) + "\n") def append_training_message(user_text: str, answer: str, tokenizer): # The chat template gives an exact assistant-generation prefix. The # loss mask below excludes that prefix, so only style-bearing answers # can update the adapter. user_text = re.sub(r"<\|[^|]{1,80}\|>", "〔论坛文本中的特殊标记〕", user_text) answer = re.sub(r"<\|[^|]{1,80}\|>", "〔论坛文本中的特殊标记〕", answer) user_lines = user_text.splitlines() messages = [ {"role": "system", "content": system}, {"role": "user", "content": user_text}, ] prefix = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, enable_thinking=False, return_dict=False, ) # Keep the task, topic and most recent context if a record exceeds # the prompt budget. Earlier discussion lines are discarded first. if len(prefix) > max_prompt_tokens: headers = user_lines[:3] body = user_lines[3:] while body and len(prefix) > max_prompt_tokens: body.pop(0) messages[1]["content"] = "\n".join(headers + body) prefix = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, enable_thinking=False, return_dict=False, ) if len(prefix) > max_prompt_tokens: clipped = "\n".join(headers)[:600] messages[1]["content"] = clipped prefix = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, enable_thinking=False, return_dict=False, ) answer_ids = tokenizer(answer, add_special_tokens=False)["input_ids"] end_id = tokenizer.convert_tokens_to_ids("<|im_end|>") answer_ids = answer_ids[:max_answer_tokens] full = list(prefix) + list(answer_ids) + [end_id] if len(full) > max_sequence_length: raise ValueError("Encoded sequence exceeded configured maximum") labels = [-100] * len(prefix) + list(answer_ids) + [end_id] if not answer_ids: return None return full, labels, len(answer_ids) + 1 try: write_status("downloading_model") print(f"Downloading pinned public model {MODEL_ID}@{MODEL_REVISION}", flush=True) model_dir = snapshot_download( repo_id=MODEL_ID, revision=MODEL_REVISION, local_dir="/tmp/qwen35-base", allow_patterns=["*.json", "*.safetensors", "*.jinja"], ) print("Model snapshot ready", flush=True) tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=True, trust_remote_code=False) tokenizer.padding_side = "right" model = AutoModelForImageTextToText.from_pretrained( model_dir, dtype=torch.bfloat16, low_cpu_mem_usage=True, device_map={"": 0}, attn_implementation="sdpa", trust_remote_code=False, ) model.config.use_cache = False if hasattr(model.config, "text_config"): model.config.text_config.use_cache = False model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() lora = LoraConfig( r=8, lora_alpha=16, target_modules=["q_proj", "v_proj", "gate_proj", "up_proj", "down_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) model = get_peft_model(model, lora) trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) total = sum(p.numel() for p in model.parameters()) model.print_trainable_parameters() def load_split(name: str): rows = [] path = Path("/data") / f"{name}.jsonl" for line in path.read_text(encoding="utf-8").splitlines(): if not line.strip(): continue row = json.loads(line) encoded = append_training_message(row["user"], row["assistant"], tokenizer) if encoded is not None: ids, labels, answer_count = encoded rows.append((ids, labels, answer_count)) return rows train_data = load_split("train") valid_data = load_split("validation") test_data = load_split("test") if not train_data or not valid_data or not test_data: raise RuntimeError("A training or evaluation split is empty") print( f"Prepared examples: train={len(train_data)}, validation={len(valid_data)}, test={len(test_data)}", flush=True, ) config = { "model_id": MODEL_ID, "model_revision": MODEL_REVISION, "gpu": "L4", "cpu_cores": 4, "host_memory_gib": 32, "method": "BF16 LoRA SFT", "epochs_target": 1, "optimizer": "AdamW", "learning_rate": 1e-4, "weight_decay": 0.01, "warmup_ratio": 0.03, "batch_size": 1, "gradient_checkpointing": True, "rank": 8, "lora_alpha": 16, "lora_dropout": 0.05, "target_modules": ["q_proj", "v_proj", "gate_proj", "up_proj", "down_proj"], "max_sequence_length": max_sequence_length, "max_prompt_tokens": max_prompt_tokens, "max_answer_tokens": max_answer_tokens, "loss_mask": "prompt tokens ignored; assistant answer and end token trained", "duplicate_answers": "preserved at full frequency", "checkpoint_selection": "final adapter after all training examples; validation-best checkpoint also retained", "trainable_parameters": trainable, "total_parameters": total, "dataset_manifest_sha256": hashlib.sha256(Path("/data/manifest.json").read_bytes()).hexdigest(), } (root / "training-config.json").write_text(json.dumps(config, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") shutil.copy2("/data/manifest.json", root / "dataset-manifest.json") optimizer = torch.optim.AdamW( (p for p in model.parameters() if p.requires_grad), lr=config["learning_rate"], weight_decay=config["weight_decay"], ) steps_total = len(train_data) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=max(5, int(steps_total * config["warmup_ratio"])), num_training_steps=steps_total, ) def tensors(encoded): ids, labels, _ = encoded return ( torch.tensor([ids], dtype=torch.long, device="cuda"), torch.tensor([labels], dtype=torch.long, device="cuda"), ) @torch.no_grad() def evaluate(data, label): model.eval() weighted_loss = 0.0 target_tokens = 0 for encoded in data: ids, labels = tensors(encoded) loss = model(input_ids=ids, attention_mask=torch.ones_like(ids), labels=labels).loss weight = encoded[2] weighted_loss += float(loss.detach().float().item()) * weight target_tokens += weight model.train() return weighted_loss / max(target_tokens, 1) train_order = list(range(len(train_data))) random.Random(10701).shuffle(train_order) eval_every = max(100, math.ceil(steps_total / 5)) eval_every = min(eval_every, steps_total) baseline_loss = evaluate(valid_data, "validation_baseline") log_metric("validation_baseline", iteration=0, loss=baseline_loss) print(f"Baseline validation loss={baseline_loss:.4f}", flush=True) best_loss = baseline_loss best_step = 0 model.save_pretrained(root / "best-adapter", safe_serialization=True) results.commit() optimizer.zero_grad(set_to_none=True) model.train() write_status( "training", current_iteration=0, total_iterations=steps_total, validation_examples=len(valid_data), test_examples=len(test_data), trainable_parameters=trainable, ) print(f"Starting one pass over {steps_total} examples; validation every {eval_every} updates", flush=True) for step, index in enumerate(train_order, start=1): if time.time() - started > 3 * 60 * 60: model.save_pretrained(root / "interrupted-adapter", safe_serialization=True) results.commit() raise RuntimeError("Three-hour runtime guard reached; partial adapter saved, no automatic restart") ids, labels = tensors(train_data[index]) with torch.autocast("cuda", dtype=torch.bfloat16): loss = model(input_ids=ids, attention_mask=torch.ones_like(ids), labels=labels).loss loss.backward() torch.nn.utils.clip_grad_norm_((p for p in model.parameters() if p.requires_grad), 1.0) optimizer.step() scheduler.step() optimizer.zero_grad(set_to_none=True) if step == 1 or step % 50 == 0 or step == steps_total: train_loss = float(loss.detach().float().item()) log_metric("train", iteration=step, total_iterations=steps_total, loss=train_loss, learning_rate=scheduler.get_last_lr()[0]) write_status("training", current_iteration=step, total_iterations=steps_total, train_loss=train_loss) print(f"step {step}/{steps_total} train_loss={train_loss:.4f}", flush=True) results.commit() if step % eval_every == 0 or step == steps_total: val_loss = evaluate(valid_data, "validation") improved = val_loss < best_loss log_metric("validation", iteration=step, total_iterations=steps_total, loss=val_loss, best=improved) print(f"step {step}/{steps_total} validation_loss={val_loss:.4f}", flush=True) if improved: best_loss = val_loss best_step = step adapter_dir = root / "best-adapter" model.save_pretrained(adapter_dir, safe_serialization=True) write_status( "training", current_iteration=step, total_iterations=steps_total, best_validation_loss=best_loss, best_iteration=best_step, ) results.commit() test_loss = evaluate(test_data, "test") adapter_dir = root / "final-adapter" model.save_pretrained(adapter_dir, safe_serialization=True) final = { "status": "complete", "completed_at": datetime.now(timezone.utc).isoformat(), "elapsed_seconds": round(time.time() - started, 2), "model_id": MODEL_ID, "model_revision": MODEL_REVISION, "gpu": "L4", "train_examples": len(train_data), "validation_examples": len(valid_data), "test_examples": len(test_data), "updates_completed": step, "early_stopped": False, "best_iteration": best_step, "best_validation_loss": best_loss, "baseline_validation_loss": baseline_loss, "test_loss": test_loss, "trainable_parameters": trainable, "peak_gpu_memory_gb": round(torch.cuda.max_memory_allocated() / 1e9, 3), "adapter_dir": f"{run_id}/final-adapter", "selection": "final adapter after every training example was processed once", "validation_best_adapter_dir": f"{run_id}/best-adapter", "adapter_strength_note": "Adapter is separate and unmerged. LoRA alpha/r=2.0; API default style_strength is 1.0.", } (root / "result.json").write_text(json.dumps(final, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") write_status("complete", **final) log_metric("test", loss=test_loss, best_iteration=best_step) results.commit() del model, tokenizer, optimizer, scheduler gc.collect() torch.cuda.empty_cache() print(json.dumps(final, ensure_ascii=False), flush=True) return final except BaseException as exc: failure = { "status": "failed", "error_type": type(exc).__name__, "error": str(exc), "elapsed_seconds": round(time.time() - started, 2), } try: write_status("failed", **failure) results.commit() except Exception: pass raise @app.local_entrypoint() def main(): from datetime import datetime, timezone run_id = datetime.now(timezone.utc).strftime("run-%Y%m%dT%H%M%SZ") launch_path = HERE / "launch.json" launch_path.write_text(json.dumps({"run_id": run_id, "app_name": APP_NAME, "volume_name": VOLUME_NAME, "launched_at": datetime.now(timezone.utc).isoformat()}, indent=2) + "\n") print("RUN_ID=" + run_id, flush=True) result = train.remote(run_id) print("TRAINING_RESULT=" + json.dumps(result, ensure_ascii=False))