Julia-2 / runtime /julia2 /__init__.py
Julia Klee
Julia-2: julia2_audio_v1 (text = base_v2 byte-identical, + pruned audio tower, stem p9), int8/int4 variants, lean runtime 0.1.0 (audio, LiveSession, modalities), card with speech, live calls and variants
1d1c6db
Raw History Blame Contribute Delete
24.7 kB
"""Julia-2 runtime: a decision model (text, JSON, images, audio, live calls). Load once, decide many times.
from julia2 import Runtime
rt = Runtime("Julia-2") # local snapshot dir; GPU if available, else CPU
rt.predict_questions(state, {"move": {"type": "choice", "instructions": "...", "criteria": {...}}})
rt.predict_batch([{state, questions, images?, audio?}, ...])
rt.decide(state, instructions, criteria)
live = rt.open_live(context, questions, lang="en") # LiveSession: push audio/text, read the answer stream
live.push(pcm_float32_16k); live.turn("caller"); live.push_text("..."); answers, alert = live.ask()
State: str | JSON | System One parts (text / image_url / input_audio). Every question gives a probability for every
option; nothing is generated. The state is read once per request (shared state) and the questions run as short branches
of it; the live session appends audio tokens to the same cached state. Own small forwards for trunk, vision and audio
towers (no transformers at inference); fast kernels (fla / causal-conv1d, CUDA graphs) optional, pure-torch fallbacks.
"""
import json
import math
import time
from pathlib import Path
import numpy as np
import torch
from . import prompt as P
from .trunk import Trunk
from .vision import VisionTower, load_image, image_key, preprocess
from .audio import AudioStem, load_wav, AUDIO_START, AUDIO_END, SR
__all__ = ["Runtime", "LiveSession"]
__version__ = "0.1.0-draft"
class Tokenizer:
"""`tokenizers` fast tokenizer + the added special tokens of tokenizer_config.json (ids identical to the HF tokenizer)."""
def __init__(self, d):
from tokenizers import Tokenizer as T, AddedToken
self.t = T.from_file(str(d / "tokenizer.json"))
cfg = json.loads((d / "tokenizer_config.json").read_text())
have = set(json.loads((d / "tokenizer.json").read_text()).get("added_tokens", []) and [a["id"] for a in json.loads((d / "tokenizer.json").read_text())["added_tokens"]])
extra = [AddedToken(v["content"], special=True, normalized=False) for k, v in sorted(cfg.get("added_tokens_decoder", {}).items(), key=lambda kv: int(kv[0])) if int(k) not in have]
if extra:
self.t.add_special_tokens(extra)
self.pad_id = self.t.token_to_id(cfg.get("pad_token") or "<|endoftext|>") or 0
self._cache = {}
def encode(self, text):
ids = self._cache.get(text)
if ids is None:
ids = self.t.encode(text, add_special_tokens=False).ids
if len(self._cache) < 500_000:
self._cache[text] = ids
return ids
def token_id(self, s):
return self.t.token_to_id(s)
def _cpu_bf16_fast():
"""True when bf16 matmuls are at least as fast as fp32 on this CPU (AMX / AVX512-BF16); measured once at load."""
try:
import time
a = torch.randn(64, 1024); w = torch.randn(3584, 1024)
def t(x, ww):
torch.nn.functional.linear(x, ww)
t0 = time.perf_counter()
for _ in range(3):
torch.nn.functional.linear(x, ww)
return time.perf_counter() - t0
return t(a.bfloat16(), w.bfloat16()) <= t(a, w)
except Exception:
return False
class Runtime:
def __init__(self, path, device=None, precision="bf16", max_len=32768, token_budget=32768, threads=None, cpu_dtype=None,
modalities=("text", "image", "audio")):
"""precision: 'bf16' (repo root) | 'int8' | 'int4' (weight-only quantised variants in <path>/int8, <path>/int4).
modalities: which towers to load. ("text",) loads only the decision trunk (smallest memory, fastest load);
add "image" and/or "audio" to load the vision and audio towers. Inputs of a modality that was not loaded raise.
cpu_dtype: torch.bfloat16 (default when the CPU has fast bf16 matmuls: AVX512-BF16 / AMX) or torch.float32.
threads: CPU threads (default: physical cores, at most 8; oversubscription is very costly)."""
root = Path(path); self.root = root; self.precision = precision
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
self.cfg = json.loads((root / "config.json").read_text())
tcfg = json.loads((root / "trunk" / "config.json").read_text())
if self.device.type == "cpu":
n = threads or max(1, min(8, (__import__("os").cpu_count() or 2) // 2))
torch.set_num_threads(int(n))
if cpu_dtype is None:
cpu_dtype = torch.bfloat16 if _cpu_bf16_fast() else torch.float32
self.wdtype = torch.bfloat16 if self.device.type == "cuda" else cpu_dtype
self.tok = Tokenizer(root / "tokenizer")
self.max_len, self.budget = max_len, token_budget
# --- modules (only the tensors Julia-2 uses are loaded)
from safetensors import safe_open
wfile = root / self.cfg.get("weights_file", "model.safetensors") if precision == "bf16" else root / precision / "model.safetensors"
if not wfile.exists():
raise FileNotFoundError(f"no weights for precision {precision!r}: {wfile}")
f = safe_open(str(wfile), "pt")
keys = set(f.keys())
self._qstate = {k: f.get_tensor(k) for k in keys if k.endswith((".q", ".s"))} if precision != "bf16" else {}
self._qstate.update({k: bytes(f.get_tensor(k).tolist()).decode() for k in keys if k.endswith(".qcfg")})
tc = tcfg["text_config"]
self.trunk = Trunk(tc, self.cfg["readout"]["codes"], self.device, self.wdtype)
self._load(f, keys, "trunk.language_model.", self.trunk, exclude=("readout.",))
self.trunk.readout.weight.data = f.get_tensor("readout.weight").float().to(self.device); self.trunk.readout.bias.data = f.get_tensor("readout.bias").float().to(self.device)
self.trunk.to(self.device).eval()
for n, p in self.trunk.named_parameters(): # reference checkpoint runs all trunk weights in bf16 (readout fp32)
if not n.startswith("readout.") and p.dtype == torch.float32:
p.data = p.data.to(self.wdtype)
self.modalities = tuple(m.lower() for m in modalities)
unknown = set(self.modalities) - {"text", "image", "audio"}
if unknown:
raise ValueError(f"unknown modalities {sorted(unknown)} (use text, image, audio)")
self.vision = None
if "image" in self.modalities and any(k.startswith("trunk.visual.") for k in keys):
self.vision = VisionTower(tcfg["vision_config"], self.device, self.wdtype)
self._load(f, keys, "trunk.visual.", self.vision)
self.vision.to(self.device, self.wdtype).eval()
self.audio = None
acfg = self.cfg.get("audio")
if "audio" in self.modalities and acfg and any(k.startswith("audio.") for k in keys):
self.audio = AudioStem(acfg["encoder_config"], acfg.get("prune") or {}, self.device, self.wdtype)
self._load(f, keys, "audio.", self.audio)
self.audio.encoder.to(self.device, self.wdtype).eval(); self.audio.proj.to(self.device, torch.float32).eval()
if self._qstate:
from .quant import swap_linears
qs = {k: (v.to(self.device) if torch.is_tensor(v) else v) for k, v in self._qstate.items()}
swap_linears(self.trunk, qs, "trunk.language_model.")
if self.vision is not None:
swap_linears(self.vision, qs, "trunk.visual.")
if self.audio is not None:
swap_linears(self.audio, qs, "audio.")
self._qstate = None
self.emb = self.trunk.embed_tokens
self.max_pixels = int(self.cfg.get("max_image_pixels", 1_638_400))
self._img_cache, self._img_cache_max = {}, 64
def _load(self, f, keys, prefix, module, exclude=()):
sd = {}
for k in keys:
if k.startswith(prefix) and not any(k[len(prefix):].startswith(e) for e in exclude) and not k.endswith((".q", ".s", ".qcfg")):
sd[k[len(prefix):]] = f.get_tensor(k)
missing, unexpected = module.load_state_dict(sd, strict=False)
qw = {k[len(prefix):-2] + ".weight" for k in keys if k.startswith(prefix) and k.endswith(".q")}
missing = [m for m in missing if not m.startswith("readout.") and m not in qw]
if missing or unexpected:
raise RuntimeError(f"checkpoint mismatch under {prefix}: missing {missing[:5]} unexpected {unexpected[:5]}")
# ------------------------------------------------------------------ state parts
def split_state(self, state, images=(), audio=()):
"""System One state -> ordered parts [("text", str) | ("image", ref) | ("audio", ref)].
A plain string / JSON state is one text part; `images=` / `audio=` arguments are placed BEFORE the text."""
parts = [("image", x) for x in (images or [])] + [("audio", x) for x in (audio or [])]
if not isinstance(state, list):
return parts + [("text", state)]
for p in state:
t = p.get("type") if isinstance(p, dict) else None
if t in ("image_url", "image", "input_image"):
u = p.get("image_url", p.get("url", p.get("image"))); parts.append(("image", u.get("url") if isinstance(u, dict) else u))
elif t in ("input_audio", "audio", "audio_url"):
u = p.get("input_audio", p.get("audio", p.get("audio_url", p.get("url"))))
if isinstance(u, dict) and "data" in u:
parts.append(("audio", (np.asarray(u["data"], dtype=np.float32), u["sampling_rate"]) if "sampling_rate" in u else u["data"]))
else:
parts.append(("audio", u.get("url") if isinstance(u, dict) else u))
elif t in ("text", "input_text"):
parts.append(("text", str(p.get("text", ""))))
else:
parts.append(("text", p if isinstance(p, str) else json.dumps(p, ensure_ascii=False)))
return parts
@staticmethod
def _text_of(parts):
return "\n".join(x for k, x in parts if k == "text" and isinstance(x, str)) if any(k == "text" for k, _ in parts) else ""
# ------------------------------------------------------------------ embeddings of non-text parts
def _image_tokens(self, ref):
img = load_image(ref); key = image_key(img) + f":{self.max_pixels}"
hit = self._img_cache.get(key)
if hit is None:
patches, grid = preprocess(img, self.max_pixels)
hit = (self.vision.encode(patches, grid), grid)
if len(self._img_cache) >= self._img_cache_max:
self._img_cache.pop(next(iter(self._img_cache)))
self._img_cache[key] = hit
return hit
def _ids_emb(self, text):
ids = torch.tensor(self.tok.encode(text), dtype=torch.long, device=self.device)
return self.emb(ids)
def _state_embeds(self, parts):
"""Ordered parts -> (embeds [T,H], pos3 [3,T] or None). Text parts are joined as they come; images and audio
are wrapped in their marker tokens; a text part following a non-text part starts on a new line."""
embs, pos, cur = [], [], 0
has_img = any(k == "image" for k, _ in parts)
def add_emb(e, p3=None):
nonlocal cur
embs.append(e)
if has_img:
pos.append(torch.arange(e.shape[0])[None].expand(3, -1) + cur if p3 is None else p3)
cur = cur + e.shape[0] if p3 is None else int(p3.max().item()) + 1
def add_text(t):
if t:
add_emb(self._ids_emb(t))
add_text("### State\n")
prev = None
for kind, x in parts:
if kind == "text":
st = x if isinstance(x, str) else json.dumps(x, ensure_ascii=False)
if st == "{}" or st is None:
st = ""
if prev not in (None, "text") and st and not st.startswith("\n"):
st = "\n" + st
add_text(st)
elif kind == "image":
if self.vision is None:
raise RuntimeError("image input, but the vision tower is not loaded (checkpoint without it, or Runtime(modalities=...) without \"image\")")
toks, grid = self._image_tokens(x)
add_text(P.VISION_START)
p3, _ = VisionTower.llm_positions(cur, grid, self.vision.merge)
add_emb(toks.to(self.wdtype), p3)
add_text(P.VISION_END)
else:
if self.audio is None:
raise RuntimeError("audio input, but the audio tower is not loaded (checkpoint without it, or Runtime(modalities=...) without \"audio\")")
wav = x if isinstance(x, np.ndarray) else load_wav(x)
add_text(AUDIO_START)
add_emb(self.audio([wav])[0].to(self.wdtype))
add_text(AUDIO_END)
prev = kind
return torch.cat(embs, 0), (torch.cat(pos, 1) if has_img else None)
# ------------------------------------------------------------------ inference
@staticmethod
def _tail(qtype, question, options):
text = P.render("", qtype, question, options)
return text[text.index("\n\n### Question ("):]
def _probs_text(self, rows):
"""Plain text rows -> probabilities; length-bucketed batches, no shared state (each row is one sequence)."""
enc = [self.tok.encode(P.render(r["state"], r["type"], r["question"], r["options"])) for r in rows]
trunc = []
for i, ids in enumerate(enc):
if len(ids) > self.max_len:
enc[i] = ids[:64] + ids[-(self.max_len - 64):]; trunc.append(i)
order = sorted(range(len(rows)), key=lambda i: len(enc[i])); out = [None] * len(rows); i = 0
while i < len(order):
batch, mx = [], 0
while i < len(order) and (not batch or max(mx, len(enc[order[i]])) * (len(batch) + 1) <= self.budget):
batch.append(order[i]); mx = max(mx, len(enc[order[i]])); i += 1
lg = self.trunk.ask(self.trunk._empty(1), [enc[j] for j in batch], pad_to=32 if mx <= 1024 else 128)
for b, j in enumerate(batch):
out[j] = torch.softmax(lg[b, : len(rows[j]["options"])], -1).tolist()
return out, trunc
def _probs_shared(self, parts, qrows):
"""One multimodal / shared state, Q questions: read the state once, fork into Q branches."""
emb, pos3 = self._state_embeds(parts)
T = emb.shape[0]
if T + 512 > self.max_len:
raise ValueError(f"state too long: {T} tokens")
st = self.trunk.new_state(max_len=int(math.ceil((T + 512) / 512) * 512))
self.trunk.append(st, emb, pos3)
sufs = [self.tok.encode(self._tail(q["type"], q["question"], q["options"])) for q in qrows]
lg = self.trunk.ask(st, sufs)
return [torch.softmax(lg[j, : len(q["options"])], -1).tolist() for j, q in enumerate(qrows)]
@staticmethod
def _answer(qtype, keys, probs):
if qtype == "noul":
p = dict(zip(keys, probs)); pt = p["true"] / max(p["true"] + p["false"], 1e-9)
return {"type": "noul", "noul": pt, "confidence": abs(2 * pt - 1)}
s = sorted(probs, reverse=True); best = keys[max(range(len(probs)), key=probs.__getitem__)]
a = {"type": qtype, "probabilities": dict(zip(keys, probs)), "confidence": s[0] - (s[1] if len(s) > 1 else 0)}
if qtype == "choice":
a["choice"] = best
else:
a["score"] = int(best); a["expected_level"] = sum(int(k) * p for k, p in zip(keys, probs))
return a
@torch.inference_mode()
def predict_batch(self, requests, shared="auto"):
"""requests: [{state, questions, images?, audio?}]. Text-only requests with one question are batched by length;
multimodal states and multi-question requests use the shared state (read once, Q branches)."""
rows, meta = [], []
text_rows, text_meta = [], []
res = [{"model": self.cfg.get("name", "julia-2"), "answers": {}} for _ in requests]
for ri, req in enumerate(requests):
parts = self.split_state(req["state"], req.get("images"), req.get("audio"))
multimodal = any(k != "text" for k, _ in parts)
qrows = []
for qk, q in req["questions"].items():
opts = P.options_for(q)
qrows.append({"key": qk, "type": q["type"], "question": q.get("instructions", ""), "options": opts})
use_shared = multimodal or (shared is True) or (shared == "auto" and len(qrows) > 1 and self.device.type == "cuda")
if use_shared:
probs = self._probs_shared(parts, qrows)
for q, p in zip(qrows, probs):
res[ri]["answers"][q["key"]] = self._answer(q["type"], [k for k, _ in q["options"]], p)
else:
st = parts[0][1] if len(parts) == 1 else self._text_of(parts)
for q in qrows:
text_rows.append({"state": st, "type": q["type"], "question": q["question"], "options": q["options"]}); text_meta.append((ri, q))
if text_rows:
probs, trunc = self._probs_text(text_rows)
for i, ((ri, q), p) in enumerate(zip(text_meta, probs)):
a = self._answer(q["type"], [k for k, _ in q["options"]], p)
if i in trunc:
a["truncated"] = True
res[ri]["answers"][q["key"]] = a
return res
def predict_questions(self, state, questions, images=None, audio=None, shared="auto"):
return self.predict_batch([{"state": state, "questions": questions, "images": images or [], "audio": audio or []}], shared=shared)[0]
def decide(self, state, instructions, criteria, **kw):
return self.predict_questions(state, {"q": {"type": "choice", "instructions": instructions, "criteria": criteria}}, **kw)["answers"]["q"]
def open_live(self, context, questions, lang="en", **kw):
return LiveSession(self, context, questions, lang=lang, **kw)
class LiveSession:
"""A live call: fixed context + fixed questions; audio (or text) is appended to the cached state as it arrives and the
questions are re-asked as short forks of that state. Audio is encoded in hops (hop_s of new audio with ctx_s of left
context, 2 frames of look-ahead held back) which reproduces a full re-encode; alert = hysteresis on the P(alert) stream.
s = rt.open_live({"customer": ...}, questions, lang="en")
s.turn("caller"); s.push(pcm); answers, alert = s.ask()
questions: System One dict {key: {type, instructions, criteria}}; the hysteresis watches `alert_key` (a noul question).
"""
def __init__(self, rt, context, questions, lang="en", hop_s=0.96, ctx_s=3.0, max_len=8192, alert_key="alert", on_th=0.6, off_th=0.4, k_on=2, k_off=3, compile=True):
self.rt, self.lang = rt, lang
self.qs = [{"key": k, "type": q["type"], "question": q.get("instructions", ""), "options": P.options_for(q)} for k, q in questions.items()]
self.sufs = {pre: [rt.tok.encode(pre + Runtime._tail(q["type"], q["question"], q["options"])) for q in self.qs] for pre in ("", AUDIO_END)}
self.st = rt.trunk.new_state(max_len)
self.hop, self.ctx, self.la = int(hop_s * SR) // 640 * 640, int(ctx_s * SR) // 640 * 640, 2
self.buf = np.zeros(0, dtype=np.float32); self.hist = np.zeros(0, dtype=np.float32)
self.open_audio, self.n_tok = False, 0
self.alert_key, self.on_th, self.off_th, self.k_on, self.k_off = alert_key, on_th, off_th, k_on, k_off
self.alert, self._on, self._off, self.log = False, 0, 0, []
ctx_text = context if isinstance(context, str) else json.dumps(context, ensure_ascii=False)
self._append_text("### State\n" + ctx_text + ("\nCall transcript:" if lang == "en" else "\nTranscrição da ligação:"))
if compile and rt.audio is not None and rt.device.type == "cuda":
self.compile()
def compile(self):
"""Graph the encoder for the hop feature shapes (block only at a turn start; ctx + block afterwards)."""
shapes = set(); hist = 0
for _ in range(4):
ctx = min(hist, self.ctx); n = (ctx + self.hop) // 160 - 1
shapes.add(int(n)); hist += self.hop
shapes.add(int(self.ctx // 160 + self.hop // 160 - 1))
self.rt.audio.compile_hop(sorted(shapes))
# ----------------------------------------------------- appends
def _append(self, e):
self.rt.trunk.append(self.st, e); self.n_tok += e.shape[0]
def _append_text(self, text):
with torch.inference_mode():
self._append(self.rt._ids_emb(text))
def _close_audio(self):
if self.open_audio:
self._flush(final=True); self._append_text(AUDIO_END); self.open_audio = False
def turn(self, speaker):
"""New speaker turn. speaker: 'caller' | 'customer' (or any label)."""
self._close_audio()
name = {"en": {"caller": "Caller", "customer": "Customer"}, "pt": {"caller": "Interlocutor", "customer": "Cliente"}}.get(self.lang, {}).get(speaker, speaker.capitalize())
self._append_text(f"\n{name}: " + AUDIO_START); self.open_audio = True; self.hist = np.zeros(0, dtype=np.float32)
def push_text(self, text, speaker=None):
"""Append a text chunk (e.g. a transcript turn) instead of audio."""
self._close_audio()
if speaker:
name = {"en": {"caller": "Caller", "customer": "Customer"}, "pt": {"caller": "Interlocutor", "customer": "Cliente"}}.get(self.lang, {}).get(speaker, speaker.capitalize())
text = f"\n{name}: {text}"
self._append_text(text)
def push(self, pcm, sr=SR):
"""Append audio samples (float32 mono). Returns the number of state tokens added."""
if self.rt.audio is None:
raise RuntimeError("no audio stem in this checkpoint")
if sr != SR:
pcm = load_wav(np.asarray(pcm, dtype=np.float32), sr)
if not self.open_audio:
self._append_text(AUDIO_START); self.open_audio = True
self.buf = np.concatenate([self.buf, np.asarray(pcm, dtype=np.float32)]); n = 0
while len(self.buf) >= self.hop:
n += self._flush(final=False)
return n
@torch.inference_mode()
def _flush(self, final):
take = len(self.buf) if final else self.hop
if take < 1600:
if final:
self.buf = self.buf[take:]
return 0
block = self.buf[:take]
ctx = self.hist[-self.ctx:]; ctx = ctx[len(ctx) % 640:]; n_ctx = len(ctx) // 640
wav = np.concatenate([ctx, block])
h, m = self.rt.audio.encode([wav])
n_emit = int(m[0].sum()) - n_ctx - (0 if final else self.la)
if not final:
n_emit -= n_emit % 2
if n_emit <= 0:
return 0
y, ym = self.rt.audio.proj(h[:, n_ctx:n_ctx + n_emit], m[:, n_ctx:n_ctx + n_emit])
e = y[0, ym[0]]
used = n_emit * 640 if not final else take
self.hist = np.concatenate([self.hist, block[:used]])[-self.ctx * 4:]; self.buf = self.buf[used:]
self._append(e.to(self.rt.wdtype))
return e.shape[0]
# ----------------------------------------------------- answers
@torch.inference_mode()
def ask(self):
"""-> (answers {key: System One answer}, alert bool). Forks the cached state into one branch per question."""
pre = AUDIO_END if self.open_audio else ""
lg = self.rt.trunk.ask(self.st, self.sufs[pre])
answers = {}
for j, q in enumerate(self.qs):
p = torch.softmax(lg[j, : len(q["options"])], -1).tolist()
answers[q["key"]] = Runtime._answer(q["type"], [k for k, _ in q["options"]], p)
a = answers.get(self.alert_key)
pa = a["noul"] if a and a["type"] == "noul" else 0.0
if pa >= self.on_th:
self._on += 1; self._off = 0
elif pa <= self.off_th:
self._off += 1; self._on = 0
else:
self._on = self._off = 0
if not self.alert and self._on >= self.k_on:
self.alert = True
if self.alert and self._off >= self.k_off:
self.alert = False
self.log.append({"t": time.time(), "n_tok": self.n_tok, "alert": self.alert, "p_alert": pa})
return answers, self.alert
def close(self):
self._close_audio()