from bisect import bisect_left,bisect_right import gzip import hashlib import json from pathlib import Path import numpy as np from tqdm import tqdm from functional_rl import v2 from refined_math.loss import AnswerCorpus from refined_v4.data import load_rows from refined_v4.train import TokenCorpus,atomic_json class EndingCorpus(AnswerCorpus): def __init__(self,path: Path,budget: int,retain_prefix: bool,factor: float,report_path: Path,completion_only: bool=False): if not retain_prefix: raise ValueError('Code suffix weighting requires the complete supplied function context') TokenCorpus.__init__(self,path,budget,retain_prefix) self.preserve_context=True self.completion_only=completion_only root=path.parents[2] rows=load_rows(root,path.parent.name,'sft') lookup={row['source_id']:row for row in rows} if len(lookup)!=len(rows): raise ValueError('SFT source IDs must identify individual implementations uniquely') self.weights=[] previous=suffix_targets=0 weight_sum=0. with gzip.open(path,'rt') as stream: for index,line in enumerate(tqdm(stream,desc='Weight implementation endings',colour='cyan',mininterval=10)): if index==len(self.documents): break document=json.loads(line) ids=self.documents[index].tolist() ends=np.cumsum([len(v2.ENC.decode_single_token_bytes(t)) for t in ids]).tolist() starts=[0]+ends[:-1] selected=np.zeros(len(ids),dtype=bool) if completion_only: from .envs import make_episode if document.get('objective')!='query_completion_only': raise ValueError('Completion-only training requires matched query-suffix documents') row=lookup[document['query_source_id']] demos=[lookup[key] for key in document['demo_source_ids']] episode=make_episode(dict(row,demonstrations=demos),document['hint_level']) if episode.prompt+episode.completion!=document['text']: raise ValueError('Matched completion prompt differs from its benchmark source') first=document['completion_start'] if ids[first:first+document['hint_level']]!=document['completion_ids']: raise ValueError('Loss targets differ from the exact native missing token IDs') selected[first:first+document['hint_level']]=True else: rendered,spans,offset=[],[],0 for example in document['examples']: row=lookup[example['source_id']] if hashlib.sha256(row['reference'].encode()).hexdigest()!=example['reference_sha256']: raise ValueError('SFT source reference differs from immutable document metadata') text=v2.render(row) start=offset+len((v2.header(row)+row['protected_prefix']).encode()) end=offset+len(text.encode()) spans.append((start,end)) rendered.append(text) offset=end+2 if '\n\n'.join(rendered)!=document['text']: raise ValueError('Cannot reconstruct benchmark-native SFT document') for start,end in spans: first=bisect_right(ends,start) last=bisect_left(starts,end) selected[max(first,last-16):last]=True weights=np.zeros(len(ids),dtype=np.float32) if completion_only else np.ones(len(ids),dtype=np.float32) weights[selected]=factor count=self.ends[index]-previous previous=self.ends[index] suffix_targets+=int(selected[1:count+1].sum()) normalizer=float(weights[1:count+1].sum()) if normalizer: weights*=count/normalizer weight_sum+=float(weights[1:count+1].sum(dtype=np.float64)) self.weights.append(weights) atomic_json(report_path,dict(input_prediction_tokens=budget,ending_prediction_tokens=suffix_targets, factor=factor,normalized_weight_sum=weight_sum, completion_only=completion_only, objective=('Fixed input-position budget; supervise the sampled missing query suffix only, normalized per document.' if completion_only else 'All declared input predictions remain supervised. Weight the last up-to-16 implementation tokens, normalized per document.'))) def take(self,start: int,count: int): examples=super().take(start,count) if self.completion_only: for example in examples: example.mask=[int(chosen and weight>0) for chosen,weight in zip(example.mask,example.weights,strict=True)] return examples