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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import time
|
| 5 |
+
import re
|
| 6 |
+
from collections import Counter
|
| 7 |
+
from transformers import AutoTokenizer, AutoModel
|
| 8 |
+
|
| 9 |
+
def add_gumbel_noise(logits, temperature):
|
| 10 |
+
if temperature == 0:
|
| 11 |
+
return logits
|
| 12 |
+
logits = logits.to(torch.float64)
|
| 13 |
+
noise = torch.rand_like(logits, dtype=torch.float64)
|
| 14 |
+
gumbel_noise = (- torch.log(noise)) ** temperature
|
| 15 |
+
return logits.exp() / gumbel_noise
|
| 16 |
+
|
| 17 |
+
def get_num_transfer_tokens(block_mask_index: torch.Tensor, steps: int) -> torch.Tensor:
|
| 18 |
+
device = block_mask_index.device
|
| 19 |
+
dtype = torch.long
|
| 20 |
+
total = block_mask_index.sum(dim=1)
|
| 21 |
+
base = torch.div(total, steps, rounding_mode='floor')
|
| 22 |
+
rem = total - base * steps
|
| 23 |
+
num_transfer_tokens = base.unsqueeze(1).expand(-1, steps).to(dtype)
|
| 24 |
+
cols = torch.arange(steps, device=device).unsqueeze(0)
|
| 25 |
+
add_mask = cols < rem.unsqueeze(1)
|
| 26 |
+
num_transfer_tokens = num_transfer_tokens + add_mask.to(dtype)
|
| 27 |
+
return num_transfer_tokens
|
| 28 |
+
|
| 29 |
+
# =================================================================
|
| 30 |
+
# [수정됨] top_prob_margin 지원 추가
|
| 31 |
+
# =================================================================
|
| 32 |
+
def get_transfer_index(logits, temperature, remasking, mask_index, x, num_transfer_tokens, threshold=None):
|
| 33 |
+
# 1) Sample proposal x0
|
| 34 |
+
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
|
| 35 |
+
x0 = torch.argmax(logits_with_noise, dim=-1)
|
| 36 |
+
|
| 37 |
+
# 2) Confidence for chosen tokens
|
| 38 |
+
if remasking == "low_confidence":
|
| 39 |
+
p = F.softmax(logits.to(torch.float64), dim=-1)
|
| 40 |
+
x0_p = torch.gather(p, dim=-1, index=x0.unsqueeze(-1)).squeeze(-1)
|
| 41 |
+
|
| 42 |
+
# [여기 추가됨!] top_prob_margin 로직 복원
|
| 43 |
+
elif remasking == "top_prob_margin":
|
| 44 |
+
p = F.softmax(logits.to(torch.float64), dim=-1)
|
| 45 |
+
top2_probs, _ = torch.topk(p, k=2, dim=-1)
|
| 46 |
+
x0_p = top2_probs[..., 0] - top2_probs[..., 1]
|
| 47 |
+
|
| 48 |
+
elif remasking == "random":
|
| 49 |
+
x0_p = torch.rand(x0.shape, device=x0.device, dtype=torch.float64)
|
| 50 |
+
else:
|
| 51 |
+
raise NotImplementedError(remasking)
|
| 52 |
+
|
| 53 |
+
# Only modify masked spots
|
| 54 |
+
x0 = torch.where(mask_index, x0, x)
|
| 55 |
+
neg_inf = torch.tensor(torch.finfo(x0_p.dtype).min, device=x0_p.device, dtype=x0_p.dtype)
|
| 56 |
+
confidence = torch.where(mask_index, x0_p, neg_inf)
|
| 57 |
+
|
| 58 |
+
# 3) Pick positions to transfer
|
| 59 |
+
if threshold is not None:
|
| 60 |
+
transfer_index = mask_index & (confidence >= threshold)
|
| 61 |
+
max_conf_indices = torch.argmax(confidence, dim=1, keepdim=True)
|
| 62 |
+
force_mask = torch.zeros_like(transfer_index).scatter_(1, max_conf_indices, True)
|
| 63 |
+
transfer_index = transfer_index | force_mask
|
| 64 |
+
transfer_index = transfer_index & mask_index
|
| 65 |
+
return x0, transfer_index
|
| 66 |
+
|
| 67 |
+
if num_transfer_tokens is None:
|
| 68 |
+
raise ValueError("num_transfer_tokens must be a tensor when threshold is None.")
|
| 69 |
+
|
| 70 |
+
if num_transfer_tokens.dim() == 2 and num_transfer_tokens.size(1) == 1:
|
| 71 |
+
num_transfer_tokens = num_transfer_tokens.squeeze(1)
|
| 72 |
+
num_transfer_tokens = num_transfer_tokens.to(dtype=torch.long, device=confidence.device)
|
| 73 |
+
num_transfer_tokens = torch.clamp(num_transfer_tokens, min=0)
|
| 74 |
+
|
| 75 |
+
values, idx = torch.sort(confidence, dim=1, descending=True)
|
| 76 |
+
B, L = confidence.shape
|
| 77 |
+
cols = torch.arange(L, device=confidence.device).unsqueeze(0).expand(B, L)
|
| 78 |
+
k_expanded = num_transfer_tokens.unsqueeze(1).expand(B, L)
|
| 79 |
+
select_sorted = cols < k_expanded
|
| 80 |
+
|
| 81 |
+
transfer_int = torch.zeros(B, L, device=confidence.device, dtype=torch.int8)
|
| 82 |
+
transfer_int = transfer_int.scatter(1, idx, select_sorted.to(torch.int8))
|
| 83 |
+
transfer_index = transfer_int.bool() & mask_index
|
| 84 |
+
|
| 85 |
+
return x0, transfer_index
|
| 86 |
+
|
| 87 |
+
# =================================================================
|
| 88 |
+
# [수정됨] top_prob_margin 지원 추가 (Dynamic 버전)
|
| 89 |
+
# =================================================================
|
| 90 |
+
def get_transfer_index_dynamic(logits, temperature, remasking, mask_index, x, num_transfer_tokens, factor=1):
|
| 91 |
+
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
|
| 92 |
+
x0 = torch.argmax(logits_with_noise, dim=-1)
|
| 93 |
+
|
| 94 |
+
if remasking == 'low_confidence':
|
| 95 |
+
p = F.softmax(logits.to(torch.float64), dim=-1)
|
| 96 |
+
x0_p = torch.squeeze(torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1)
|
| 97 |
+
|
| 98 |
+
# [여기 추가됨!] top_prob_margin 로직 복원
|
| 99 |
+
elif remasking == 'top_prob_margin':
|
| 100 |
+
p = F.softmax(logits.to(torch.float64), dim=-1)
|
| 101 |
+
top2_probs, _ = torch.topk(p, k=2, dim=-1)
|
| 102 |
+
x0_p = top2_probs[..., 0] - top2_probs[..., 1]
|
| 103 |
+
|
| 104 |
+
elif remasking == 'random':
|
| 105 |
+
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
|
| 106 |
+
else:
|
| 107 |
+
raise NotImplementedError(remasking)
|
| 108 |
+
|
| 109 |
+
x0 = torch.where(mask_index, x0, x)
|
| 110 |
+
confidence = torch.where(mask_index, x0_p, -np.inf)
|
| 111 |
+
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
|
| 112 |
+
num_transfer_tokens = mask_index.sum(dim=1, keepdim=True)
|
| 113 |
+
|
| 114 |
+
for j in range(confidence.shape[0]):
|
| 115 |
+
num_tokens = int(num_transfer_tokens[j].item())
|
| 116 |
+
if num_tokens == 0: continue
|
| 117 |
+
|
| 118 |
+
ns = list(range(1, num_transfer_tokens[j] + 1))
|
| 119 |
+
es = [factor / (n + 1) for n in ns]
|
| 120 |
+
threshs = [1 - e for e in es]
|
| 121 |
+
threshs[0] = -1
|
| 122 |
+
|
| 123 |
+
sorted_confidence = torch.sort(confidence[j][mask_index[j]], dim=-1, descending=True)[0]
|
| 124 |
+
top_i = len(threshs)
|
| 125 |
+
for i in range(len(threshs)):
|
| 126 |
+
if sorted_confidence[i] < threshs[i]:
|
| 127 |
+
top_i = i
|
| 128 |
+
break
|
| 129 |
+
if top_i == 0: top_i = 1
|
| 130 |
+
|
| 131 |
+
_, select_index = torch.topk(confidence[j], k=top_i)
|
| 132 |
+
transfer_index[j, select_index] = True
|
| 133 |
+
|
| 134 |
+
return x0, transfer_index
|
| 135 |
+
|
| 136 |
+
# =================================================================
|
| 137 |
+
# generate_standard (기존 함수)
|
| 138 |
+
# =================================================================
|
| 139 |
+
@ torch.no_grad()
|
| 140 |
+
def generate_standard(model, prompt, attention_mask=None, steps=128, gen_length=128, block_length=128, temperature=0.,
|
| 141 |
+
cfg_scale=0., remasking='low_confidence', mask_id=126336, logits_eos_inf=False, confidence_eos_eot_inf=False):
|
| 142 |
+
x = torch.full((prompt.shape[0], prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
|
| 143 |
+
x[:, :prompt.shape[1]] = prompt.clone()
|
| 144 |
+
|
| 145 |
+
if attention_mask is not None:
|
| 146 |
+
attention_mask = torch.cat([attention_mask, torch.ones((prompt.shape[0], gen_length), dtype=attention_mask.dtype, device=model.device)], dim=-1)
|
| 147 |
+
|
| 148 |
+
prompt_index = (x != mask_id)
|
| 149 |
+
assert gen_length % block_length == 0
|
| 150 |
+
num_blocks = gen_length // block_length
|
| 151 |
+
assert steps % num_blocks == 0
|
| 152 |
+
steps = steps // num_blocks
|
| 153 |
+
|
| 154 |
+
for num_block in range(num_blocks):
|
| 155 |
+
block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length] == mask_id)
|
| 156 |
+
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
|
| 157 |
+
|
| 158 |
+
for i in range(steps):
|
| 159 |
+
mask_index = (x == mask_id)
|
| 160 |
+
if cfg_scale > 0.:
|
| 161 |
+
un_x = x.clone()
|
| 162 |
+
un_x[prompt_index] = mask_id
|
| 163 |
+
x_ = torch.cat([x, un_x], dim=0)
|
| 164 |
+
if attention_mask is not None:
|
| 165 |
+
attention_mask_ = torch.cat([attention_mask, attention_mask], dim=0)
|
| 166 |
+
logits = model(x_, attention_mask=attention_mask_).logits
|
| 167 |
+
logits, un_logits = torch.chunk(logits, 2, dim=0)
|
| 168 |
+
logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
|
| 169 |
+
else:
|
| 170 |
+
logits = model(x, attention_mask=attention_mask).logits
|
| 171 |
+
|
| 172 |
+
if logits_eos_inf:
|
| 173 |
+
logits[:, :, 126081] = -torch.inf
|
| 174 |
+
|
| 175 |
+
logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
|
| 176 |
+
x0 = torch.argmax(logits_with_noise, dim=-1)
|
| 177 |
+
|
| 178 |
+
if confidence_eos_eot_inf:
|
| 179 |
+
logits_with_noise[:, :, 126081] = logits[:, :, 126348] = -torch.inf
|
| 180 |
+
|
| 181 |
+
if remasking == 'low_confidence':
|
| 182 |
+
p = F.softmax(logits, dim=-1)
|
| 183 |
+
x0_p = torch.squeeze(torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1)
|
| 184 |
+
elif remasking == 'top_prob_margin':
|
| 185 |
+
p = F.softmax(logits, dim=-1)
|
| 186 |
+
top2_probs, _ = torch.topk(p, k=2, dim=-1)
|
| 187 |
+
x0_p = top2_probs[:, :, 0] - top2_probs[:, :, 1]
|
| 188 |
+
elif remasking == 'random':
|
| 189 |
+
x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
|
| 190 |
+
else:
|
| 191 |
+
raise NotImplementedError(remasking)
|
| 192 |
+
|
| 193 |
+
x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
|
| 194 |
+
x0 = torch.where(mask_index, x0, x)
|
| 195 |
+
confidence = torch.where(mask_index, x0_p, -np.inf)
|
| 196 |
+
|
| 197 |
+
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
|
| 198 |
+
for j in range(confidence.shape[0]):
|
| 199 |
+
_, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
|
| 200 |
+
transfer_index[j, select_index] = True
|
| 201 |
+
x[transfer_index] = x0[transfer_index]
|
| 202 |
+
return x
|
| 203 |
+
|
| 204 |
+
# =================================================================
|
| 205 |
+
# generate_with_dual_cache (최적화 함수)
|
| 206 |
+
# =================================================================
|
| 207 |
+
@torch.no_grad()
|
| 208 |
+
def generate_with_dual_cache(
|
| 209 |
+
model, prompt, steps=128, gen_length=128, block_length=128, temperature=0.,
|
| 210 |
+
remasking="low_confidence", mask_id=126336, threshold=None, factor=None,
|
| 211 |
+
cfg_scale=0., logits_eos_inf=False, confidence_eos_eot_inf=False, attention_mask=None
|
| 212 |
+
):
|
| 213 |
+
if cfg_scale > 0:
|
| 214 |
+
print("⚠️ Warning: cfg_scale > 0 is not supported in Dual Cache mode. Falling back to standard generate.")
|
| 215 |
+
return generate_standard(model, prompt, attention_mask, steps, gen_length, block_length, temperature, cfg_scale, remasking, mask_id, logits_eos_inf, confidence_eos_eot_inf)
|
| 216 |
+
|
| 217 |
+
B = prompt.shape[0]
|
| 218 |
+
Lp = int(prompt.shape[1])
|
| 219 |
+
|
| 220 |
+
assert gen_length % block_length == 0
|
| 221 |
+
num_blocks = gen_length // block_length
|
| 222 |
+
assert steps % num_blocks == 0
|
| 223 |
+
steps_per_block = steps // num_blocks
|
| 224 |
+
|
| 225 |
+
x = torch.full((B, Lp + gen_length), mask_id, dtype=torch.long, device=model.device)
|
| 226 |
+
x[:, :Lp] = prompt
|
| 227 |
+
|
| 228 |
+
nfe = 0
|
| 229 |
+
for nb in range(num_blocks):
|
| 230 |
+
s = Lp + nb * block_length
|
| 231 |
+
e = s + block_length
|
| 232 |
+
|
| 233 |
+
block_mask_index = (x[:, s:e] == mask_id)
|
| 234 |
+
num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps_per_block)
|
| 235 |
+
|
| 236 |
+
# 1) Warm KV-cache
|
| 237 |
+
out_full = model(x, use_cache=True)
|
| 238 |
+
past_key_values = out_full.past_key_values
|
| 239 |
+
nfe += 1
|
| 240 |
+
|
| 241 |
+
replace_position = torch.zeros_like(x, dtype=torch.bool)
|
| 242 |
+
replace_position[:, s:e] = True
|
| 243 |
+
|
| 244 |
+
global_mask_index = (x == mask_id)
|
| 245 |
+
global_mask_index[:, e:] = False
|
| 246 |
+
|
| 247 |
+
if factor is None:
|
| 248 |
+
quota0 = None if threshold is not None else num_transfer_tokens[:, 0]
|
| 249 |
+
# 여기 remasking 인자가 'top_prob_margin'이어도 이제 작동함
|
| 250 |
+
x0, transfer_index = get_transfer_index(
|
| 251 |
+
out_full.logits, temperature, remasking, global_mask_index, x, quota0, threshold
|
| 252 |
+
)
|
| 253 |
+
else:
|
| 254 |
+
x0, transfer_index = get_transfer_index_dynamic(
|
| 255 |
+
out_full.logits, temperature, remasking, global_mask_index, x, None, factor
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
x = torch.where(transfer_index, x0, x)
|
| 259 |
+
|
| 260 |
+
for i in range(1, steps_per_block):
|
| 261 |
+
if (x[:, s:e] == mask_id).sum() == 0:
|
| 262 |
+
break
|
| 263 |
+
try:
|
| 264 |
+
logits_blk = model(
|
| 265 |
+
x[:, s:e], past_key_values=past_key_values, use_cache=True, replace_position=replace_position
|
| 266 |
+
).logits
|
| 267 |
+
except TypeError:
|
| 268 |
+
logits_blk = model(
|
| 269 |
+
x[:, s:e], past_key_values=past_key_values, use_cache=True
|
| 270 |
+
).logits
|
| 271 |
+
|
| 272 |
+
mask_blk = (x[:, s:e] == mask_id)
|
| 273 |
+
|
| 274 |
+
if factor is None:
|
| 275 |
+
quota_i = None if threshold is not None else num_transfer_tokens[:, i]
|
| 276 |
+
x0_blk, transfer_idx_blk = get_transfer_index(
|
| 277 |
+
logits_blk, temperature, remasking, mask_blk, x[:, s:e], quota_i, threshold
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
x0_blk, transfer_idx_blk = get_transfer_index_dynamic(
|
| 281 |
+
logits_blk, temperature, remasking, mask_blk, x[:, s:e], None, factor
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
blk_old = x[:, s:e]
|
| 285 |
+
blk_new = torch.where(transfer_idx_blk, x0_blk, blk_old)
|
| 286 |
+
x = torch.cat([x[:, :s], blk_new, x[:, e:]], dim=1)
|
| 287 |
+
nfe += 1
|
| 288 |
+
|
| 289 |
+
return x
|
| 290 |
+
|
| 291 |
+
# Alias
|
| 292 |
+
generate = generate_standard
|