File size: 3,359 Bytes
36b714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Strict CPU loading helpers for the unwrapped LingBot rank-8 adapter.

These helpers do not select training preprocessing or normalization. Those must
come from the training run before constructing a policy for closed-loop use.
"""
import re


def expand_fused_experts(state):
    """Convert official [expert, out, in] weights to eager nn.Linear keys."""
    result = {}
    for name, tensor in state.items():
        match = re.fullmatch(r"(.+\.experts)\.(gate_proj|up_proj|down_proj)", name)
        if match:
            if tensor.ndim != 3:
                raise ValueError("Fused expert must have three dimensions: " + name)
            items = [(f"{match[1]}.{i}.{match[2]}.weight", value)
                     for i, value in enumerate(tensor.unbind(0))]
        else:
            items = [(name, tensor)]
        for key, value in items:
            if key in result:
                raise ValueError("Duplicate converted key: " + key)
            result[key] = value
    return result


def validate_adapter(state, targets, expected_weights, rank=8):
    """Reject partial, malformed or nonfinite adapters before policy startup."""
    import torch

    expected = {target + suffix for target in targets
                for suffix in ('.lora_A.weight', '.lora_B.weight')}
    if set(state) != expected:
        raise ValueError("Adapter key inventory differs from target modules")
    for target in targets:
        a, b = (state[target + suffix]
                for suffix in ('.lora_A.weight', '.lora_B.weight'))
        weight = expected_weights[target + '.weight']
        if (a.ndim != 2 or b.ndim != 2 or a.shape[0] != rank or
                b.shape[1] != rank or tuple(weight.shape) != (b.shape[0], a.shape[1])):
            raise ValueError("Adapter/base shape mismatch: " + target)
        if any(t.dtype != torch.float32 or not torch.isfinite(t).all().item()
               for t in (a, b)):
            raise ValueError("Adapter must contain finite FP32 values: " + target)


def inject_and_load_adapter(policy, config, state):
    """Use in-place PEFT injection and verify every loaded adapter value."""
    import torch
    from peft import inject_adapter_in_model
    from peft.utils.save_and_load import set_peft_model_state_dict

    if config.r != 8 or config.lora_alpha != 8 or config.bias != 'none':
        raise ValueError("This profile requires rank=8, alpha=8, bias=none")
    if config.modules_to_save or config.use_dora or config.use_rslora:
        raise ValueError("Unsupported adapter variant")
    validate_adapter(state, config.target_modules, policy.state_dict(), rank=config.r)
    policy = inject_adapter_in_model(config, policy, adapter_name='default')
    loaded = set_peft_model_state_dict(policy, state, adapter_name='default')
    if loaded.unexpected_keys or any('lora_' in k for k in loaded.missing_keys):
        raise ValueError("Adapter loading left missing or unexpected adapter keys")
    actual = policy.state_dict()
    for key, tensor in state.items():
        target = key.replace('.lora_A.weight', '.lora_A.default.weight').replace(
            '.lora_B.weight', '.lora_B.default.weight')
        if not torch.equal(actual[target].cpu(), tensor.cpu()):
            raise ValueError("Loaded adapter differs from source: " + key)
    policy.requires_grad_(False)
    policy.eval()
    return policy