Token Classification
lora
File size: 7,422 Bytes
86599c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Apply the token attribution path to the 40-layer Nippers MoE backbone."""
import copy
from types import MethodType

import torch
from torch import nn
from torch.utils.checkpoint import checkpoint as recompute
from transformers.masking_utils import create_causal_mask, create_recurrent_attention_mask
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import apply_rotary_pos_emb

from detector_runtime.model import gpu_environment, load_model
from model import AttributionPath


class LinearChunkPool(nn.Module):
    """Extend the Jev pair pooler to fixed-width chunks using their endpoints."""

    def __init__(self, width, stride):
        super().__init__()
        self.stride = stride
        self.linear = nn.Linear(2 * width, width, bias=False)
        nn.init.zeros_(self.linear.weight)

    def forward(self, memory, lengths):
        _, width, dim = memory.shape
        starts = torch.arange(0, width, self.stride, device=memory.device)
        ends = torch.minimum(starts + self.stride - 1, lengths[:, None] - 1)
        valid = starts < lengths[:, None]
        safe_starts = torch.minimum(starts, lengths[:, None] - 1)
        first = memory.gather(1, safe_starts[:, :, None].expand(-1, -1, dim))
        last = memory.gather(1, ends[:, :, None].expand(-1, -1, dim))
        pooled = self.pool_endpoints(first, last, safe_starts != ends)
        return pooled.masked_fill(~valid[:, :, None], 0), ends, valid

    def pool_endpoints(self, first, last, multiple_tokens):
        mean = (first.float() + last.float()).mul_(0.5).to(last.dtype)
        pooled = mean + self.linear(torch.cat((first, last), dim=-1)).to(last.dtype)
        # Match the Jev singleton bypass.
        return torch.where(multiple_tokens.unsqueeze(-1), pooled, last)


def route_eight(self, hidden):
    logits = nn.functional.linear(hidden.reshape(-1, self.hidden_dim), self.weight)
    values, indices = logits.float().softmax(-1).topk(8, dim=-1)
    return logits, (values / values.sum(-1, keepdim=True)).to(logits.dtype), indices


class AIDetector35BA3B(AttributionPath):
    rotary = staticmethod(apply_rotary_pos_emb)

    def __init__(self, base, checkpoint, decoder_stride, config):
        super().__init__()
        config = {**config, "base_model": base}
        self.environment = gpu_environment(config)
        loaded = load_model(config)
        self.backbone = loaded.backbone
        self.native_linear_pool = config.get("native_linear_pool", False)
        all_token_pool = config.get("attention_query_pool", False)
        if all_token_pool and (decoder_stride != 64 or self.native_linear_pool):
            raise ValueError("All-token pooling requires stride 64 and decoder retrieval")
        if checkpoint is None and not self.native_linear_pool and not all_token_pool:
            raise ValueError("An initialization checkpoint is required for the retrieval model")
        if not self.native_linear_pool:
            donor_layer = self.backbone.layers[23]
            if donor_layer.block_type != "full_attention":
                raise ValueError("Retrieval donor must be a full-attention layer")
            self.donor = nn.Module()
            self.donor.self_attn = copy.deepcopy(donor_layer.self_attn)
            self.donor.input_layernorm = copy.deepcopy(donor_layer.input_layernorm)
            self.donor.float().requires_grad_(True)
        loaded.add_adapters(config, [list(range(config["experts_per_layer"])) for _ in self.backbone.layers])
        self.backbone.gradient_checkpointing_disable()
        del loaded
        for layer in self.backbone.layers:
            layer.mlp.gate.forward = MethodType(route_eight, layer.mlp.gate)
        if checkpoint is not None:
            expected = {key for key, value in self.named_parameters() if value.requires_grad}
            saved = torch.load(checkpoint, map_location="cpu", weights_only=True, mmap=True)
            if saved["step"] != config["initialization_step"]:
                raise ValueError("Unexpected starting checkpoint")
            inherited = {key: value for key, value in saved["model"].items() if key in expected}
            if set(inherited) != expected:
                raise ValueError(f"Missing inherited detector weights: {sorted(expected - set(inherited))}")
            self.load_state_dict(inherited, strict=False)
            del inherited, saved
        torch.manual_seed(config["seed"])
        self.configure_attribution(config["encoder_layers"], decoder_stride, checkpoint_decoder=True)
        if all_token_pool:
            from model import ChunkAttentionPool
            self.attention_pool = ChunkAttentionPool(self.backbone.config.hidden_size)
        if self.native_linear_pool:
            self.pool = LinearChunkPool(self.backbone.config.hidden_size, decoder_stride)

    def decode(self, memory, pos, lengths):
        if not self.native_linear_pool:
            return super().decode(memory, pos, lengths)
        hidden, anchors, valid = self.pool(memory, lengths)
        rope = self.backbone.rotary_emb(hidden, anchors.unsqueeze(0).expand(3, -1, -1))
        mask_kwargs = dict(config=self.backbone.config, inputs_embeds=hidden,
                           attention_mask=valid, past_key_values=None, position_ids=None)
        masks = {
            "full_attention": create_causal_mask(**mask_kwargs),
            "linear_attention": create_recurrent_attention_mask(**mask_kwargs),
        }
        for layer in self.backbone.layers[self.split:]:
            kwargs = dict(position_embeddings=rope, attention_mask=masks[layer.block_type],
                          position_ids=anchors, past_key_values=None, use_cache=False)
            if self.training and self.checkpoint_decoder:
                hidden = recompute(layer, hidden, use_reentrant=False, **kwargs)
            else:
                hidden = layer(hidden, **kwargs)
        return self.backbone.norm(hidden)

    def enable_compile(self):
        # Match the previous A100 training recipe. The custom grouped GEMMs remain
        # Triton calls; Inductor compiles the surrounding PyTorch operations.
        import torch._functorch.config
        import torch._dynamo.config
        import torch._inductor.config
        torch._functorch.config.backward_pass_autocast = "off"
        torch._inductor.config.emulate_precision_casts = True
        torch._inductor.config.shape_padding = False
        torch._inductor.config.comprehensive_padding = False
        torch._dynamo.config.suppress_errors = False
        torch._dynamo.config.recompile_limit = 64
        # Buffer the different shapes of full-token and compressed execution in
        # the same manner as the original inference path, without CUDA graphs.
        opts = dict(dynamic=True, fullgraph=False, backend="inductor",
                    options={"triton.cudagraphs": False})
        for i, layer in enumerate(self.backbone.layers):
            if self.native_linear_pool or i < self.split or layer.block_type == "linear_attention":
                layer.forward = torch.compile(layer.forward, **opts)
            else:
                # Full-attention decoder blocks use encoder retrieval instead
                # of their original forward; compile their actual MLP call.
                layer.mlp.forward = torch.compile(layer.mlp.forward, **opts)
        if not self.native_linear_pool:
            self.retrieve = torch.compile(self.retrieve, **opts)