basal-engine 3.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/media.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Images and audio in a request (basal-omni on Gemma 4; `basal-serve --mode eager --media on`).
|
|
2
|
+
|
|
3
|
+
A request carries its media with the state:
|
|
4
|
+
|
|
5
|
+
"media": [{"type": "image" | "audio", "data": "<base64>"}, ...], "detail": "default" | "high" (optional)
|
|
6
|
+
|
|
7
|
+
The items go where the state text goes, before it, in the order given: the prompt the basal-omni evaluation reads them
|
|
8
|
+
with. Images: any single-frame format Pillow opens (an animated or multi-page file is refused; an MPO phone photo is
|
|
9
|
+
read as its photo), turned as its EXIF orientation says, shrunk to at most MAX_SIDE px a side, a transparent one
|
|
10
|
+
composited onto white, then converted to RGB; "detail" sets the image's soft tokens (default 280, high 1,120).
|
|
11
|
+
Audio: WAV, FLAC, OGG or MP3 (libsndfile), mixed to mono and resampled to 16 kHz; at most the model's audio window
|
|
12
|
+
(Gemma 4: 750 tokens x 40 ms = 30 s). One request holds at most MAX_ITEMS items of at most MAX_BYTES each; an image
|
|
13
|
+
may have at most MAX_PIXELS pixels (decompression bombs are refused before decoding); a clip is read up to the window
|
|
14
|
+
(one frame more shows it is longer), and a clip of a model without a known window up to MAX_AUDIO_SAMPLES samples, so
|
|
15
|
+
a long clip that compresses well is refused without decoding it whole. Errors are ValueError (HTTP 422).
|
|
16
|
+
"""
|
|
17
|
+
import base64
|
|
18
|
+
import binascii
|
|
19
|
+
import io
|
|
20
|
+
from math import gcd
|
|
21
|
+
|
|
22
|
+
MAX_ITEMS = 8
|
|
23
|
+
MAX_BYTES = 20 * 1024 * 1024
|
|
24
|
+
MAX_PIXELS = 50_000_000
|
|
25
|
+
MAX_SIDE = 4096 # a decoded image is kept at most this long a side (the model's soft tokens need far less)
|
|
26
|
+
MAX_AUDIO_SAMPLES = 1 << 26 # decoded samples of one clip, every channel (256 MB of float32; 30 s at 192 kHz x 8 is 46 M)
|
|
27
|
+
SAMPLE_RATE = 16000
|
|
28
|
+
DETAIL = {"default": 280, "high": 1120}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def kinds_of(config):
|
|
32
|
+
"""Media a model's config.json can take: ("image", "audio") for an image and an audio encoder."""
|
|
33
|
+
return tuple(k for k, key in (("image", "vision_config"), ("audio", "audio_config")) if config.get(key))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def audio_window(processor_config):
|
|
37
|
+
"""Longest audio clip in seconds (Gemma 4: audio_seq_length tokens of audio_ms_per_token ms), None if unknown."""
|
|
38
|
+
n, ms = processor_config.get("audio_seq_length"), processor_config.get("audio_ms_per_token")
|
|
39
|
+
return n * ms / 1000 if n and ms else None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def detail_tokens(detail):
|
|
43
|
+
if detail not in DETAIL:
|
|
44
|
+
raise ValueError(f'detail must be one of {sorted(DETAIL)}, got {detail!r}')
|
|
45
|
+
return DETAIL[detail]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _raw(data, n):
|
|
49
|
+
if not isinstance(data, str) or not data:
|
|
50
|
+
raise ValueError(f"media {n}: data must be a base64 string")
|
|
51
|
+
if data[:5].lower() == "data:" and "," in data: # a data URL: data:<type>;base64,<payload> (any case)
|
|
52
|
+
data = data.split(",", 1)[1]
|
|
53
|
+
data = "".join(data.split()) # MIME-wrapped base64 (every 76 characters), as base64 tools write it
|
|
54
|
+
if "=" not in data and len(data) % 4 in (2, 3): # URL-safe base64 is often sent without its padding
|
|
55
|
+
data += "=" * (4 - len(data) % 4)
|
|
56
|
+
if len(data) * 3 // 4 > MAX_BYTES:
|
|
57
|
+
raise ValueError(f"media {n}: more than {MAX_BYTES // (1024 * 1024)} MB")
|
|
58
|
+
try: # (the URL-safe alphabet too: standard base64 has no "-" or "_")
|
|
59
|
+
return base64.b64decode(data.replace("-", "+").replace("_", "/"), validate=True)
|
|
60
|
+
except (binascii.Error, ValueError):
|
|
61
|
+
raise ValueError(f"media {n}: data is not valid base64") from None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
ANIMATED = {"GIF", "PNG", "WEBP", "TIFF"} # formats whose second frame means an animation or several pages
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _image(raw, n):
|
|
68
|
+
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
69
|
+
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
|
70
|
+
try:
|
|
71
|
+
im = Image.open(io.BytesIO(raw))
|
|
72
|
+
w, h = im.size
|
|
73
|
+
if w * h > MAX_PIXELS:
|
|
74
|
+
raise ValueError(f"media {n}: {w}x{h} pixels, more than {MAX_PIXELS:,}")
|
|
75
|
+
if im.format in ANIMATED and getattr(im, "is_animated", False): # not MPO: a phone photo (Ultra HDR, depth)
|
|
76
|
+
# (is_animated looks for a second frame; n_frames would walk every frame of a GIF)
|
|
77
|
+
raise ValueError(f"media {n}: an animated or multi-page {im.format} image; send a single frame")
|
|
78
|
+
alpha = im.mode in ("RGBA", "LA", "PA") or "transparency" in im.info
|
|
79
|
+
if alpha or im.mode == "P": # a palette image is resized by nearest neighbour; do it in colour
|
|
80
|
+
to = "RGBA" if alpha else "RGB"
|
|
81
|
+
im = im if im.mode == to else im.convert(to) # (convert copies, even to the same mode)
|
|
82
|
+
im.thumbnail((MAX_SIDE, MAX_SIDE)) # first, while the image is large: 8 x 50 MP held 1.1 GB RGB per request
|
|
83
|
+
im = ImageOps.exif_transpose(im) # a phone photo is stored sideways with an Orientation tag
|
|
84
|
+
if alpha: # onto white, not onto black
|
|
85
|
+
im = Image.alpha_composite(Image.new("RGBA", im.size, (255, 255, 255, 255)), im.convert("RGBA"))
|
|
86
|
+
return im.convert("RGB")
|
|
87
|
+
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, SyntaxError) as e:
|
|
88
|
+
raise ValueError(f"media {n}: not a readable image ({type(e).__name__})") from None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _audio(raw, n, max_seconds):
|
|
92
|
+
import numpy as np
|
|
93
|
+
import soundfile as sf
|
|
94
|
+
try:
|
|
95
|
+
with sf.SoundFile(io.BytesIO(raw)) as f:
|
|
96
|
+
sr, channels, frames = f.samplerate, f.channels, f.frames
|
|
97
|
+
limit = MAX_AUDIO_SAMPLES // max(channels, 1) # the most frames of MAX_AUDIO_SAMPLES samples
|
|
98
|
+
window = int((max_seconds + 1e-6) * sr) if max_seconds else None # the most frames in the window
|
|
99
|
+
keep = limit if window is None else min(limit, window)
|
|
100
|
+
x = f.read(keep + 1, dtype="float32", always_2d=True) # one frame more shows the clip is longer
|
|
101
|
+
except (RuntimeError, TypeError, ValueError) as e: # soundfile's LibsndfileError is a RuntimeError
|
|
102
|
+
raise ValueError(f"media {n}: not readable audio (WAV, FLAC, OGG or MP3; {type(e).__name__})") from None
|
|
103
|
+
if x.shape[0] == 0:
|
|
104
|
+
raise ValueError(f"media {n}: empty audio")
|
|
105
|
+
seconds = max(x.shape[0], frames if frames > 0 else 0) / sr # (the header's length when the read stopped early)
|
|
106
|
+
if window is not None and x.shape[0] > window:
|
|
107
|
+
raise ValueError(f"media {n}: {seconds:.1f} s of audio, more than the model's {max_seconds:g} s")
|
|
108
|
+
if x.shape[0] > limit:
|
|
109
|
+
raise ValueError(f"media {n}: {seconds:.1f} s of audio in {channels} channels, more than "
|
|
110
|
+
f"{MAX_AUDIO_SAMPLES:,} samples")
|
|
111
|
+
x = x.mean(axis=1)
|
|
112
|
+
if sr != SAMPLE_RATE:
|
|
113
|
+
from scipy.signal import resample_poly
|
|
114
|
+
g = gcd(int(sr), SAMPLE_RATE)
|
|
115
|
+
x = resample_poly(x, SAMPLE_RATE // g, int(sr) // g)
|
|
116
|
+
return np.ascontiguousarray(x, dtype=np.float32)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def decode(entries, kinds, max_audio_seconds=None):
|
|
120
|
+
"""The request's "media" -> (images, audio arrays, the type of every item in order). kinds: what the model takes."""
|
|
121
|
+
if not isinstance(entries, list) or not entries:
|
|
122
|
+
raise ValueError('media must be a non-empty list of {"type": "image" | "audio", "data": "<base64>"}')
|
|
123
|
+
if len(entries) > MAX_ITEMS:
|
|
124
|
+
raise ValueError(f"{len(entries)} media items, at most {MAX_ITEMS} per request")
|
|
125
|
+
images, audio, order = [], [], []
|
|
126
|
+
for n, m in enumerate(entries):
|
|
127
|
+
t = m.get("type") if isinstance(m, dict) else None
|
|
128
|
+
if t not in ("image", "audio"):
|
|
129
|
+
raise ValueError(f'media {n}: type must be "image" or "audio"')
|
|
130
|
+
if t not in kinds:
|
|
131
|
+
raise ValueError(f"media {n}: this model does not take {t} (it takes: {', '.join(kinds) or 'no media'})")
|
|
132
|
+
raw = _raw(m.get("data"), n)
|
|
133
|
+
if t == "image":
|
|
134
|
+
images.append(_image(raw, n))
|
|
135
|
+
else:
|
|
136
|
+
audio.append(_audio(raw, n, max_audio_seconds))
|
|
137
|
+
order.append(t)
|
|
138
|
+
return images, audio, order
|
basal/metrics.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Prometheus text exposition for GET /metrics of basal-serve and basal-router. No torch here: basal-router imports
|
|
2
|
+
this module alone (importing basal.server for it took 6-9 s on the router's event loop at the first scrape)."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def prometheus(metrics):
|
|
6
|
+
"""Prometheus text exposition of [(name, help, type, [(labels dict, value)])]; label values escaped as the format
|
|
7
|
+
asks (backslash, newline, double quote)."""
|
|
8
|
+
def esc(v):
|
|
9
|
+
return str(v).replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"')
|
|
10
|
+
out = []
|
|
11
|
+
for name, help_, kind, samples in metrics:
|
|
12
|
+
out += [f"# HELP {name} " + str(help_).replace("\\", "\\\\").replace("\n", "\\n"), f"# TYPE {name} {kind}"]
|
|
13
|
+
for labels, value in samples:
|
|
14
|
+
lab = ",".join(f'{k}="{esc(v)}"' for k, v in labels.items())
|
|
15
|
+
out.append(f"{name}{{{lab}}} {value}" if lab else f"{name} {value}")
|
|
16
|
+
return "\n".join(out) + "\n"
|