File size: 12,310 Bytes
a9a1e96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import math
from copy import copy
from contextvars import ContextVar

import torch
from torch import nn
from torch.nn import functional as F

from generation_limits import MAX_BLOCK_SIZE

BLOCK_SIZE = 128
ACTIVE = ContextVar('diffusion_block_start', default=None)


def masks(length, start, subblock, window, device, dtype):
    return attention_masks(length, start, subblock, window, device, dtype)


def attention_masks(length, start, subblock, window, device, dtype, query_start=0, sliding_start=0):
    q = torch.arange(query_start, length, device=device)[:, None]
    k = torch.arange(length, device=device)[None, :]
    allow = (k <= q) | ((q >= start) & ((q-start)//subblock == (k-start)//subblock))
    def additive(visible):
        return torch.zeros_like(visible, dtype=dtype)[None, None].masked_fill(~visible, float('-inf'))
    return {'full_attention': additive(allow),
            'sliding_attention': additive((allow & ((q-k).abs() < window))[:, sliding_start:]),
            'linear_attention': None}


def future_residual(x, taps, start):
    positions = torch.arange(x.shape[1], device=x.device)
    result = torch.zeros_like(x, dtype=torch.float32)
    for offset, tap in enumerate(taps, 1):
        valid = (positions >= start) & (positions + offset < x.shape[1])
        index = (positions + offset).clamp(max=x.shape[1]-1)
        result = result + x[:, index].float() * tap * valid[None, :, None]
    return result






def install_future_convolutions(model):
    from transformers.models.inkling2_loop.modeling_inkling2_loop import (
        Inkling2LoopDynamicShortConvolution, Inkling2LoopShortConvolution,
    )

    for module in list(model.modules()):
        if isinstance(module, Inkling2LoopShortConvolution):
            weight = module.conv1d.weight
            width, device = weight.shape[0], weight.device
            scale = math.sqrt(module.conv_kernel_size + 1)
        elif isinstance(module, Inkling2LoopDynamicShortConvolution):
            width, device = module.static_weight.shape[1], module.static_weight.device
            scale = math.sqrt(2 * module.conv_kernel_size + 1)
        else:
            continue
        module.register_parameter('future_taps', nn.Parameter(torch.zeros(2, width, device=device)))

        def extend(mod, args, out, scale=scale):
            start = ACTIVE.get()
            if start is None:
                return out
            return out + (future_residual(args[0], mod.future_taps, start) / scale).to(out.dtype)

        module.register_forward_hook(extend)


def logits(model, ids, positions, start=None, subblock=BLOCK_SIZE):
    attention = None
    if start is not None:
        config = model.config.text_config
        attention = masks(ids.shape[1], start, subblock, config.sliding_window_size,
                          ids.device, model.get_input_embeddings().weight.dtype)
    context = ACTIVE.set(start)
    try:
        return model(input_ids=ids, attention_mask=attention, use_cache=False,
                     logits_to_keep=positions).logits[0]
    finally:
        ACTIVE.reset(context)


def guarded_candidates(scores, ids, positions, mask_id, stop_ids, suppressed):
    scores[:, mask_id] = -torch.inf
    if suppressed:
        scores[:, suppressed] = -torch.inf
    if stop_ids:
        scores[1:, list(stop_ids)] = -torch.inf
    # Prevent a third identical token after an already-established run.
    previous = ids[0, (positions - 1).clamp_min(0)]
    earlier = ids[0, (positions - 2).clamp_min(0)]
    repeated = (positions >= 2) & (previous == earlier) & (previous != mask_id)
    if stop_ids:
        repeated &= ~torch.isin(previous, positions.new_tensor(list(stop_ids)))
    scores[repeated.nonzero().flatten(), previous[repeated]] = -torch.inf
    confidence, tokens = scores.softmax(-1).max(-1)
    eligible = positions <= positions[0] + 11
    # Adjacent identical guesses deep inside one masked run are often the same
    # marginal repeated, not independent evidence for multiple occurrences.
    eligible[1:] &= ((positions[1:] != positions[:-1] + 1) | (tokens[1:] != tokens[:-1]))
    return confidence.masked_fill(~eligible, -torch.inf), tokens




@torch.no_grad()
def generate(model, ids, mask_id, stop_ids, max_new_tokens=128, threshold=0.9, stats=None, prefix_cache=False,
             block_steps=0, confidence_order=False, guarded=False, suppressed=(), scorer=None,
             block_size=BLOCK_SIZE):
    tokens = []
    for _, _, _, _, tokens, _ in denoise_steps(
        model, ids, mask_id, stop_ids, max_new_tokens, threshold, stats, prefix_cache, block_steps, confidence_order,
        guarded=guarded, suppressed=suppressed, scorer=scorer, block_size=block_size,
    ):
        pass
    return tokens


def fork_prefix_cache(cache):
    """Fork dynamic Inkling cache metadata and writable short-convolution state.

    Dynamic attention updates replace K/V tensor references (torch.cat), so
    the immutable prefix K/V storage itself can be shared with every trial.
    """
    fork = copy(cache)
    fork.layers = []
    for original in cache.layers:
        layer = copy(original)
        for name in ('conv_kernel_size', 'has_previous_state', 'is_conv_states_initialized'):
            setattr(layer, name, copy(getattr(original, name)))
        layer.conv_states = {i: state.clone() if state is not None else None
                             for i, state in original.conv_states.items()}
        layer.cumulative_length_linear = original.cumulative_length_linear.clone()
        fork.layers.append(layer)
    return fork


class BlockPrefix:
    def __init__(self, model):
        self.model = model
        self.cache = None
        self.length = 0
        self.last_logits = None

    def attention(self, ids, diffusion_start):
        window = self.model.config.text_config.sliding_window_size
        active_width = max(1, ids.shape[1] - diffusion_start)
        return attention_masks(ids.shape[1], diffusion_start, active_width, window, ids.device,
                               self.model.get_input_embeddings().weight.dtype, query_start=self.length,
                               sliding_start=max(0, self.length - window + 1))

    @torch.no_grad()
    def commit(self, ids):
        if self.length == ids.shape[1]:
            return False
        out = self.model(input_ids=ids[:, self.length:], attention_mask=self.attention(ids, ids.shape[1]),
                         cache=self.cache, use_cache=True, logits_to_keep=1)
        self.cache = out.cache
        self.last_logits = out.logits[0]
        self.length = ids.shape[1]
        return True

    @torch.no_grad()
    def scores(self, ids, positions, attention):
        # Token shift: the first query's prediction comes from the causal prefix.
        first = positions[0].item() == self.length
        local = positions[int(first):] - self.length - 1
        if not local.numel():
            return self.last_logits.clone()
        context = ACTIVE.set(0)
        try:
            out = self.model(input_ids=ids[:, self.length:], attention_mask=attention,
                             cache=fork_prefix_cache(self.cache), use_cache=True, logits_to_keep=local).logits[0]
        finally:
            ACTIVE.reset(context)
        return torch.cat((self.last_logits, out), dim=0) if first else out


def denoise_steps(model, ids, mask_id, stop_ids, max_new_tokens=128, threshold=0.9, stats=None, prefix_cache=False,
                  block_steps=0, confidence_order=False, one_at_a_time=False, guarded=False, suppressed=(),
                  scorer=None, block_size=BLOCK_SIZE, observe_draft=None):
    if not 1 <= block_size <= MAX_BLOCK_SIZE:
        raise ValueError(f'block_size must be between 1 and {MAX_BLOCK_SIZE}')
    generated = []
    block = 0
    prefix = BlockPrefix(model) if prefix_cache else None
    if scorer is not None and prefix is not None and not hasattr(scorer, 'begin_block'):
        raise ValueError('A custom scorer cannot be combined with prefix caching')

    def evaluate(positions):
        if scorer is not None:
            return scorer(ids, positions, start)
        if prefix is not None:
            return prefix.scores(ids, positions, attention)
        return logits(model, ids, positions-1, start, subblock=ids.shape[1]-start)
    while len(generated) < max_new_tokens:
        block += 1
        start = ids.shape[1]
        width = min(block_size, max_new_tokens-len(generated))
        yield block, 0, width, 0, list(generated), [mask_id] * width
        if prefix is not None:
            commit = getattr(scorer, 'commit_prefix', None)
            committed = prefix.commit(ids) if commit is None else commit(prefix, ids)
            if committed and stats is not None:
                stats['cache_commits'] = stats.get('cache_commits', 0) + 1
        ids = torch.cat([ids, ids.new_full((1, width), mask_id)], dim=1)
        attention = prefix.attention(ids, start) if prefix is not None else None
        if prefix is not None and scorer is not None:
            scorer.begin_block(prefix, ids, attention)
        cursor = start
        step = 0
        block_start = len(generated)
        if confidence_order:
            while True:
                positions = (ids[0, start:] == mask_id).nonzero().flatten() + start
                if not positions.numel():
                    break
                with torch.no_grad():
                    scores = evaluate(positions)
                    if guarded:
                        confidence, tokens = guarded_candidates(scores, ids, positions, mask_id, stop_ids, suppressed)
                    else:
                        scores[:, mask_id] = -torch.inf
                        confidence, tokens = scores.softmax(-1).max(-1)
                step += 1
                if stats is not None:
                    stats['forwards'] += 1
                count = max(1, int((confidence >= threshold).sum().item()))
                if block_steps:
                    count = max(count, math.ceil(len(positions) / max(1, block_steps-step+1)))
                if one_at_a_time:
                    count = 1
                elif guarded:
                    count = min(count, int(confidence.isfinite().sum().item()))
                if one_at_a_time and confidence.max().item() < threshold:
                    chosen = positions.new_zeros(1)
                else:
                    chosen = confidence.topk(count).indices
                ids[0, positions[chosen]] = tokens[chosen]
                if observe_draft is not None:
                    observe_draft(torch.stack((positions - start, tokens)).tolist())
                cells = ids[0, start:].tolist()
                visible = []
                stopped = False
                for token in cells:
                    if token == mask_id:
                        break
                    if token in stop_ids:
                        stopped = True
                        break
                    visible.append(token)
                yield block, step, width, width-cells.count(mask_id), generated + visible, cells
                if stopped:
                    return
            generated.extend(cells)
            continue
        while cursor < start + width:
            positions = torch.arange(cursor, start+width, device=ids.device)
            with torch.no_grad():
                scores = evaluate(positions)
            step += 1
            if stats is not None:
                stats['forwards'] += 1
            scores[:, mask_id] = -torch.inf
            confidence, tokens = scores.softmax(-1).max(-1)
            low = (confidence < threshold).nonzero()
            count = max(1, int(low[0, 0])) if low.numel() else len(positions)
            if block_steps:
                count = max(count, math.ceil(len(positions) / max(1, block_steps-step+1)))
            ids[0, cursor:cursor+count] = tokens[:count]
            cursor += count
            for token in tokens[:count].tolist():
                if token in stop_ids:
                    yield block, step, width, len(generated)-block_start, list(generated), ids[0, start:].tolist()
                    return
                generated.append(token)
            yield block, step, width, len(generated)-block_start, list(generated), ids[0, start:].tolist()