Text Generation
PyTorch
English
experimental
custom-architecture
BoggersLM-Alpha / utf8_constraint.py
BoggersTheFish's picture
Initial private BoggersLM-Alpha research release
480f8c6 verified
Raw History Blame Contribute Delete
1.29 kB
"""Strict UTF-8 decoding constraints for native token generation."""
import codecs,functools
class UTF8Constraint:
def __init__(self,raw,bos=256,eos=257,pad=258):
self.raw=raw;self.bos=bos;self.eos=eos;self.pad=pad
self.allowed=functools.lru_cache(maxsize=256)(self._allowed)
def advance(self,pending,token):
dec=codecs.getincrementaldecoder('utf-8')('strict')
dec.setstate((pending,0))
try:
dec.decode(token,final=False)
q=dec.getstate()[0]
if len(q)>=2:
lead,second=q[:2]
if (lead==0xe0 and second<0xa0) or (lead==0xed and second>=0xa0) or (lead==0xf0 and second<0x90) or (lead==0xf4 and second>0x8f):return None
return q
except UnicodeDecodeError:return None
def _allowed(self,pending,remaining=3):
a=[]
for i,b in enumerate(self.raw):
if i in (self.bos,self.pad):continue
if i==self.eos:
if not pending:a.append(i)
continue
if not b:continue
q=self.advance(pending,b)
if q is None:continue
need=(2 if q[0]<0xe0 else 3 if q[0]<0xf0 else 4)-len(q) if q else 0
if need<=remaining:a.append(i)
return tuple(a)