File size: 4,635 Bytes
e30ad40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Intervention via projection-removal hooks — v32b.

    h_new = h - (1 - alpha) * D^T D h

alpha=1 -> no-op, alpha=0 -> full removal.

QwQ-32B uses the same `model.model.layers[L]` indexing as Qwen3, so
this code is structurally identical to v12. Default decode is sampling
(temp=0.6, top_p=0.95) per DS-R1-Distill's recommendation — DO NOT use greedy,
DS-R1-Distill degenerates into endless repetition.
"""
from typing import Dict, Optional
import torch


def _make_hook(D: torch.Tensor, alpha: float):
    coef = 1.0 - float(alpha)

    def hook(module, inputs, outputs):
        if coef <= 1e-6:
            return outputs
        h = outputs[0] if isinstance(outputs, tuple) else outputs
        orig_dtype = h.dtype
        h_f = h.float()
        D_f = D.to(h_f.device).float()
        proj_coef = torch.einsum("bsh,kh->bsk", h_f, D_f)
        recon     = torch.einsum("bsk,kh->bsh", proj_coef, D_f)
        h_new = (h_f - coef * recon).to(orig_dtype)
        if isinstance(outputs, tuple):
            return (h_new,) + outputs[1:]
        return h_new
    return hook


def _generate(model, tokenizer, prompt, device, max_new_tokens,
              do_sample: bool = True,
              temperature: float = 0.6,
              top_p: float = 0.95,
              seed: Optional[int] = None):
    """Generate. DS-R1-Distill default = sampling (greedy is unsafe for QwQ-32B)."""
    model.eval()
    inp = tokenizer(prompt, return_tensors="pt",
                    truncation=True, max_length=4096).to(device)
    if do_sample and seed is not None:
        torch.manual_seed(int(seed))
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(int(seed))
    gen_kwargs = dict(
        max_new_tokens=max_new_tokens,
        do_sample=bool(do_sample),
        temperature=float(temperature) if do_sample else 1.0,
        top_p=float(top_p) if do_sample else 1.0,
        pad_token_id=tokenizer.eos_token_id,
    )
    with torch.no_grad():
        out = model.generate(**inp, **gen_kwargs)
    full = tokenizer.decode(out[0], skip_special_tokens=True)
    prompt_text = tokenizer.decode(inp["input_ids"][0], skip_special_tokens=True)
    if full.startswith(prompt_text):
        gen = full[len(prompt_text):]
    else:
        gen = full
    # Defensive BPE-artifact normalization. Stage 00 cleans its own
    # outputs; stages 03/04 also generate fresh text and need the same
    # fix, or the BehaviorDetector regex never matches (Ġ destroys the
    # \b word boundaries — every "wait", "maybe", "perhaps" gets read
    # as "Ġwait" with no boundary on the left).
    from src.utils import normalize_bpe_artifacts
    return normalize_bpe_artifacts(gen)


def generate_with_alpha(model, tokenizer, prompt,
                        directions_per_layer, alpha_per_layer,
                        device, max_new_tokens=2048,
                        do_sample: bool = True,
                        temperature: float = 0.6,
                        top_p: float = 0.95,
                        seed: Optional[int] = None):
    handles = []
    for lid, D in directions_per_layer.items():
        a = float(alpha_per_layer.get(lid, 1.0))
        if a >= 1.0 - 1e-6 or D is None or D.numel() == 0:
            continue
        try:
            mod_device = next(model.model.layers[lid].parameters()).device
        except StopIteration:
            mod_device = device
        handles.append(
            model.model.layers[lid].register_forward_hook(
                _make_hook(D.to(mod_device), a)
            )
        )
    try:
        return _generate(model, tokenizer, prompt, device, max_new_tokens,
                         do_sample=do_sample, temperature=temperature,
                         top_p=top_p, seed=seed)
    finally:
        for h in handles:
            h.remove()


def generate_plain(model, tokenizer, prompt, device, max_new_tokens=2048,
                   do_sample: bool = True,
                   temperature: float = 0.6,
                   top_p: float = 0.95,
                   seed: Optional[int] = None):
    return _generate(model, tokenizer, prompt, device, max_new_tokens,
                     do_sample=do_sample, temperature=temperature,
                     top_p=top_p, seed=seed)


def global_alpha_to_per_layer(alpha: float,
                              best_alpha_per_layer: Dict[int, float]) -> Dict[int, float]:
    """eff[L] = global + (1-global) * per_layer[L]. Same as v12."""
    alpha = max(0.0, min(1.0, alpha))
    return {
        lid: alpha + (1.0 - alpha) * max(0.0, min(1.0, float(ba)))
        for lid, ba in best_alpha_per_layer.items()
    }