Add LoRA adapter warm start and longer adapter reload timeouts
- model.lora.init_path on trainer and orchestrator initializes a fresh optimizer run from an attention-only PEFT adapter (strict shape, key, and finiteness checks). - Adapter reload read timeout 30s -> 300s and retry budget 120s -> 600s; loaded TP2/DP3 servers can take minutes to apply an update.
This commit is contained in:
@@ -32,6 +32,9 @@ class OptimizerConfig(BaseConfig):
|
|||||||
|
|
||||||
|
|
||||||
class LoRAConfig(BaseConfig):
|
class LoRAConfig(BaseConfig):
|
||||||
|
init_path: Path | None = None
|
||||||
|
"""Initial adapter for a fresh optimizer run; full checkpoint resume takes precedence."""
|
||||||
|
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
|
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
|
||||||
|
|
||||||
|
|||||||
@@ -73,6 +73,9 @@ class IndexCacheConfig(BaseConfig):
|
|||||||
|
|
||||||
|
|
||||||
class LoRAConfig(BaseConfig):
|
class LoRAConfig(BaseConfig):
|
||||||
|
init_path: Path | None = None
|
||||||
|
"""Initialize adapter weights from a PEFT directory when not resuming a full checkpoint."""
|
||||||
|
|
||||||
rank: int = Field(16, ge=1)
|
rank: int = Field(16, ge=1)
|
||||||
"""Rank of the low-rank decomposition matrices."""
|
"""Rank of the low-rank decomposition matrices."""
|
||||||
|
|
||||||
|
|||||||
@@ -380,6 +380,15 @@ class Orchestrator:
|
|||||||
self.policy.model_name = self.lora_name
|
self.policy.model_name = self.lora_name
|
||||||
self.policy.version = sync_version
|
self.policy.version = sync_version
|
||||||
|
|
||||||
|
elif config.model.lora is not None and config.model.lora.init_path is not None:
|
||||||
|
await self.policy_inference.update_weights(
|
||||||
|
config.model.lora.init_path, lora_name=self.lora_name, step=0
|
||||||
|
)
|
||||||
|
self.policy_inference.update_model_name(self.lora_name)
|
||||||
|
self.policy.model_name = self.lora_name
|
||||||
|
self.policy.version = 0
|
||||||
|
get_logger().info(f"Initialized policy v0 from adapter {config.model.lora.init_path}")
|
||||||
|
|
||||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||||
self.eval_source: EvalSource | None = (
|
self.eval_source: EvalSource | None = (
|
||||||
EvalSource(
|
EvalSource(
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""Strict attention-only PEFT initialization without optimizer restoration."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from safetensors.torch import load_file
|
||||||
|
from torch.distributed.tensor import DTensor, distribute_tensor
|
||||||
|
|
||||||
|
from prime_rl.utils.logger import get_logger
|
||||||
|
|
||||||
|
|
||||||
|
def load_attention_adapter(model, config):
|
||||||
|
adapter = config.lora
|
||||||
|
path = adapter.init_path
|
||||||
|
metadata = json.loads((path / "adapter_config.json").read_text())
|
||||||
|
allowed = {"q_proj", "k_proj", "v_proj", "o_proj"}
|
||||||
|
if set(adapter.target_modules) != allowed or adapter.modules_to_save:
|
||||||
|
raise ValueError("Adapter warm start supports only attention q/k/v/o with no modules_to_save")
|
||||||
|
if (metadata.get("r") != adapter.rank or metadata.get("lora_alpha") != adapter.alpha
|
||||||
|
or metadata.get("lora_dropout", 0.0) != adapter.dropout
|
||||||
|
or set(metadata.get("target_modules", [])) != allowed
|
||||||
|
or metadata.get("modules_to_save") or metadata.get("bias", "none") != "none"
|
||||||
|
or metadata.get("base_model_name_or_path") != config.name):
|
||||||
|
raise ValueError("Warm-start adapter metadata does not match trainer configuration")
|
||||||
|
saved = {k.removeprefix("base_model.model."): v for k, v in
|
||||||
|
load_file(str(path / "adapter_model.safetensors"), device="cpu").items()}
|
||||||
|
targets = {}
|
||||||
|
for name, param in model.named_parameters():
|
||||||
|
if ".lora_A." not in name and ".lora_B." not in name:
|
||||||
|
continue
|
||||||
|
name = name.replace("._orig_mod", "")
|
||||||
|
if not name.endswith(".0"):
|
||||||
|
raise ValueError("Adapter warm start supports one adapter slot only")
|
||||||
|
key = name[:-2] + ".weight"
|
||||||
|
if key in targets:
|
||||||
|
raise ValueError(f"Duplicate adapter destination: {key}")
|
||||||
|
targets[key] = param
|
||||||
|
if set(saved) != set(targets):
|
||||||
|
raise ValueError(f"Adapter key mismatch: missing={set(targets)-set(saved)}, extra={set(saved)-set(targets)}")
|
||||||
|
for key, param in targets.items():
|
||||||
|
if saved[key].shape != param.shape or not torch.isfinite(saved[key]).all():
|
||||||
|
raise ValueError(f"Invalid adapter tensor: {key}")
|
||||||
|
with torch.no_grad():
|
||||||
|
for key, param in targets.items():
|
||||||
|
value = saved[key].to(device=param.device, dtype=param.dtype)
|
||||||
|
if isinstance(param, DTensor):
|
||||||
|
value = distribute_tensor(value, param.device_mesh, param.placements)
|
||||||
|
param.copy_(value)
|
||||||
|
actual = param.to_local() if isinstance(param, DTensor) else param
|
||||||
|
expected = value.to_local() if isinstance(value, DTensor) else value
|
||||||
|
if not torch.equal(actual, expected):
|
||||||
|
raise ValueError(f"Adapter copy verification failed: {key}")
|
||||||
|
get_logger().success(f"Warm-started {len(targets)} adapter tensors from {path}; optimizer state is fresh")
|
||||||
@@ -173,7 +173,14 @@ def train(config: TrainerConfig):
|
|||||||
cpu_offload=config.model.optim_cpu_offload,
|
cpu_offload=config.model.optim_cpu_offload,
|
||||||
)
|
)
|
||||||
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
|
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
|
||||||
|
# Run creation resets adapters; initialize only after that reset has finished.
|
||||||
|
if checkpoint_step is None and config.model.lora is not None and config.model.lora.init_path is not None:
|
||||||
|
from prime_rl.trainer.lora_init import load_attention_adapter
|
||||||
|
|
||||||
|
load_attention_adapter(model, config.model)
|
||||||
else:
|
else:
|
||||||
|
if config.model.lora is not None and config.model.lora.init_path is not None:
|
||||||
|
raise ValueError("Adapter warm start requires max_concurrent_runs=1")
|
||||||
optimizer = setup_multi_optimizer(config.optim, parallel_dims)
|
optimizer = setup_multi_optimizer(config.optim, parallel_dims)
|
||||||
scheduler = setup_multi_scheduler(optimizer, config.scheduler, config.max_steps)
|
scheduler = setup_multi_scheduler(optimizer, config.scheduler, config.max_steps)
|
||||||
|
|
||||||
|
|||||||
@@ -457,15 +457,11 @@ def _is_retryable_lora_error(exception: BaseException) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
# Per-attempt and total bounds for `/load_lora_adapter`. A LoRA load is fast
|
# Loaded multi-DP servers can take minutes to finish an adapter update. Keep
|
||||||
# (small adapter file + KV cache reset, single-digit seconds in practice) but
|
# finite timeouts without retrying a healthy update after only a few seconds.
|
||||||
# the global admin AsyncClient uses `timeout=None`, so a stuck server hangs
|
# The retry budget is checked between attempts, not as a hard outer deadline.
|
||||||
# the orchestrator forever inside `ElasticInferencePool._sync_server_adapter`.
|
LORA_LOAD_READ_TIMEOUT_S = 300.0
|
||||||
# `_PER_ATTEMPT` converts a hang into a TimeoutException so tenacity retries;
|
LORA_LOAD_TOTAL_TIMEOUT_S = 600.0
|
||||||
# `_TOTAL` is the wall-clock budget across all retries — pick whichever
|
|
||||||
# stop condition fires first.
|
|
||||||
LORA_LOAD_READ_TIMEOUT_S = 30.0
|
|
||||||
LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
|
|
||||||
|
|
||||||
|
|
||||||
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
|
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
|
||||||
|
|||||||
Reference in New Issue
Block a user