"""Batched, answer-blind candidate selection extracted from measured code.""" import ast from collections import Counter import re import time import numpy as np import torch import diffusion_runtime as base def forbidden_tokens(context, window, ngram, max_count, eos): """Constraints only inspect resolved left context; EOS is always permitted.""" context = context[-window:] if window else [] banned = {token for token, count in Counter(context).items() if max_count and count >= max_count} if ngram and len(context) >= ngram - 1: suffix = tuple(context[-(ngram - 1):]) if ngram > 1 else () for i in range(len(context) - ngram + 1): if tuple(context[i:i + ngram - 1]) == suffix: banned.add(context[i + ngram - 1]) return banned - set(eos) @torch.inference_mode() def sample_pool(sampler, prompt, cfg, length, seed): """Batched candidate generation, with CPU rejection resampling included in timing.""" model = sampler.model eos_raw = model.config.eos_token_id eos = set(eos_raw if isinstance(eos_raw,list) else [eos_raw]) eos_one = min(eos) pad = model.config.pad_token_id p = prompt.shape[1] count = cfg["best_of"] wave_size = min(count, max(1,4096//(p+length))) rng = np.random.default_rng(seed) prefix_list = prompt[0].tolist() outputs, forwards = [], 0 for start in range(0,count,wave_size): base.check_time(30) batch = min(wave_size,count-start) prefix = prompt.expand(batch,-1) canvas = torch.full((batch,length),pad,device="cuda",dtype=torch.long) mask = torch.ones_like(canvas,dtype=torch.bool) cpu_ids = np.full((batch,length),-1,dtype=np.int64) cpu_lp = np.zeros((batch,length),dtype=np.float64) steps = min(cfg["steps"],length) for step in range(steps): base.check_time(30) ids = torch.cat((prefix,canvas),1) fullmask = torch.cat((torch.zeros_like(prefix,dtype=torch.bool),mask),1) h = sampler.reference(ids,fullmask,p)[:,p:][mask] logits = model.lm_head(h).float() logits[:,pad] = -torch.inf k = min(cfg["top_k"],logits.shape[-1]-1) values, tokens = logits.topk(k,dim=-1) # EOS is a genuine logit candidate even if outside top-k; never synthesize it as a hard-ban violation. eos_values = logits[:,eos_one:eos_one+1] eos_tokens = torch.full_like(tokens[:,:1],eos_one) duplicate = tokens.eq(eos_one).any(-1,keepdim=True) eos_values = eos_values.masked_fill(duplicate,-torch.inf) values = torch.cat((values,eos_values),-1) tokens = torch.cat((tokens,eos_tokens),-1) normalizer = torch.logsumexp(logits/.9,-1).cpu().numpy() raw_values = values.cpu().numpy() token_values = tokens.cpu().numpy() del logits, values, tokens, h forwards += 1 remaining_after = length*(steps-step-1)//steps row_offset = 0 for row in range(batch): positions = np.flatnonzero(cpu_ids[row]<0) commit = len(positions)-remaining_after # Confidence selects slots; ascending positional commits enforce same-step bans. maximum = raw_values[row_offset:row_offset+len(positions),0]/.9-normalizer[row_offset:row_offset+len(positions)] chosen = np.argsort(maximum)[-commit:] for local in sorted(chosen.tolist(),key=lambda x:int(positions[x])): pos = int(positions[local]) idx = row_offset+local left = pos-1 while left>=0 and cpu_ids[row,left]>=0: left -= 1 context = cpu_ids[row,left+1:pos].tolist() if left<0: context = prefix_list+context window_context = context[-cfg["window"]:] if cfg["window"] else [] banned = forbidden_tokens(context,cfg["window"],cfg["ngram"],cfg["max_repeat"],eos) scores = raw_values[idx].astype(np.float64).copy() if cfg["penalty"] != 1: counts = Counter(window_context) for j,token in enumerate(token_values[idx]): if int(token) in counts and int(token) not in eos: penalty = cfg["penalty"]**min(counts[int(token)],3) scores[j] = scores[j]/penalty if scores[j]>=0 else scores[j]*penalty scores /= .9 for j,token in enumerate(token_values[idx]): if int(token) in banned: scores[j] = -np.inf assert np.isfinite(scores).any(), "EOS must remain selectable" probability = np.exp(scores-np.max(scores)) probability /= probability.sum() choice = int(rng.choice(len(scores),p=probability)) token = int(token_values[idx,choice]) assert token not in banned cpu_ids[row,pos] = token cpu_lp[row,pos] = float(raw_values[idx,choice]/.9-normalizer[idx]) row_offset += len(positions) known = cpu_ids>=0 canvas = torch.as_tensor(np.where(known,cpu_ids,pad),device="cuda",dtype=torch.long) mask = torch.as_tensor(~known,device="cuda") for row in range(batch): sequence = cpu_ids[row].tolist() stop = next((i for i,token in enumerate(sequence) if token in eos),len(sequence)) assert all(t>=0 for t in sequence[:stop]) outputs.append({"ids":sequence[:stop],"ended":stop