Diffusion-Inkling-2-mini / block_diffusion.py
summerAIO's picture
Release merged diffusion checkpoint and bilingual model card
a9a1e96 verified
Raw History Blame Contribute Delete
12.3 kB
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()