Quasar / quasar /inference /extended.py
Atlas Ai
Upload evaluated Quasar weights with portable inference and pinned codecs
d2a1a41 verified
Raw History Blame Contribute Delete
8.32 kB
"""Audio, geometry and schema-checked calls from the same shared generator.
Recorded training exposure is required. Structural masks constrain packets;
semantic usefulness must be established separately on trained checkpoints.
"""
from pathlib import Path
import json
import numpy as np
import torch
from .universal import UniversalGenerator
from .decoding import Sampling, sample_next
from ..data.curated import validate_calls
from ..data.text_preparation import sha256_file
from ..tokenizers.universal import TokenGrammar
from ..tokenizers.audio_aligned import AlignedAudioTokenizer
class ExtendedGenerator(UniversalGenerator):
def require_task(self, task):
if not self.meta.get('task_target_tokens', {}).get(task):
raise RuntimeError('This checkpoint has no recorded training exposure for ' + task)
def audio(self):
if not hasattr(self, '_audio'):
identity = self.meta.get('data', {}).get('preparation', {}).get('audio_codec')
if not identity or identity.get('implementation') != 'quasar.tokenizers.audio_aligned.AlignedAudioTokenizer':
raise RuntimeError('Checkpoint has no compatible frozen audio codec identity')
path = Path(identity['path'])
if not path.is_absolute():
path = (self.path / path).resolve()
for name in ('config.json', 'model.safetensors'):
if sha256_file(path / name) != identity['sha256'][name]:
raise ValueError('Audio codec differs from training')
self._audio = AlignedAudioTokenizer(path, identity['alignment_samples'], identity['codebooks'], device=self.device)
return self._audio
def _candidates(self, grammar, kind, remaining):
v, s, state = self.vocab, self.vocab.special, grammar.state
if state == 'audio':
book = grammar.count % v.audio_books
lo = v.ranges['audio'][0] + book * v.audio_size
# Keep two boundary guards within the two-second source budget.
if grammar.count >= 152 * v.audio_books or (book == 0 and grammar.count >= 64 and remaining <= 5):
return [s('/audio')]
tokens = list(range(lo, lo + v.audio_size))
if grammar.count >= 64 and book == 0:
tokens.append(s('/audio'))
return tokens
if state == 'mesh':
return [s('vertices')]
if state == 'vertices':
if grammar.count >= 9 and grammar.count % 3 == 0 and remaining <= 8:
return [s('faces')]
return list(range(*v.ranges['coordinate'])) + [s('faces')]
if state == 'faces':
if grammar.count >= 3 and grammar.count % 3 == 0 and remaining <= 5:
return [s('/mesh')]
lo = v.ranges['index'][0]
return list(range(lo, lo + grammar.vertices)) + [s('/mesh')]
if state == 'calls':
return [s('/calls')] if remaining <= 2 else list(range(v.text_size)) + [s('/calls')]
if state == 'packets':
return [s('eos')]
raise ValueError('Unsupported generated packet state: ' + state)
@torch.inference_mode()
def packet(self, task, inputs, kind, sp):
self.require_task(task)
v, s = self.vocab, self.vocab.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)]
budget = min(sp.max_new_tokens, self.model.cfg.max_seq_len - len(prefix))
minimum = {'audio': 66, 'mesh': 16, 'calls': 3}[kind]
if budget < minimum:
raise ValueError('Complete packet and conditioning exceed the requested context/output budget')
grammar = TokenGrammar(v)
for token in prefix:
grammar.advance(token)
device = next(self.model.parameters()).device
amp = device.type == 'cuda'
cache = self.model.new_cache(1, dtype=torch.bfloat16 if amp else torch.float32)
rng = torch.Generator(device=device).manual_seed(sp.seed)
emitted = []
with torch.autocast(device.type, dtype=torch.bfloat16, enabled=amp):
logits = self.model(torch.tensor([prefix], device=device), cache=cache)[:, -1]
while grammar.state != 'done' and len(emitted) < budget:
candidates = [t for t in self._candidates(grammar, kind, budget - len(emitted)) if grammar.accepts(t)]
if not candidates:
raise RuntimeError('No structurally valid completion fits the packet budget')
if len(candidates) == 1:
token = candidates[0]
else:
legal = torch.zeros((1, v.size), dtype=torch.bool, device=device)
legal[:, candidates] = True
history = torch.tensor([emitted], dtype=torch.long, device=device)
token = int(sample_next(logits, legal, sp, rng, history, v.text_size)[0])
grammar.advance(token); emitted.append(token)
if grammar.state != 'done':
logits = self.model(torch.tensor([[token]], device=device), cache=cache, start=cache.next_pos)[:, -1]
if grammar.state != 'done':
raise RuntimeError('Model did not finish a valid packet within the output budget')
v.validate(prefix + emitted)
return emitted
def generate_audio(self, prompt, sp=None):
tokens = self.packet('t2a', [{'type': 'text', 'text': prompt}], 'audio',
sp or Sampling(temperature=.8, top_k=64, top_p=.9, max_new_tokens=642))
raw = np.asarray(tokens[:-2], dtype=np.int64).reshape(-1, self.vocab.audio_books)
offsets = self.vocab.ranges['audio'][0] + np.arange(self.vocab.audio_books) * self.vocab.audio_size
packet = {'type': 'audio', 'codes': (raw - offsets).tolist()}
codec = self.audio()
return codec.decode(packet), codec.sr
def describe_audio(self, waveform, sample_rate, sp=None):
self.require_task('a2t')
packet = self.audio().encode(waveform, sample_rate)
return self._predict('a2t', [packet], 'text', sp or Sampling(temperature=.5, max_new_tokens=128))[0]
def generate_mesh(self, prompt, sp=None):
t = self.packet('t2m', [{'type': 'text', 'text': prompt}], 'mesh',
sp or Sampling(temperature=.8, top_k=64, top_p=.9, max_new_tokens=780))
s = self.vocab.special
vertices = np.asarray(t[t.index(s('vertices')) + 1:t.index(s('faces'))]).reshape(-1, 3)
faces = np.asarray(t[t.index(s('faces')) + 1:t.index(s('/mesh'))]).reshape(-1, 3)
vertices -= self.vocab.ranges['coordinate'][0]; faces -= self.vocab.ranges['index'][0]
if len(np.unique(vertices, axis=0)) != len(vertices) or np.any(np.linalg.norm(
np.cross(vertices[faces[:, 1]] - vertices[faces[:, 0]], vertices[faces[:, 2]] - vertices[faces[:, 0]]), axis=1) == 0):
raise RuntimeError('Generated mesh has collapsed or degenerate geometry; semantic generation is unverified')
return {'type': 'mesh', 'vertices': vertices.tolist(), 'faces': faces.tolist()}
def describe_mesh(self, packet, sp=None):
return self._predict('m2t', [packet], 'text', sp or Sampling(temperature=.5, max_new_tokens=128))[0]
def propose_calls(self, prompt, tools, sp=None):
self.require_task('tools')
validate_calls(tools, [])
tokens = self.packet('tools', [{'type': 'tools', 'value': tools}, {'type': 'text', 'text': 'user: ' + prompt}],
'calls', sp or Sampling(temperature=.5, max_new_tokens=256))
text = self.tok.decode([t for t in tokens if t < self.vocab.text_size])
def reject_constant(value):
raise ValueError('Non-finite JSON constant: ' + value)
result = json.loads(text, parse_constant=reject_constant)
if not isinstance(result, list):
raise ValueError('Generated calls must be a JSON list')
validate_calls(tools, result)
return result