"""Legacy protocol compatibility and deterministic HF data loading.""" import math import numpy as np import torch from torch.utils.data import Dataset,Sampler from datasets import load_from_disk from experiments_codebase.paths import paths def seed_for(seed, stream, step=0): """由总种子、用途编号和步数隔开数据采样、训练和选基的随机流。""" return int(np.random.SeedSequence([seed, stream, step]).generate_state(1, dtype=np.uint64)[0] % (2 ** 63 - 1)) class HFDataset(Dataset): def __init__(self,rows):self.data=rows def __len__(self):return len(self.data) def __getitem__(self,index):return self.data[index] class ProtocolSampler(Sampler): """Same independent PCG batch-order stream as the previous implementation.""" def __init__(self,dataset,seed):self.dataset=dataset;self.rng=np.random.default_rng(seed_for(seed,11)) def __iter__(self):return iter(self.rng.permutation(len(self.dataset)).tolist()) def __len__(self):return len(self.dataset) class LegacyCollator: def __init__(self,tokenizer):self.tokenizer=tokenizer def __call__(self,rows): width=math.ceil(max(len(r['input_ids']) for r in rows)/8)*8 ids=torch.full((len(rows),width),self.tokenizer.pad_token_id,dtype=torch.long) mask=torch.zeros_like(ids);targets=torch.full_like(ids,-100) for i,row in enumerate(rows): size=len(row['input_ids']);ids[i,-size:]=torch.tensor(row['input_ids']);mask[i,-size:]=1 if row.get('answer_length',0):targets[i,-row['answer_length']:]=ids[i,-row['answer_length']:] labels=torch.tensor([r['label'] for r in rows]) if 'label' in rows[0] else targets return dict(input_ids=ids,attention_mask=mask,labels=labels) def legacy_rows(args,tokenizer): ds=load_from_disk(str(paths()['data']/args.task_name.lower()));rng=np.random.default_rng(args.seed) n=args.num_train+args.num_dev if n>len(ds['train']):raise ValueError('Train and development counts exceed available data') ids=rng.permutation(len(ds['train']))[:n];groups={} for split,source,indices in [('train','train',ids[:args.num_train]),('development','train',ids[args.num_train:]),('validation','validation',range(min(args.num_eval,len(ds['validation']))))]: rows=[] for i in indices: row=ds[source][int(i)] if args.task_name=='SST2': tokens=tokenizer.encode(f"{row['sentence'].strip()} It was",add_special_tokens=True,truncation=True,max_length=args.max_length) rows.append(dict(input_ids=tokens,label=int(row['label']),source_index=int(i),source_split=source)) else: answers=[str(v) for v in row['answers_spans']['spans']] answer=tokenizer.encode(' '+answers[0],add_special_tokens=False)[:min(32,args.max_length//4)] prompt=f"Passage: {row['passage']}\nQuestion: {row['question']}\nAnswer:" tokens=tokenizer.encode(prompt,add_special_tokens=True,truncation=True,max_length=args.max_length-len(answer)) if not tokens or not answer:raise ValueError('Empty DROP prompt or answer') rows.append(dict(input_ids=tokens+answer,prompt_ids=tokens,answer_length=len(answer),answers=answers,source_index=int(i),source_split=source)) groups[split]=rows return groups def convert_samples(task,samples,tokenizer,args): """MeZO Framework._convert for evaluation; unsupported modes are rejected by CLI.""" from .utils import encode_prompt data=[] for sample in samples: candidates,lengths=encode_prompt(task,task.get_template(),[],sample,tokenizer,max_length=args.max_length, generation=task.generation,generation_with_gold=True,max_new_tokens=args.max_new_tokens) correct=0 if task.generation else sample.candidates.index(sample.correct_candidate[0] if isinstance(sample.correct_candidate,list) else sample.correct_candidate) if args.train_as_classification: data.append([{'input_ids':candidates[i],'labels':correct,'option_len':lengths[i],'num_options':len(sample.candidates)} for i in range(len(candidates))]) else:data.append({'input_ids':candidates[correct],'labels':candidates[correct],'option_len':lengths[correct]}) return data