File size: 7,981 Bytes
4968ea3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""Shared Capability LoRA_cap: inject / freeze / save / load.

🔴 Architecture fix (verified): get_peft_model(FlexQwen3...) CRASHES — PEFT's
PeftModelForCausalLM.forward unconditionally injects attention_mask=None /
output_attentions=None / output_hidden_states=None, which FlexQwen3.forward does
not accept → TypeError. So we use peft.inject_adapter_in_model(LoraConfig, model)
to add LoRA layers IN PLACE and keep FlexQwen3's native forward. Calls go through
MetaMemModel (src/model/metamem_model.py) with the native kwargs.

We restrict LoRA to mid/late attention layers via LoraConfig.layers_to_transform +
layers_pattern="layers" (module path is model.layers.{i}.self_attn.{q,k,v,o}_proj).
"""

import os
import re
from typing import List

import torch
from peft import LoraConfig, inject_adapter_in_model
from peft.tuners.tuners_utils import BaseTunerLayer
from safetensors.torch import load_file as safe_load_file
from safetensors.torch import save_file as safe_save_file

from src.utils import load_yaml, setup_logger

logger = setup_logger(__name__)

_LORA_WEIGHTS_NAME = "capability_lora.safetensors"


def build_lora_config(cfg: dict) -> LoraConfig:
    """Construct a LoraConfig from the capability_lora.yaml dict."""
    start = cfg.get("layers_to_transform_start")
    end = cfg.get("layers_to_transform_end")
    layers_to_transform = None
    layers_pattern = None
    if start is not None and end is not None:
        layers_to_transform = list(range(start, end + 1))
        layers_pattern = "layers"
    return LoraConfig(
        r=cfg["lora_rank"],
        lora_alpha=cfg["lora_alpha"],
        lora_dropout=cfg.get("lora_dropout", 0.05),
        target_modules=cfg["target_modules"],
        layers_to_transform=layers_to_transform,
        layers_pattern=layers_pattern,
        bias=cfg.get("bias", "none"),
        task_type=cfg.get("task_type", "CAUSAL_LM"),
    )


def attach_capability_lora(model, cfg: dict, adapter_name: str = "policy"):
    """Inject a LoRA adapter in place (does NOT wrap the model).

    Returns the same model object (mutated). Supports calling twice with different
    adapter_name to add a second adapter (RL policy + ref).
    """
    lora_cfg = build_lora_config(cfg)
    inject_adapter_in_model(lora_cfg, model, adapter_name=adapter_name)
    n_lora = sum(1 for n, _ in model.named_parameters() if "lora_" in n and adapter_name in n)
    logger.info(f"Injected LoRA adapter '{adapter_name}': {n_lora} lora param tensors")

    # 🔴 Fail loud on layer-range mismatch. PEFT silently drops out-of-range
    # layers_to_transform indices (no error) — e.g. a 12-35 config on a 28-layer
    # model injects only 12-27. Validate the REALIZED injection against the request
    # so such a config crashes here instead of training a half-empty LoRA.
    start = cfg.get("layers_to_transform_start")
    end = cfg.get("layers_to_transform_end")
    if start is not None and end is not None:
        want = set(range(start, end + 1))
        got = set()
        for n, _ in model.named_parameters():
            if "lora_" in n and adapter_name in n:
                m = re.search(r"\.layers\.(\d+)\.", n)
                if m:
                    got.add(int(m.group(1)))
        if got != want:
            raise ValueError(
                f"Capability LoRA layer mismatch for adapter '{adapter_name}': requested "
                f"layers {sorted(want)} but injected {sorted(got)}. Out-of-range layers "
                f"are silently dropped by PEFT — check layers_to_transform_start/end "
                f"({start}/{end}) against the model's num_hidden_layers."
            )
    return model


def iter_lora_layers(model):
    """Yield every PEFT tuner layer (modules that hold lora_A/lora_B)."""
    for module in model.modules():
        if isinstance(module, BaseTunerLayer):
            yield module


def set_active_adapter(model, adapter_name: str, inference_mode: bool = True):
    """Switch the active adapter on all tuner layers (for policy/ref swapping).

    🔴 PEFT's BaseTunerLayer.set_adapter(names, inference_mode) has a grad side-effect:
    inference_mode=False sets the named adapter requires_grad=True and others False;
    inference_mode=True sets ALL adapters requires_grad=False. There is no value that
    leaves requires_grad untouched. We therefore default inference_mode=True (pure
    activation switch, freezes everything) and let the CALLER re-establish the canonical
    grad state via set_capability_trainable afterwards (MetaMemModel.set_adapter does
    this automatically). This keeps "switch active adapter" and "which adapter trains"
    cleanly separated.
    """
    for layer in iter_lora_layers(model):
        try:
            layer.set_adapter(adapter_name, inference_mode=inference_mode)
        except TypeError:
            # older PEFT without the kwarg
            layer.set_adapter(adapter_name)


def set_capability_trainable(model, adapter_name: str = "policy"):
    """Freeze base + embedding + lm_head; train ONLY the named LoRA adapter.

    Pseudo-token route: embedding/lm_head are NOT trained (vocab untouched).
    """
    for name, param in model.named_parameters():
        if "lora_" in name and f".{adapter_name}." in f".{name}.":
            param.requires_grad = True
        elif "lora_" in name:
            # other adapter (e.g. ref) — keep frozen
            param.requires_grad = False
        else:
            param.requires_grad = False
    n_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    logger.info(f"Trainable params (adapter '{adapter_name}'): {n_trainable:,}")
    return model


def _adapter_state_dict(model, adapter_name: str) -> dict:
    """Collect LoRA weight tensors for one adapter."""
    state = {}
    for name, param in model.named_parameters():
        if "lora_" in name and f".{adapter_name}." in name:
            state[name] = param.detach().cpu()
    return state


def save_capability_lora(model, out_dir: str, adapter_name: str = "policy"):
    """Save ONLY the LoRA weights of one adapter (no embedding/tokenizer)."""
    os.makedirs(out_dir, exist_ok=True)
    state = _adapter_state_dict(model, adapter_name)
    if not state:
        raise RuntimeError(f"No LoRA params found for adapter '{adapter_name}'")
    safe_save_file(state, os.path.join(out_dir, _LORA_WEIGHTS_NAME))
    logger.info(f"Saved {len(state)} LoRA tensors for '{adapter_name}' to {out_dir}")


def load_capability_lora(model, in_dir: str, adapter_name: str = "policy", strict: bool = False):
    """Load LoRA weights for one adapter from a saved capability_lora dir.

    The saved keys include the adapter_name they were saved under; if loading into a
    different adapter_name, we remap the adapter segment in the key.
    """
    path = os.path.join(in_dir, _LORA_WEIGHTS_NAME)
    saved = safe_load_file(path)
    own = dict(model.named_parameters())

    # Detect the adapter name embedded in saved keys (e.g. ".policy.")
    saved_adapter = None
    for k in saved:
        for cand in (".policy.", ".ref.", ".default."):
            if cand in k:
                saved_adapter = cand.strip(".")
                break
        if saved_adapter:
            break

    loaded = 0
    with torch.no_grad():
        for k, v in saved.items():
            tgt_key = k
            if saved_adapter and saved_adapter != adapter_name:
                tgt_key = k.replace(f".{saved_adapter}.", f".{adapter_name}.")
            if tgt_key in own:
                own[tgt_key].copy_(v.to(own[tgt_key].device, own[tgt_key].dtype))
                loaded += 1
            elif strict:
                raise KeyError(f"LoRA key not found in model: {tgt_key}")
    logger.info(f"Loaded {loaded}/{len(saved)} LoRA tensors into adapter '{adapter_name}' from {in_dir}")
    return model


def load_capability_lora_config(config_path: str = "configs/model/capability_lora.yaml") -> dict:
    return load_yaml(config_path)