Files
ModelHub XC c1ce9811bb 初始化项目,由ModelHub XC社区提供模型
Model: Xirui1208/selective-readtwice-7b-early-evaluated-20260928
Source: Original Platform
2026-11-17 05:18:17 +08:00

23 lines
1.6 KiB
Python

"""Lossless source slicing with real tokenizer budgets and Unicode boundaries."""
def split_context(tok,text,chunk_tokens=5000):
if not isinstance(text,str) or not text: raise ValueError('Context must be nonempty text')
enc=tok(text,add_special_tokens=False,return_offsets_mapping=True)
ids=enc['input_ids']; offsets=enc['offset_mapping']; token_bounds=[0]; char_bounds=[0]; chunks=[]; lengths=[]
while token_bounds[-1]<len(ids):
end=min(token_bounds[-1]+chunk_tokens,len(ids))
while True:
while end<len(ids) and offsets[end-1][1]>offsets[end][0]: end-=1
if end<=token_bounds[-1]: raise ValueError('Cannot create a Unicode-safe chunk within the token budget')
char_end=offsets[end][0] if end<len(ids) else len(text)
# Tokenizer normalization (e.g. reordered Burmese combining marks)
# makes decode(encode(source)) non-lossless. Slice SOURCE characters.
chunk=text[char_bounds[-1]:char_end]
actual_length=len(tok.encode(chunk,add_special_tokens=False))
if actual_length<=chunk_tokens: break
end-=1
chunks.append(chunk); lengths.append(actual_length)
token_bounds.append(end); char_bounds.append(char_end)
if ''.join(chunks)!=text: raise AssertionError('Source text changed during chunking')
if any(not c for c in chunks): raise AssertionError('Empty chunk')
return {'chunks':chunks,'chunk_lengths':lengths,'chunk_token_boundaries':token_bounds,'chunk_char_boundaries':char_bounds,'num_tokens':sum(lengths),'num_chunks':len(chunks)}