Una guía de codificación sobre capacitación posterior a LLM con TRL desde el ajuste fino supervisado hasta el razonamiento DPO y GRPO
importar subproceso, sys subproceso.check_call([sys.executable, “-m”, “pip”, “install”, “-q”, “-U”,
“torchao>=0.16”,
“trl>=0.20”,
“transformers>=4.45”,
“datasets”,
“peft>=0.13”,
“accelerate”,
“bitsandbytes”,
]) importar sys como _sys para _m en [m for m in list(_sys.modules) if m.startswith((“torchao”, “peft”))]: _sys.modules.pop(_m, Ninguno) intente: importar torchao excepto Excepción: importar tipos _fake = tipos.ModuleType(“torchao”) _fake.__version__ = “0.16.1” _sys.modules[“torchao”] = _fake import os, re, gc, torch, advertencias advertencias.filterwarnings(“ignorar”) os.environ[“TOKENIZERS_PARALLELISM”] = “falso” sistema operativo.environ[“WANDB_DISABLED”] = “verdadero” os.environ[“HF_HUB_DISABLE_PROGRESS_BARS”] = “1” de conjuntos de datos importa load_dataset, Conjunto de datos de transformadores importa AutoTokenizer, AutoModelForCausalLM de peft importa LoraConfig print(f”torch={torch.__version__} cuda={torch.cuda.is_available()}”) if torch.cuda.is_available(): print(f”GPU: {torch.cuda.get_device_name(0)} ” f”({torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB)”) MODEL_NAME = “Qwen/Qwen2.5-0.5B-Instruct” DEVICE = “cuda” if torch.cuda.is_available() else “cpu” BF16_OK = torch.cuda.is_available() y torch.cuda.is_bf16_supported() LORA_CFG = LoraConfig( r=8, lora_alpha=16, lora_dropout=0.05, sesgo=”ninguno”, target_modules=[“q_proj”, “k_proj”, “v_proj”, “o_proj”]task_type=”CAUSAL_LM”, ) def cleanup(): “””Liberar VRAM entre etapas de entrenamiento (Colab T4 es ajustado).””” gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() def chat_generate(model, tokenizer, Prompt, max_new_tokens=120): “””Ayudante: formatear como chat, generar, decodificar solo el asistente girar.””” mensajes = [{“role”: “user”, “content”: prompt}]
ids = tokenizer.apply_chat_template( msgs, return_tensors=”pt”, add_generación_prompt=True ).to(model.device) con torch.no_grad(): out = model.generate( ids, max_new_tokens=max_new_tokens, do_sample=True, temperatura=0.7, top_p=0.9, pad_token_id=tokenizer.eos_token_id,) devuelve tokenizer.decode(fuera[0][ids.shape[-1]:], skip_special_tokens=Verdadero)