File size: 6,151 Bytes
d2a1a41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""Generation for the actual v2 packet grammar and a shared Axiom checkpoint."""
from __future__ import annotations
from pathlib import Path
import numpy as np
import torch
from ..tokenizers.text import TextTokenizer
from ..tokenizers.vision import VisualTokenizer
from ..training.checkpoint import load_quasar
from .decoding import Sampling,sample_next


class UniversalGenerator:
    def __init__(self,checkpoint: str|Path,device: str='cuda'):
        self.path=Path(checkpoint)
        self.model,self.vocab,self.meta=load_quasar(self.path,device)
        self.model.eval()
        if not hasattr(self.vocab,'special'):raise ValueError('UniversalGenerator requires a packet-v2 checkpoint')
        self.tok=TextTokenizer.load(self.path/'tokenizers/text_tokenizer.json')
        self.codec=None;self.device=device

    def vision(self):
        if self.codec is None:self.codec=VisualTokenizer.load(self.path/'tokenizers/vq',self.device)
        return self.codec

    @torch.inference_mode()
    def _predict(self,task,inputs,kind,sp: Sampling,frames=8,resolution=64):
        if not self.meta.get('task_target_tokens',{}).get(task):
            raise RuntimeError(f'This checkpoint has no recorded training exposure for {task}')
        v=self.vocab;s=v.special
        prefix=[s('bos'),s('task:'+task),s('input')]
        for segment in inputs:prefix+=v.packet(segment,self.tok.encode)
        prefix+=[s('output'),s(kind)]
        # This is structural forcing only. All content codes/tokens are predicted by Quasar.
        if kind=='image':
            if resolution not in (64,128) or (resolution==128 and v.schema_version!=3):
                raise ValueError('128px image generation requires a schema-v3 checkpoint')
            if resolution==128:prefix += [s('resolution:128')]
            plan=[('vision',(resolution//8)**2),('/image',1),('eos',1)]
        elif kind=='video':
            if not 1<=frames<=v.max_frames:raise ValueError('frame count exceeds vocabulary')
            plan=[]
            for i in range(frames):plan += [('frame',1),('time:'+str(i),1),('vision',64),('/frame',1)]
            plan += [('/video',1),('eos',1)]
        else:plan=[('free_text',sp.max_new_tokens)]
        needed=sum(n for _,n in plan)
        if len(prefix)+needed>self.model.cfg.max_seq_len:raise ValueError('requested input/output exceeds trained context')
        device=next(self.model.parameters()).device;use_amp=device.type=='cuda'
        cache=self.model.new_cache(1,dtype=torch.bfloat16 if use_amp else torch.float32)
        gen=torch.Generator(device=device).manual_seed(sp.seed)
        emitted=[];content=[];stop=False
        with torch.autocast(device.type,dtype=torch.bfloat16,enabled=use_amp):
            logits=self.model(torch.tensor([prefix],device=device),cache=cache)[:,-1]
            for state,n in plan:
                for _ in range(n):
                    if state in ('vision','free_text'):
                        legal=torch.zeros((1,v.size),dtype=torch.bool,device=device)
                        lo,hi=v.ranges['vision' if state=='vision' else 'text'];legal[:,lo:hi]=True
                        if state=='free_text':legal[:,s('/text')]=True
                        history=torch.tensor([content],dtype=torch.long,device=device)
                        token=int(sample_next(logits,legal,sp,gen,history,v.text_size)[0])
                        if state=='free_text' and token==s('/text'):
                            emitted += [token,s('eos')];stop=True;break
                        content.append(token)
                    else:token=s(state)
                    emitted.append(token)
                    # A one-token cache append cannot infer its location in the
                    # current visual run. Preserve the full-prefix spatial slot,
                    # resetting at image/frame boundaries exactly as training does.
                    history_tokens=torch.tensor([prefix+emitted],device=device)
                    position=self.model.visual_positions(history_tokens)[:,-1:]
                    logits=self.model(history_tokens[:,-1:],vis_pos=position,
                                      cache=cache,start=cache.next_pos)[:,-1]
                if stop:break
        if kind=='text':return self.tok.decode(content),{'learned_text_stop':stop,'token_limit':sp.max_new_tokens}
        v.validate(prefix+emitted)
        codes=np.asarray(content,dtype=np.int64)-v.visual_offset
        return codes.reshape((resolution//8,resolution//8) if kind=='image' else (frames,8,8)),{'structurally_valid':True}

    def generate_text(self,prompt,sp=None):
        return self._predict('chat_text',[{'type':'text','text':prompt}],'text',sp or Sampling(temperature=.5,top_p=.9))[0]

    def generate_image(self,prompt,sp=None,resolution=64):
        if resolution==128 and not self.meta.get('image_128_trained',False):
            raise RuntimeError('128px image generation has no verified training exposure in this checkpoint')
        codes,_=self._predict('t2i',[{'type':'text','text':prompt}],'image',sp or Sampling(),resolution=resolution)
        return self.vision().decode(codes[None])[0]

    def generate_video(self,prompt,frames=8,sp=None):
        codes,_=self._predict('t2v',[{'type':'text','text':prompt}],'video',sp or Sampling(),frames)
        return self.vision().decode(codes)

    def describe_image(self,pixels,sp=None):
        codes=self.vision().encode(np.asarray(pixels)[None])[0]
        return self._predict('i2t',[{'type':'image','codes':codes}],'text',sp or Sampling(temperature=.5))[0]

    def describe_video(self,frames,sp=None):
        codes=self.vision().encode(np.asarray(frames))
        return self._predict('v2t',[{'type':'video','codes':codes}],'text',sp or Sampling(temperature=.5))[0]

    def continue_video(self,frames,new_frames=4,sp=None):
        codes=self.vision().encode(np.asarray(frames))
        generated,_=self._predict('vcont',[{'type':'video','codes':codes}],'video',sp or Sampling(),new_frames)
        return self.vision().decode(generated)