diff --git a/build.zig b/build.zig index 08765bd1df..47886e874f 100644 --- a/build.zig +++ b/build.zig @@ -411,6 +411,7 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b .{ .name = "tf-grid-sync-bench", .path = "zig/tests/grid_sync_bench.zig", .about = "A GPU-wide barrier in one persistent dispatch against dependent relaunches" }, .{ .name = "tf-weight-read-check", .path = "zig/tests/weight_read_check.zig", .about = "Check native file reads and failed-read cleanup", .c_source = "zig/tests/pread_fault.c" }, .{ .name = "tf-glm-run", .path = "zig/tests/glm_run.zig", .about = "GLM-5.3-Flash greedy replies at each draft depth against depth 0 and reference tokens" }, + .{ .name = "tf-glm-vision", .path = "zig/tests/glm_vision.zig", .about = "GLM-5.3-Flash's image tower on an image or a reference dump's patches, compared with the dump" }, .{ .name = "tf-glm-attn-probe", .path = "zig/tests/glm_attn_probe.zig", .about = "GLM-5.3-Flash's dense latent attention kernels on given inputs (scores, probabilities, outputs)" }, .{ .name = "tf-moe-bench", .path = "zig/tests/moe_bench.zig", .about = "Routed-expert prompt kernels from .metal files on a skewed routing: chained speed, bits against the first" }, .{ .name = "tf-mm-bench", .path = "zig/tests/mm_bench.zig", .about = "Prompt matmul kernels from .metal files: chained speed at one shape, bits against the first, error against fp64" }, @@ -549,6 +550,8 @@ fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: metal.linkFramework("Metal", .{}); metal.linkFramework("Foundation", .{}); metal.linkFramework("IOSurface", .{}); // the Neural Engine's prompt share passes IOSurfaces + metal.linkFramework("ImageIO", .{}); // GLM-5.3-Flash's image input: decoding (families/glm/image.zig) + metal.linkFramework("CoreGraphics", .{}); metal.linkSystemLibrary("objc", .{}); const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true }); diff --git a/docs/api.md b/docs/api.md index a0563b0048..578b23c744 100644 --- a/docs/api.md +++ b/docs/api.md @@ -68,9 +68,11 @@ chat fields that shape the prompt (`tools`, `reasoning_effort`, `chat_template_k `tokens`, and `token_strs` with `return_token_strs: true`. The IDs are the ones the chat route runs for the same request, images expanded. `/detokenize` takes `tokens` and returns `prompt`. In the Python 0.6.6 engine, `--vision` lets supported Qwen3.5/3.8 dense checkpoints accept `image_url` content parts -alongside text in user messages and in tool results (`role: "tool"`), such as an agent's screenshots. +alongside text in user messages and in tool results (`role: "tool"`), such as an agent's screenshots. The native server +does the same with `--vision` for Qwen3.8-27B on CUDA and GLM-5.3-Flash on Metal, with data URLs, and public HTTPS URLs +under `--vision-urls` ([image input](vision.md#the-native-server)). See [image input](vision.md) for data URLs, public image URLs, limits and cache behavior. -The native binary refuses `--vision` and answers image parts with HTTP 400. +Other native families refuse `--vision` and answer image parts with HTTP 400. Unsupported image input, audio, video and non-text output requests receive HTTP 400. ## Decisions diff --git a/docs/vision.md b/docs/vision.md index 9536f7e7fc..adf85a9a30 100644 --- a/docs/vision.md +++ b/docs/vision.md @@ -142,6 +142,34 @@ This prevents identical image-placeholder token IDs from reusing another image's Multi-turn image conversations work when the request includes the original image content parts, but image-prefix reuse and persisted image KV are not implemented. For Qwen, each image request carries its own multimodal rotary positions and continuation offset, including during concurrent lane rounds. GLM uses its native KDA/NoPE attention state. +## The native server + +`tensorfold-native serve` takes `--vision`, `--vision-max-images` (default 4) and `--vision-image-tokens` (default +4,096) for engines that read images; GLM-5.3-Flash on one Mac reads them so far, and other native engines refuse the +flag at startup. + +- Images arrive as `image_url` data URLs in user messages and tool results. With `--vision-urls` (it needs + `--vision`), a part may name a public HTTPS URL instead, fetched as 0.6.6 fetched it: port 443 without credentials + or a fragment; every address the host resolves to public (no private, loopback, link-local, carrier-grade NAT, + documentation, multicast or metadata address, and for IPv6 global unicast only, without 6to4 or Teredo); TLS + verified for the host against the system's certificates, on the address that was checked; up to 3 redirects, + each checked again; a declared `image/jpeg`, `image/png` or `image/webp`, uncompressed; 10 MB an image and 20 MB + a request across data URLs and downloads; 10 s a download and 30 s a request's downloads. The refusals are + 0.6.6's words; a TLS failure, like any other failed connection, is "image download failed or timed out". Host + names that aren't ASCII and IPv6 address literals are refused. Without the flag, an HTTPS URL is refused with the + flag's name. +- PNG and JPEG are decoded by the platform's decoder (ImageIO on macOS). WebP is refused by name until a decoder + exists; other formats are refused. +- The limits and the processing are 0.6.6's: EXIF orientation, alpha composited over white, the GLM5-Next processor's + sizing and PIL's bicubic resampler. Six drawn PNG fixtures give patches bit-equal to 0.6.6 with mlx-vlm + (`tools/zig/glm_vision_fixtures.py`). JPEG patches differ slightly, because ImageIO and libjpeg-turbo decode + differently. +- Images are counted from the request's image parts. A user or tool message whose text spells the model's image + markers (`<|image|>`, `<|begin_of_image|>`, `<|end_of_image|>`) is tokenized as ordinary text, so only the chat + template's own markers, one wrapper for each image part, become image tokens. +- The prompt cache keys each image's placeholder rows by the image's content, so a kept state resumes the same image + and never another one under the same placeholders. Image conversations reuse their history like text ones. + ## Verification Compare image requests with `draft: true` and `draft: false` at identical sampling settings and seed, then compare concurrent requests with their solo results. diff --git a/tools/zig/glm_vision_fixtures.py b/tools/zig/glm_vision_fixtures.py new file mode 100644 index 0000000000..72e222fe93 --- /dev/null +++ b/tools/zig/glm_vision_fixtures.py @@ -0,0 +1,151 @@ +"""GLM-5.3-Flash image input against the Python frontend, on a fixed image set (#565's gate).""" + +from __future__ import annotations + +import argparse +import io +import json +import re +import subprocess +import sys +from pathlib import Path + +import mlx.core as mx +import numpy as np +from PIL import Image, ImageDraw + + +def draw_shapes(size: tuple[int, int]) -> Image.Image: + w, h = size + im = Image.new("RGB", size, (245, 240, 230)) + d = ImageDraw.Draw(im) + d.ellipse((w * 0.08, h * 0.25, w * 0.42, h * 0.7), fill=(210, 40, 40)) + d.rectangle((w * 0.55, h * 0.25, w * 0.9, h * 0.7), fill=(40, 70, 200)) + for x in range(int(w * 0.1), int(w * 0.9), 6): + d.line((x, h * 0.8, x, h * 0.92), fill=(20, 20, 20), width=2) + d.text((w * 0.4, h * 0.06), "GLM 7", fill=(0, 0, 0)) + return im + + +def fixtures(folder: Path) -> list[Path]: + folder.mkdir(parents=True, exist_ok=True) + out = [] + + def save(name: str, im: Image.Image, **kw) -> None: + p = folder / name + im.save(p, **kw) + out.append(p) + + save("shapes.png", draw_shapes((517, 389))) # padding only + big = draw_shapes((2000, 1500)) + px = big.load() + for y in range(0, 1500, 3): # fine detail for the antialias + for x in range(0, 2000, 7): + px[x, y] = ((x * 3) % 256, (y * 5) % 256, (x + y) % 256) + save("large.png", big) # antialiased downscale + save("tiny.png", draw_shapes((20, 15))) # upscale to the token floor + logo = Image.new("RGBA", (96, 96), (0, 0, 0, 0)) + d = ImageDraw.Draw(logo) + d.rounded_rectangle((4, 4, 92, 92), 16, fill=(30, 30, 40, 255)) + d.polygon([(26, 28), (70, 28), (30, 68), (70, 68), (70, 74), (24, 74), (64, 34), (26, 34)], fill=(255, 255, 255, 230)) + save("logo.png", logo) # RGBA upscale, alpha over white + pal = draw_shapes((517, 389)).quantize(32) + pal.info["transparency"] = 0 + save("palette.png", pal, transparency=0) # palette, a transparent entry + la = Image.new("LA", (240, 180), (128, 0)) + d = ImageDraw.Draw(la) + for r in range(80, 0, -8): + d.ellipse((120 - r, 90 - r, 120 + r, 90 + r), fill=(255 - 3 * r, 255 - 2 * r)) + save("gray-alpha.png", la) # gray with alpha + rot = draw_shapes((300, 200)) + exif = Image.Exif() + exif[0x0112] = 6 # rotate 90 degrees clockwise + save("rotated.jpg", rot, quality=90, exif=exif.tobytes()) # EXIF orientation + save("shapes.jpg", draw_shapes((517, 389)), quality=85) # baseline JPEG + return out + + +def reference(model: Path, image_path: Path, out: Path, tower, processor, max_tokens: int) -> dict: + from tensorfold.vision.images import DEFAULT_LIMITS, _decode + + out.mkdir(parents=True, exist_ok=True) + image = _decode(image_path.read_bytes(), "auto", DEFAULT_LIMITS, DEFAULT_LIMITS.max_total_pixels).to_pil() + done = processor([image], return_tensors="np", min_image_tokens=min(16, max_tokens), max_image_tokens=max_tokens) + patches = np.asarray(done["pixel_values"], dtype=np.float32) + grid = np.asarray(done["image_grid_thw"], dtype=np.int64) + dtype = tower.patch_embed.proj.weight.dtype + x = mx.array(patches).astype(dtype) + g = mx.array(grid, dtype=mx.int32) + h = tower.patch_embed(x) + embed = h + pos = tower._rotary_embeddings(g) + cu = mx.array([0, int(h.shape[0])]) + block0 = None + for i, block in enumerate(tower.blocks): + h = block(h, cu, pos) + if i == 0: + block0 = h + blocks = h + features = tower(x, g) + mx.eval(embed, block0, blocks, features) + for name, a in (("patches", patches), ("embed", embed), ("block0", block0), ("blocks", blocks), ("features", features)): + np.asarray(a.astype(mx.float32) if isinstance(a, mx.array) else a, dtype=np.float32).tofile(out / f"{name}.f32") + meta = {"image": str(image_path), "size": list(image.size), "mode": Image.open(image_path).mode, "grid_thw": grid[0].tolist(), + "max_tokens": max_tokens, "tokens": int(features.shape[0]), "patch_width": int(patches.shape[1]), "dtype": str(dtype)} + (out / "meta.json").write_text(json.dumps(meta, indent=1) + "\n") + return meta + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--model", required=True, help="the GLM-5.3-Flash checkpoint folder") + ap.add_argument("--out", required=True, help="where the images and their references go") + ap.add_argument("--max-tokens", type=int, default=4096, help="the visual-token budget an image is sized to") + ap.add_argument("--tower", help="tf-glm-vision: also compare the native patches and tower with each reference") + args = ap.parse_args() + + from mlx_vlm.models.glm5_next.config import VisionConfig + from mlx_vlm.models.glm5_next.processing import Glm5NextImageProcessor + from mlx_vlm.models.glm5_next.vision import VisionModel + + model, out = Path(args.model), Path(args.out) + config = json.loads((model / "config.json").read_text()) + proc_cfg = json.loads((model / "processor_config.json").read_text())["image_processor"] + proc_cfg.pop("image_processor_type", None) + processor = Glm5NextImageProcessor(**proc_cfg) + tower = VisionModel(VisionConfig.from_dict(config["vision_config"])) + index = json.loads((model / "model.safetensors.index.json").read_text())["weight_map"] + weights = {} + for shard in sorted({f for k, f in index.items() if k.startswith("model.visual.")}): + for k, v in mx.load(str(model / shard)).items(): + if k.startswith("model.visual."): + weights[k[len("model.visual."):]] = v + tower.load_weights(list(tower.sanitize(weights).items()), strict=True) + mx.eval(tower.parameters()) + + failures = 0 + for image in fixtures(out / "images"): + ref = out / image.name.replace(".", "-") + meta = reference(model, image, ref, tower, processor, args.max_tokens) + line = f"{image.name:15} {meta['size'][0]}x{meta['size'][1]} {meta['mode']:5} grid {meta['grid_thw']} {meta['tokens']} tokens" + if args.tower: + run = subprocess.run([args.tower, str(model), str(ref), "features", str(image)], capture_output=True, text=True) + text = run.stdout + run.stderr + p = re.search(r"patches: (\d+) of (\d+) values differ", text) + c = re.search(r"cosine mean ([0-9.]+) worst ([0-9.]+)", text) + if run.returncode != 0 or not p or not c: + failures += 1 + line += f" FAIL: {text.strip().splitlines()[-1] if text.strip() else run.returncode}" + else: + differ = int(p.group(1)) + exact = differ == 0 + # PNG patches must be bit-exact; JPEG patches differ by decoder (ImageIO against libjpeg-turbo) + failures += (not exact) and image.suffix == ".png" + line += f" patches {'equal' if exact else f'{differ} of {p.group(2)} differ'}, rows' cosine {c.group(1)} (worst {c.group(2)})" + print(line) + print("PASS" if failures == 0 else f"FAIL: {failures}") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/zig/lean_check.py b/tools/zig/lean_check.py index a97aa37701..a5928f867b 100644 --- a/tools/zig/lean_check.py +++ b/tools/zig/lean_check.py @@ -19,6 +19,8 @@ "zig/src/families/flashnext/roles_gen.zig", "zig/kernels/metal/flashnext/sources_gen.zig", ) +# Third-party sources kept as their authors wrote them (stb_image.h) are skipped too. +VENDORED = "zig/vendor/" def generator_output(path: Path) -> bool: @@ -31,7 +33,7 @@ def generator_output(path: Path) -> bool: def problems(path: Path) -> list[str]: """Every rule break in one file, as 'path:line: reason'.""" - if generator_output(path): + if generator_output(path) or path.relative_to(ROOT).as_posix().startswith(VENDORED): return [] lines = path.read_text(errors="replace").splitlines() rel, found = path.relative_to(ROOT), [] diff --git a/tools/zig/vision_served.py b/tools/zig/vision_served.py new file mode 100644 index 0000000000..8d9a645e7f --- /dev/null +++ b/tools/zig/vision_served.py @@ -0,0 +1,164 @@ +"""Image input served end to end on a running ``tensorfold-native --vision`` (#565's served checks).""" + +from __future__ import annotations + +import argparse +import base64 +import concurrent.futures as cf +import json +import sys +import urllib.error +import urllib.request +from pathlib import Path + + +def post(url: str, body: dict) -> tuple[int, dict]: + req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=1800) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"{}") + + +def data_url(raw: bytes, mime: str) -> str: + return f"data:{mime};base64,{base64.b64encode(raw).decode()}" + + +def image_part(url: str, detail: str | None = None) -> dict: + inner = {"url": url} + if detail: + inner["detail"] = detail + return {"type": "image_url", "image_url": inner} + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--url", default="http://127.0.0.1:8000") + ap.add_argument("--images", required=True) + ap.add_argument("--tokens", type=int, default=48) + ap.add_argument("--fresh-url", help="the same model served with --prompt-cache-gib 0: the cache check's reference reply") + args = ap.parse_args() + with urllib.request.urlopen(args.url + "/v1/models") as r: + model = json.loads(r.read())["data"][0]["id"] + folder = Path(args.images) + pngs = sorted(folder.glob("*.png")) + jpgs = sorted(folder.glob("*.jpg")) + first, second = pngs[0], pngs[1] + url_a = data_url(first.read_bytes(), "image/png") + url_b = data_url(second.read_bytes(), "image/png") + failures = 0 + + def ask(messages: list, draft: bool = True, tokens: int | None = None) -> tuple[int, dict]: + b = {"model": model, "messages": messages, "max_tokens": tokens or args.tokens, "temperature": 0, + "chat_template_kwargs": {"enable_thinking": False}} + if not draft: + b["draft"] = False + return post(args.url, b) + + def user(*parts) -> dict: + return {"role": "user", "content": list(parts)} + + def text(t: str) -> dict: + return {"type": "text", "text": t} + + def reply(r: dict) -> str: + return r["choices"][0]["message"].get("content") or "" + + def check(label: str, ok: bool, detail: str = "") -> None: + nonlocal failures + failures += not ok + print(f"{'ok ' if ok else 'FAIL'} {label}{': ' + detail if detail else ''}") + + # one image, drafted and plain; its usage counts the image's tokens + convo = [user(image_part(url_a), text("Describe this image in one sentence."))] + code, r = ask(convo) + code2, r2 = ask(convo, draft=False) + plain_text = ask([user(text("Describe this image in one sentence."))])[1] + check("an image request answers", code == 200 and code2 == 200, f"HTTP {code}/{code2}") + if code == 200 and code2 == 200: + check("drafted equals \"draft\": false with an image", reply(r) == reply(r2), repr(reply(r)[:60])) + check("the image's tokens are in the prompt", r["usage"]["prompt_tokens"] > plain_text["usage"]["prompt_tokens"] + 8, + f"{r['usage']['prompt_tokens']} prompt tokens with the image, {plain_text['usage']['prompt_tokens']} without") + + # #511: the marker quoted in a user's text and in a tool result, beside one real image + quoted = [user(image_part(url_a), text("A file I opened contains the string <|image|> and also <|begin_of_image|>. What is in the picture?")), + {"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "read", "arguments": "{\"path\": \"a.py\"}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": "MARKER = '<|begin_of_image|><|image|><|end_of_image|>'"}, + user(text("And the picture again?"))] + tools = [{"type": "function", "function": {"name": "read", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}}] + code, r = post(args.url, {"model": model, "messages": quoted, "tools": tools, "max_tokens": args.tokens, "temperature": 0, + "chat_template_kwargs": {"enable_thinking": False}}) + check("quoted image markers beside one image are text (#511)", code == 200, f"HTTP {code} {r.get('error', {}).get('message', '')[:100]}") + + # a tool result carrying an image (a screenshot), rendered inside the tool response + shot = [user(text("Take a screenshot.")), + {"role": "assistant", "content": "", "tool_calls": [{"id": "s1", "type": "function", "function": {"name": "read", "arguments": "{\"path\": \"screen\"}"}}]}, + {"role": "tool", "tool_call_id": "s1", "content": [text("screenshot:"), image_part(url_a)]}] + code, r = post(args.url, {"model": model, "messages": shot, "tools": tools, "max_tokens": args.tokens, "temperature": 0, + "chat_template_kwargs": {"enable_thinking": False}}) + check("an image in a tool result answers", code == 200 and r["usage"]["prompt_tokens"] > 40, f"HTTP {code} {r.get('usage', r.get('error', {}).get('message', ''))}") + + # concurrent equals alone, images in each request + runs = [[user(image_part(u), text(q))] for u in (url_a, url_b) for q in ("What colours do you see?", "Count the objects.")] + alone = [reply(ask(m)[1]) for m in runs] + with cf.ThreadPoolExecutor(len(runs)) as pool: + together = [reply(f.result()[1]) for f in [pool.submit(ask, m) for m in runs]] + same = sum(x == y for x, y in zip(alone, together)) + check("concurrent image requests equal their runs alone", same == len(runs), f"{same} of {len(runs)}") + + # the prompt cache keeps state at planned cuts (system, a 256+ token reply): turn three resumes past turn 2's image + system = {"role": "system", "content": " ".join(f"Rule {i}: describe what you see plainly and briefly." for i in range(120))} + q, q2, q3 = "What is shown?", "Say that again in three words.", "And once more." + head = ask([system, user(text(q))], tokens=1)[1]["usage"]["prompt_tokens"] # the text alone: past where an image starts + first = " ".join(f"Detail {i}: the picture shows shapes, colours and lines." for i in range(40)) # a reply of 256+ tokens + + def turns(url: str) -> tuple[list, list]: + two = [system, user(image_part(url), text(q)), {"role": "assistant", "content": first}, user(text(q2))] + return two, two + [{"role": "assistant", "content": "Three words here."}, user(text(q3))] + + two_a, three_a = turns(url_a) + two_b, three_b = turns(url_b) + if args.fresh_url: # B's reply with nothing kept + rf = post(args.fresh_url, {"model": model, "messages": three_b, "max_tokens": 24, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}})[1] + ask(two_a, tokens=8) # keeps A's state at the long reply's start, past its image + code, ra = ask(three_a, tokens=24) + cached_a = ra.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1 + check("an image conversation's later turn resumes past its image", code == 200 and cached_a > head, f"cached {cached_a} of {ra.get('usage', {}).get('prompt_tokens')}; the text alone is {head}") + # image B under the same text and placeholder ids resumes at most the text before its image + code, rb = ask(three_b, tokens=24) + cached_b = rb.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1 + check("another image under the same placeholders resumes only the text before it", code == 200 and cached_b < head, + f"cached {cached_b} of {rb.get('usage', {}).get('prompt_tokens')}") + if args.fresh_url: + check("and answers as a server with nothing kept", reply(rf) == reply(rb), repr(reply(rb)[:60])) + + # refusals, before any token + webp = b"RIFF\x24\x00\x00\x00WEBPVP8 \x18\x00\x00\x00" + bytes(24) + gif = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00!\xf9\x04\x00\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;" + refusals = [ + ("WebP, by name", [user(image_part(data_url(webp, "image/webp")), text("hi"))], "WebP"), + ("GIF", [user(image_part(data_url(gif, "image/gif")), text("hi"))], "not PNG or JPEG"), + ("an image in an assistant message", [user(text("hi")), {"role": "assistant", "content": [image_part(url_a)]}, user(text("ok"))], "user and tool messages only"), + ("too many images", [user(*[image_part(url_a)] * 5, text("hi"))], "at most"), + ("a remote URL without --vision-urls", [user(image_part("https://example.com/cat.png"), text("hi"))], "--vision-urls"), + ("a URL that is neither data nor https", [user(image_part("http://example.com/cat.png"), text("hi"))], "data URLs or public HTTPS URLs"), + ("bad base64", [user(image_part("data:image/png;base64,@@@@"), text("hi"))], "encoding"), + ("a bad detail", [user(image_part(url_a, "medium"), text("hi"))], "detail"), + ("bytes that decode as nothing", [user(image_part(data_url(b"\x89PNG\r\n\x1a\n" + bytes(32), "image/png")), text("hi"))], "could not be decoded"), + ] + for label, messages, words in refusals: + code, r = ask(messages) + message = r.get("error", {}).get("message", json.dumps(r)) + check(f"refused {label}", code == 400 and words in message, f"HTTP {code} {message[:100]!r}") + if jpgs: + code, r = ask([user(image_part(data_url(jpgs[0].read_bytes(), "image/jpeg")), text("Describe it."))]) + check("a JPEG answers", code == 200, f"HTTP {code}") + code, r = ask([user(image_part(url_a, "low"), text("Describe it."))]) + check("detail low answers", code == 200, f"HTTP {code}") + print("PASS" if failures == 0 else f"FAIL: {failures}") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/zig/vision_urls_served.py b/tools/zig/vision_urls_served.py new file mode 100644 index 0000000000..3ab3c5773a --- /dev/null +++ b/tools/zig/vision_urls_served.py @@ -0,0 +1,99 @@ +"""Image URLs served end to end on a running ``tensorfold-native --vision --vision-urls`` (#565's URL checks).""" + +from __future__ import annotations + +import argparse +import base64 +import json +import ssl +import sys +import urllib.error +import urllib.request + +IMAGE = "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/tensorfold-hero.png" +REDIRECT = "https://github.com/ashhart/TensorFold/raw/main/assets/tensorfold-hero.png" # 302 to IMAGE's host +OTHER = "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/tensorfold-cuda-banner.png" + + +def post(url: str, body: dict) -> tuple[int, dict]: + req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=1800) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"{}") + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--url", default="http://127.0.0.1:8000") + ap.add_argument("--tokens", type=int, default=48) + args = ap.parse_args() + with urllib.request.urlopen(args.url + "/v1/models") as r: + model = json.loads(r.read())["data"][0]["id"] + try: # python.org's macOS builds ship no CA store until "Install Certificates" runs + import certifi + tls = ssl.create_default_context(cafile=certifi.where()) + except ImportError: + tls = ssl.create_default_context() + with urllib.request.urlopen(IMAGE, timeout=30, context=tls) as r: + inline = "data:image/png;base64," + base64.b64encode(r.read()).decode() + failures = 0 + + def ask(*parts) -> tuple[int, dict]: + return post(args.url, {"model": model, "messages": [{"role": "user", "content": list(parts)}], "max_tokens": args.tokens, + "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}}) + + def image(url: str) -> dict: + return {"type": "image_url", "image_url": {"url": url}} + + def text(t: str) -> dict: + return {"type": "text", "text": t} + + def check(label: str, ok: bool, detail: str = "") -> None: + nonlocal failures + failures += not ok + print(f"{'ok ' if ok else 'FAIL'} {label}{': ' + detail if detail else ''}") + + def same(label: str, a: tuple[int, dict], b: tuple[int, dict]) -> None: + ok = a[0] == 200 and b[0] == 200 and a[1]["usage"]["prompt_tokens"] == b[1]["usage"]["prompt_tokens"] and \ + a[1]["choices"][0]["message"]["content"] == b[1]["choices"][0]["message"]["content"] + detail = f"HTTP {a[0]}/{b[0]}" if a[0] != 200 or b[0] != 200 else \ + f"{a[1]['usage']['prompt_tokens']} prompt tokens, {a[1]['choices'][0]['message']['content'][:60]!r}" + if a[0] != 200 or b[0] != 200: + detail += " " + json.dumps(a[1].get("error") or b[1].get("error"))[:120] + check(label, ok, detail) + + q = text("Describe this image in one sentence.") + by_data = ask(image(inline), q) + same("an HTTPS image URL answers as its bytes in a data URL", ask(image(IMAGE), q), by_data) + same("a URL that redirects to the image answers the same", ask(image(REDIRECT), q), by_data) + two = ask(image(OTHER), image(inline), text("How do these two images differ?")) + check("a URL and a data URL in one request answer", two[0] == 200, f"HTTP {two[0]} {json.dumps(two[1].get('error', ''))[:100]}") + + refusals = [ + ("an HTTP error", "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/no-such-image.png", "image download returned HTTP 404"), + ("a page that isn't an image", "https://example.com/", "image URL content type must be JPEG, PNG or WebP"), + ("a host that resolves to a private address", "https://localtest.me/x.png", "image URLs must resolve only to public internet addresses"), + ("a private address literal", "https://169.254.169.254/latest/meta-data", "image URLs must resolve only to public internet addresses"), + ("localhost", "https://localhost/x.png", "image URLs must use public internet hosts"), + ("cloud metadata by name", "https://metadata.google.internal/x.png", "image URLs must use public internet hosts"), + ("an expired certificate", "https://expired.badssl.com/", "image download failed or timed out"), + ("a certificate for another host", "https://wrong.host.badssl.com/", "image download failed or timed out"), + ("a self-signed certificate", "https://self-signed.badssl.com/", "image download failed or timed out"), + ("plain HTTP", "http://example.com/x.png", "images require data URLs or public HTTPS URLs"), + ("another port", "https://example.com:8443/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment"), + ("credentials", "https://user:pw@example.com/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment"), + ("a fragment", "https://example.com/x.png#a", "image URL must be HTTPS on port 443, without credentials or a fragment"), + ("a host that never resolves", "https://no-such-host.invalid/x.png", "image host could not be resolved"), + ] + for label, url, words in refusals: + code, r = ask(image(url), text("hi")) + message = r.get("error", {}).get("message", json.dumps(r)) + check(f"refused {label}", code == 400 and message == words, f"HTTP {code} {message[:100]!r}") + print("PASS" if failures == 0 else f"FAIL: {failures}") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index eac681628c..062052b612 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -15,6 +15,7 @@ const glue = &[_][]const u8{ "-O3", "--fmad=false", "--ftz=false", "--prec-div=t const kernels = [_]Kernel{ .{ .name = "gdn", .flags = &.{ "-O3", "--fmad=false" } }, // cuda/kernels/gdn.py, tensorfold_gdn_v2 + .{ .name = "gdn_prefill", .flags = &.{ "-O3", "--fmad=false" } }, // the same extension's prompt chain .{ .name = "probe", .flags = &.{"-O3"} }, .{ .name = "qmm_group", .flags = &.{"-O3"} }, // cuda/kernels/qmm.py, tensorfold_qmm_v5 .{ .name = "qmm_prefill", .flags = &.{"-O3"} }, @@ -32,6 +33,8 @@ const kernels = [_]Kernel{ .{ .name = "lane_gemv", .flags = &.{"-O3"} }, // ours: qmm_group's arithmetic, a column tile's K slices in one CTA .{ .name = "sample", .flags = &.{ "-O3", "--fmad=false", "--ftz=false" } }, // ours: the Metal engine's keyed draws .{ .name = "train", .flags = &.{"-O3"} }, // ours: Sliding Weights' learning step (train.metal's kernels) + .{ .name = "qwen_ops", .flags = &.{"-O3"} }, // ours: the 27B's batched state copies, taps, drafter norms and rotary + .{ .name = "qwen_vision", .flags = &.{ "-O3", "--fmad=false" } }, // ours: the Qwen3.5 vision tower's glue and attention .{ .name = "nemotron_norms", .flags = glue }, // ours, each with a host reference (glue_ref.zig): Nemotron's glue .{ .name = "nemotron_route", .flags = glue }, .{ .name = "nemotron_mamba", .flags = glue }, @@ -48,6 +51,7 @@ const kernels = [_]Kernel{ .{ .name = "torch_indexing", .src = "torch_ops/indexing", .flags = torch_ops }, .{ .name = "torch_movement", .src = "torch_ops/movement", .flags = torch_ops }, .{ .name = "torch_nemotron_constants", .src = "torch_ops/nemotron_constants", .flags = torch_ops }, + .{ .name = "torch_norm_rotary", .src = "torch_ops/norm_rotary", .flags = torch_ops }, // F.rms_norm of 5120 columns }; /// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define. @@ -78,7 +82,7 @@ fn runtime(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti return cuda; } -fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module } { +fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen27: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module } { const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); core.addImport("tokenizer", tokenizer); @@ -90,7 +94,16 @@ fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin nemotron.addImport("lanes", lanes); nemotron.addImport("heat", heat); nemotron.addImport("nemotron_draft_ids", draft_ids); - return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .tokenizer = tokenizer, .heat = heat }; + // the 27B's CUDA engine, beside its Metal one in the family's folder (it reads the family's config.zig) + const qwen27 = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); + qwen27.addImport("cuda", cuda); + qwen27.addImport("core", core); + qwen27.addImport("lanes", lanes); + qwen27.addImport("nemotron", nemotron); // the checkpoint Source and torch ops the CUDA families share + // images' PNG and JPEG decoding on Linux (stb_image, vendored) + qwen27.addCSourceFile(.{ .file = b.path("zig/vendor/stb/stb_image.c"), .flags = &.{ "-O2", "-fno-sanitize=undefined" } }); + qwen27.addIncludePath(b.path("zig/vendor/stb")); + return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .qwen27 = qwen27, .tokenizer = tokenizer, .heat = heat }; } /// Linux targets: fatbins (-Dnvcc builds them, -Dfatbins embeds prebuilt ones), `tensorfold` and `tf-cuda-test`. @@ -122,7 +135,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu cli.addImport("core", mods.core); cli.addImport("lanes", mods.lanes); cli.addImport("nemotron", mods.nemotron); - const native = engines(b, target, optimize, cuda, mods.lanes, mods.nemotron); + const native = engines(b, target, optimize, cuda, mods.lanes, mods.nemotron, mods.qwen27); cli.addOptions("build_options", build_options); cli.addImport("checkpoint_cli", checkpointCli(b, target, optimize, strip, native.engines, mods.core)); b.installArtifact(b.addExecutable(.{ .name = "tensorfold", .root_module = cli })); @@ -139,18 +152,22 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("exlr8_frozen_dense", b.createModule(.{ .root_source_file = b.path("zig/tests/fixtures/exlr8/frozen_dense.zig"), .target = target, .optimize = optimize })); for (exlr8_build.denseModules(b, target, optimize, exlr8, exlr8_tests[0])) |m| runner.addImport(m.name, m.module); b.installArtifact(b.addExecutable(.{ .name = "tf-cuda-test", .root_module = runner })); - nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.tokenizer, build_options, true).root_module.strip = strip; + const qwen_cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/qwen27_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); + qwen_cli.addImport("cuda", cuda); + qwen_cli.addImport("qwen27", mods.qwen27); + b.installArtifact(b.addExecutable(.{ .name = "tf-qwen27-cuda", .root_module = qwen_cli })); + nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.qwen27, mods.tokenizer, build_options, true).root_module.strip = strip; } /// The CUDA engines a native server opens (native/cuda.zig), over the given runtime and families. -fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module) struct { api: *std.Build.Module, engines: *std.Build.Module } { +fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen27: *std.Build.Module) struct { api: *std.Build.Module, engines: *std.Build.Module } { const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const mod = b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "nemotron", .module = nemotron } }, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "nemotron", .module = nemotron }, .{ .name = "qwen27", .module = qwen27 } }, }); return .{ .api = api, .engines = mod }; } @@ -161,8 +178,8 @@ fn checkpointCli(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. } /// `zig build native`: tensorfold-native with the CUDA engines into zig-out/native/bin, as the Metal build makes it. -fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { - const m = engines(b, target, optimize, cuda, lanes, nemotron); +fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen27: *std.Build.Module, tokenizer: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { + const m = engines(b, target, optimize, cuda, lanes, nemotron, qwen27); // the HTTP side keeps its safety checks; the engine below it runs at `optimize` (the tokenizer is the family's) const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); const exe = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ @@ -190,7 +207,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/build/check_fatbins.zig"), .target = host }) })).step); const cuda = runtime(b, host, .debug, &.{}); const mods = family(b, host, .debug, cuda, draft_ids); - const native_modules = engines(b, host, .debug, cuda, mods.lanes, mods.nemotron); + const native_modules = engines(b, host, .debug, cuda, mods.lanes, mods.nemotron, mods.qwen27); const native = native_modules.engines; // the HTTP server's unit tests (zig/src/server/root.zig), which the macOS build runs, on Linux hosts too const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = host, .optimize = .debug, .link_libc = true }); @@ -210,7 +227,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st @import("cortheon_fuzz.zig").add(b, host, native_modules.api, mods.tokenizer, template); } // the tokenizer's own tests (memo, steps, regex, unicode) run here: no other test binary reaches them - for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.tokenizer, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.qwen27, mods.heat, mods.tokenizer, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); const cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cuda_main.zig"), .target = host, .optimize = .debug, .link_libc = true }); cli.addImport("cuda", cuda); cli.addImport("core", mods.core); @@ -246,7 +263,7 @@ pub fn distServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *s }; const cuda = runtime(b, target, .fast, if (prebuilt != null) &images else &.{}); const mods = family(b, target, .fast, cuda, draft_ids); - return nativeServer(b, target, .fast, cuda, mods.core, mods.lanes, mods.nemotron, mods.tokenizer, build_options, false); + return nativeServer(b, target, .fast, cuda, mods.core, mods.lanes, mods.nemotron, mods.qwen27, mods.tokenizer, build_options, false); } /// SASS targets every release fatbin holds: Ampere (sm_86), RTX 50 and RTX PRO Blackwell (sm_120), GB10 (sm_121). diff --git a/zig/kernels/cuda/gdn_prefill.cu b/zig/kernels/cuda/gdn_prefill.cu new file mode 100644 index 0000000000..a892ad52d7 --- /dev/null +++ b/zig/kernels/cuda/gdn_prefill.cu @@ -0,0 +1,150 @@ +// Device code of src/tensorfold/cuda/kernels/gdn_prefill.cu (lines 1-145, comments and ATen includes dropped). + +#include +#include +#include + +namespace tf_gdn_prefill { + +constexpr int DK = 128; +constexpr int DV = 128; + +__device__ __forceinline__ float4 widen(uint2 w) { + const __nv_bfloat162 a = *reinterpret_cast(&w.x); + const __nv_bfloat162 b = *reinterpret_cast(&w.y); + return make_float4(__low2float(a), __high2float(a), __low2float(b), __high2float(b)); +} + +__device__ __forceinline__ float4 widen(float4 w) { return w; } + +template +struct Prefetch { + using Raw = typename std::conditional::value, float4, uint2>::type; + static constexpr int KQ = STEPS * (DK / 4) / THREADS, VV = STEPS * ROWS / 8 / THREADS; + static_assert(KQ * THREADS == STEPS * (DK / 4) && VV * THREADS * 8 == STEPS * ROWS, "whole slots a thread"); + Raw kr[KQ], qr[KQ]; + uint4 vr[VV]; + float gr, br; + + __device__ __forceinline__ void fetch(const QK* q, const QK* k, const __nv_bfloat16* v, const float* g, + const float* beta, int t0, int W, int hk, int hv, int head, int key_head, + int col0) { +#pragma unroll + for (int it = 0; it < KQ; ++it) { + const int i = threadIdx.x + it * THREADS, st = i / (DK / 4), c = i % (DK / 4); + const size_t at = (static_cast(min(t0 + st, W - 1)) * hk + key_head) * DK + 4 * c; + kr[it] = *reinterpret_cast(k + at); + qr[it] = *reinterpret_cast(q + at); + } +#pragma unroll + for (int it = 0; it < VV; ++it) { + const int i = threadIdx.x + it * THREADS, st = i / (ROWS / 8), c = i % (ROWS / 8); + vr[it] = *reinterpret_cast(v + (static_cast(min(t0 + st, W - 1)) * hv + head) * DV + + col0 + 8 * c); + } + if (threadIdx.x < STEPS) { + const size_t at = static_cast(min(t0 + static_cast(threadIdx.x), W - 1)) * hv + head; + gr = g[at]; + br = beta[at]; + } + } + + __device__ __forceinline__ void store(float4 (*ks)[DK / 4], float4 (*qs)[DK / 4], float* gs, float* bs, + __nv_bfloat16 (*vs)[ROWS]) const { +#pragma unroll + for (int it = 0; it < KQ; ++it) { + const int i = threadIdx.x + it * THREADS; + ks[i / (DK / 4)][i % (DK / 4)] = widen(kr[it]); + qs[i / (DK / 4)][i % (DK / 4)] = widen(qr[it]); + } +#pragma unroll + for (int it = 0; it < VV; ++it) { + const int i = threadIdx.x + it * THREADS; + *reinterpret_cast(&vs[i / (ROWS / 8)][8 * (i % (ROWS / 8))]) = vr[it]; + } + if (threadIdx.x < STEPS) { + gs[threadIdx.x] = gr; + bs[threadIdx.x] = br; + } + } +}; + +template +__global__ void __launch_bounds__(2 * ROWS) chain_kernel( + const QK* __restrict__ q, const QK* __restrict__ k, const __nv_bfloat16* __restrict__ v, + const float* __restrict__ g, const float* __restrict__ beta, const float* __restrict__ state, + float* __restrict__ last, __nv_bfloat16* __restrict__ y, int W, int hk, int hv) { + __shared__ float4 ks[STEPS][DK / 4], qs[STEPS][DK / 4]; + __shared__ float gs[STEPS], bs[STEPS]; + __shared__ __align__(16) __nv_bfloat16 vs[STEPS][ROWS]; + const int head = blockIdx.x, row = blockIdx.y * ROWS + (threadIdx.x >> 1), half = threadIdx.x & 1; + const int key_head = head / (hv / hk); + float s[64]; + const float* s0 = state + (static_cast(head) * DV + row) * DK; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 t = *reinterpret_cast(s0 + 8 * j + 4 * half); + s[4 * j] = t.x; s[4 * j + 1] = t.y; s[4 * j + 2] = t.z; s[4 * j + 3] = t.w; + } + Prefetch pf; // each stage's loads in flight during the one before + pf.fetch(q, k, v, g, beta, 0, W, hk, hv, head, key_head, blockIdx.y * ROWS); + for (int t0 = 0; t0 < W; t0 += STEPS) { + const int n = min(STEPS, W - t0); + __syncthreads(); + pf.store(ks, qs, gs, bs, vs); + __syncthreads(); + if (t0 + STEPS < W) pf.fetch(q, k, v, g, beta, t0 + STEPS, W, hk, hv, head, key_head, blockIdx.y * ROWS); + for (int tt = 0; tt < n; ++tt) { + const float gt = gs[tt], bt = bs[tt]; + const size_t vat = (static_cast(t0 + tt) * hv + head) * DV + row; + const float vt = __bfloat162float(vs[tt][threadIdx.x >> 1]); + float m[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 kk = ks[tt][2 * j + half]; + s[4 * j] = s[4 * j] * gt; + s[4 * j + 1] = s[4 * j + 1] * gt; + s[4 * j + 2] = s[4 * j + 2] * gt; + s[4 * j + 3] = s[4 * j + 3] * gt; + m[0] = __fmaf_rn(s[4 * j], kk.x, m[0]); + m[1] = __fmaf_rn(s[4 * j + 1], kk.y, m[1]); + m[2] = __fmaf_rn(s[4 * j + 2], kk.z, m[2]); + m[3] = __fmaf_rn(s[4 * j + 3], kk.w, m[3]); + } + float mem = (m[0] + m[1]) + (m[2] + m[3]); + mem = mem + __shfl_xor_sync(0xffffffffu, mem, 1); + const float delta = (vt - mem) * bt; + float o[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 kk = ks[tt][2 * j + half], qq = qs[tt][2 * j + half]; + s[4 * j] = __fmaf_rn(kk.x, delta, s[4 * j]); + s[4 * j + 1] = __fmaf_rn(kk.y, delta, s[4 * j + 1]); + s[4 * j + 2] = __fmaf_rn(kk.z, delta, s[4 * j + 2]); + s[4 * j + 3] = __fmaf_rn(kk.w, delta, s[4 * j + 3]); + o[0] = __fmaf_rn(s[4 * j], qq.x, o[0]); + o[1] = __fmaf_rn(s[4 * j + 1], qq.y, o[1]); + o[2] = __fmaf_rn(s[4 * j + 2], qq.z, o[2]); + o[3] = __fmaf_rn(s[4 * j + 3], qq.w, o[3]); + } + float out = (o[0] + o[1]) + (o[2] + o[3]); + out = out + __shfl_xor_sync(0xffffffffu, out, 1); + if (half == 0) y[vat] = __float2bfloat16_rn(out); + } + } + float* s1 = last + (static_cast(head) * DV + row) * DK; +#pragma unroll + for (int j = 0; j < 16; ++j) + *reinterpret_cast(s1 + 8 * j + 4 * half) = make_float4(s[4 * j], s[4 * j + 1], s[4 * j + 2], + s[4 * j + 3]); +} + +} // namespace tf_gdn_prefill + +// The instantiations gdn_prefill_cuda launches for bf16 keys: 128 value rows a block, or 64 when heads < SMs. +template __global__ void tf_gdn_prefill::chain_kernel<__nv_bfloat16, 128, 32>(const __nv_bfloat16*, + const __nv_bfloat16*, const __nv_bfloat16*, const float*, const float*, const float*, float*, __nv_bfloat16*, int, + int, int); +template __global__ void tf_gdn_prefill::chain_kernel<__nv_bfloat16, 64, 32>(const __nv_bfloat16*, + const __nv_bfloat16*, const __nv_bfloat16*, const float*, const float*, const float*, float*, __nv_bfloat16*, int, + int, int); diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index 122f404495..c304af66e8 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -1,5 +1,6 @@ // Device code of src/tensorfold/cuda/kernels/prefill_attention.cu (lines 1-250, comments and ATen includes dropped), checked by zig/tests/cuda/copies.py. #include +#include #include #include @@ -56,11 +57,12 @@ __device__ __forceinline__ float rowsum(const float (&c)[8]) { __fadd_rn(__fadd_rn(w[1], w[5]), __fadd_rn(w[3], w[7]))); } -template -__global__ void __launch_bounds__(32 * WARPS, 1) -pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kc, - const __nv_bfloat16* __restrict__ vc, __nv_bfloat16* __restrict__ out, int p0, int W, int H, int HK, - int G, float scale) { +// F8: e4m3 cache rows (kc, vc) with an fp32 scale a row (ks, vs); staging widens them to bf16, so the rest is bf16's. +template +__device__ __forceinline__ void pattn_body(const __nv_bfloat16* __restrict__ q, const void* __restrict__ kc, + const void* __restrict__ vc, const float* __restrict__ ks, + const float* __restrict__ vs, __nv_bfloat16* __restrict__ out, int p0, + int W, int H, int HK, int G, float scale) { constexpr int C = D / 8, K16 = D / 16, NB = D / 8, RB = WARPS / HPC, THREADS = 32 * WARPS; constexpr bool QREG = D <= 128; // the queries' fragments stay in registers, else in shared memory extern __shared__ uint4 smem[]; @@ -71,14 +73,60 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric const int row0 = blockIdx.x * 16 * RB, last = min(row0 + 16 * RB, W) - 1; const int head = hk * G + hg * HPC + warp % HPC, wrow = row0 + (warp / HPC) * 16; const int tiles = (p0 + last) / BN + 1, items = 4 * tiles, limit = p0 + W; + // F8: fetch loads an item's e4m3 words and scales a step ahead, put widens them into its slot, hiding the loads + constexpr int PER = (HALF * C + THREADS - 1) / THREADS; + uint2 pre[F8 ? PER : 1]; + float pre_s[F8 ? PER : 1]; + auto fetch = [&](int item) { + if constexpr (F8) { + const uint8_t* src = static_cast(item % 4 < 2 ? kc : vc); + const float* sc = item % 4 < 2 ? ks : vs; + const int key0 = (item / 4) * BN + (item % 2) * HALF; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int i = threadIdx.x + j * THREADS, key = key0 + i / C; + pre[j] = make_uint2(0u, 0u); + pre_s[j] = 0.0f; + if (i < HALF * C && key < limit) { + const int64_t r = (int64_t)key * HK + hk; + pre[j] = __ldg(reinterpret_cast(src + r * D + (i % C) * 8)); + pre_s[j] = __ldg(sc + r); + } + } + } + }; + auto put = [&](int item) { + if constexpr (F8) { + uint4* dst = slots + (item % NS) * HALF * C; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int i = threadIdx.x + j * THREADS; + if (i >= HALF * C) continue; + uint4 w; + const __nv_fp8x2_storage_t* e = reinterpret_cast(&pre[j]); + uint32_t* o = reinterpret_cast(&w); +#pragma unroll + for (int k = 0; k < 4; ++k) { + const float2 x = __half22float2(__half2(__nv_cvt_fp8x2_to_halfraw2(e[k], __NV_E4M3))); + o[k] = pack(__fmul_rn(x.x, pre_s[j]), __fmul_rn(x.y, pre_s[j])); + } + dst[sw(i / C, i % C)] = w; + } + } + }; auto stage = [&](int item) { - const __nv_bfloat16* src = item % 4 < 2 ? kc : vc; const int key0 = (item / 4) * BN + (item % 2) * HALF; uint4* dst = slots + (item % NS) * HALF * C; - for (int i = threadIdx.x; i < HALF * C; i += THREADS) { - const int key = key0 + i / C; - const bool in = key < limit; // past the cache's filled keys: zeros, never read - cp16z(dst + sw(i / C, i % C), src + ((int64_t)(in ? key : 0) * HK + hk) * D + (i % C) * 8, in); + if constexpr (F8) { + fetch(item); + put(item); + } else { + const __nv_bfloat16* src = static_cast(item % 4 < 2 ? kc : vc); + for (int i = threadIdx.x; i < HALF * C; i += THREADS) { + const int key = key0 + i / C; + const bool in = key < limit; // past the cache's filled keys: zeros, never read + cp16z(dst + sw(i / C, i % C), src + ((int64_t)(in ? key : 0) * HK + hk) * D + (i % C) * 8, in); + } } }; uint32_t qa[QREG ? K16 : 1][4]; @@ -106,6 +154,9 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric if (i < items) stage(i); commit(); } + if constexpr (F8) { + if (NS < items) fetch(NS); + } float o[NB][4]; #pragma unroll for (int i = 0; i < NB; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.0f; @@ -120,7 +171,12 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric }; auto done = [&](int it) { // the slot is free: stage the item NS ahead into it __syncthreads(); - if (it + NS < items) stage(it + NS); + if constexpr (F8) { + if (it + NS < items) { + put(it + NS); + if (it + NS + 1 < items) fetch(it + NS + 1); + } + } else if (it + NS < items) stage(it + NS); commit(); }; auto scores = [&](float (&s)[4][4], const uint4* sl) { @@ -238,8 +294,30 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric } } +template +__global__ void __launch_bounds__(32 * WARPS, 1) +pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kc, + const __nv_bfloat16* __restrict__ vc, __nv_bfloat16* __restrict__ out, int p0, int W, int H, int HK, + int G, float scale) { + pattn_body(q, kc, vc, nullptr, nullptr, out, p0, W, H, HK, G, scale); +} + +template +__global__ void __launch_bounds__(32 * WARPS, 1) +pattn8_kernel(const __nv_bfloat16* __restrict__ q, const uint8_t* __restrict__ kc, const uint8_t* __restrict__ vc, + const float* __restrict__ ks, const float* __restrict__ vs, __nv_bfloat16* __restrict__ out, int p0, + int W, int H, int HK, int G, float scale) { + pattn_body(q, kc, vc, ks, vs, out, p0, W, H, HK, G, scale); +} + } // namespace tf_prefill_attention // Head dim 128, eight warps, eight query heads a block, eight staging slots (Nemotron's 16 heads a KV head). template __global__ void tf_prefill_attention::pattn_kernel<128, 8, 8, 8>(const __nv_bfloat16*, const __nv_bfloat16*, const __nv_bfloat16*, __nv_bfloat16*, int, int, int, int, int, float); +// Head dim 256, two query heads a block, two staging slots beside the staged queries (Qwen3.8's 6 heads a KV head). +template __global__ void tf_prefill_attention::pattn_kernel<256, 8, 2, 2>(const __nv_bfloat16*, + const __nv_bfloat16*, const __nv_bfloat16*, __nv_bfloat16*, int, int, int, int, int, float); +// The same over an fp8 cache (--kv-cache fp8). +template __global__ void tf_prefill_attention::pattn8_kernel<256, 8, 2, 2>(const __nv_bfloat16*, const uint8_t*, + const uint8_t*, const float*, const float*, __nv_bfloat16*, int, int, int, int, int, float); diff --git a/zig/kernels/cuda/qmm_group.cu b/zig/kernels/cuda/qmm_group.cu index f3f65e184f..9c97ddfa71 100644 --- a/zig/kernels/cuda/qmm_group.cu +++ b/zig/kernels/cuda/qmm_group.cu @@ -339,3 +339,10 @@ __global__ void __launch_bounds__(WM * WN * 32) group_kernel( // The instantiations Nemotron's windows launch on sm_121 (tile 2: rows <= 16, bf16 out). template __global__ void tf_qmm_group::group_kernel<64, 16, 64, 1, 4, 8, false, false, false, false>( const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); +// Tiles 3-5 (rows <= 32, <= 64, more), which a GB10 takes for wider verify rounds; tiles never change bits. +template __global__ void tf_qmm_group::group_kernel<64, 32, 64, 1, 4, 4, false, false, false, false>( + const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); +template __global__ void tf_qmm_group::group_kernel<64, 64, 64, 1, 4, 4, false, false, false, false>( + const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); +template __global__ void tf_qmm_group::group_kernel<64, 64, 128, 2, 4, 3, false, false, false, false>( + const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); diff --git a/zig/kernels/cuda/qmm_prefill.cu b/zig/kernels/cuda/qmm_prefill.cu index 1610b22704..b90d3eb2af 100644 --- a/zig/kernels/cuda/qmm_prefill.cu +++ b/zig/kernels/cuda/qmm_prefill.cu @@ -151,3 +151,7 @@ __global__ void __launch_bounds__(WM * WN * 32) prefill_kernel( template __global__ void tf_qmm_prefill::prefill_kernel<64, 128, 128, 2, 4, 3, false>( const __nv_bfloat16*, const uint32_t*, const __nv_bfloat16*, const __nv_bfloat16*, void*, int, int, int, int, int, int); +// prompt_tile 9 (the 27B's: 128x128 on 2x2 warps, 2 stages, two blocks an SM on a GB10), bf16 out. +template __global__ void tf_qmm_prefill::prefill_kernel<64, 128, 128, 2, 2, 2, false>( + const __nv_bfloat16*, const uint32_t*, const __nv_bfloat16*, const __nv_bfloat16*, void*, int, int, int, + int, int, int); diff --git a/zig/kernels/cuda/qwen_ops.cu b/zig/kernels/cuda/qwen_ops.cu new file mode 100644 index 0000000000..2c57e4355d --- /dev/null +++ b/zig/kernels/cuda/qwen_ops.cu @@ -0,0 +1,107 @@ +// The 27B's own small kernels: batched state copies, the drafter's taps and its fp32 RMSNorm. +#include +#include +#include + +struct TfCopy { + unsigned long long dst, src, bytes; // 16-byte aligned pointers, bytes a multiple of 16 +}; + +// One block an item, its threads striding through the item's 16-byte words. +extern "C" __global__ void __launch_bounds__(256) tf_copy_batch(const TfCopy* __restrict__ items) { + const TfCopy it = items[blockIdx.x]; + const uint4* src = reinterpret_cast(it.src); + uint4* dst = reinterpret_cast(it.dst); + const unsigned long long n = it.bytes / 16; + for (unsigned long long i = threadIdx.x + static_cast(blockIdx.y) * blockDim.x; i < n; + i += static_cast(blockDim.x) * gridDim.y) + dst[i] = src[i]; +} + +struct TfQuant { + unsigned long long src, dst, scale; // bf16 rows of 256, their e4m3 rows, one fp32 scale a row + unsigned long long rows; +}; + +// --kv-cache fp8: each 256-wide row as e4m3 of x * (448 / amax), scale amax / 448 (1 for zeros), as attention_kv8.py +extern "C" __global__ void __launch_bounds__(256) tf_kv_quant(const TfQuant* __restrict__ items) { + // a warp a row, eight rows a block, items on y + const TfQuant it = items[blockIdx.y]; + const unsigned long long row = static_cast(blockIdx.x) * 8 + threadIdx.x / 32; + if (row >= it.rows) return; + const int lane = threadIdx.x % 32; + const uint4 w = reinterpret_cast(it.src)[row * 32 + lane]; + const __nv_bfloat162* h = reinterpret_cast(&w); + float x[8]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const float2 f = __bfloat1622float2(h[i]); + x[2 * i] = f.x; + x[2 * i + 1] = f.y; + } + float amax = 0.0f; +#pragma unroll + for (int i = 0; i < 8; ++i) amax = fmaxf(amax, fabsf(x[i])); +#pragma unroll + for (int o = 16; o > 0; o /= 2) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); + const float s = amax > 0.0f ? __fdiv_rn(amax, 448.0f) : 1.0f; + const float inv = amax > 0.0f ? __fdiv_rn(448.0f, amax) : 1.0f; + uint2 out; + __nv_fp8x2_storage_t* q = reinterpret_cast<__nv_fp8x2_storage_t*>(&out); +#pragma unroll + for (int i = 0; i < 4; ++i) + q[i] = __nv_cvt_float2_to_fp8x2(make_float2(__fmul_rn(x[2 * i], inv), __fmul_rn(x[2 * i + 1], inv)), + __NV_SATFINITE, __NV_E4M3); + reinterpret_cast(it.dst)[row * 32 + lane] = out; + if (lane == 0) reinterpret_cast(it.scale)[row] = s; +} + +// forward.tree_forward's taps: (x.float() + pending.float()).to(bfloat16), row r into columns [col, col + D) of OUT. +extern "C" __global__ void __launch_bounds__(256) tf_tap(const __nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ pending, + __nv_bfloat16* __restrict__ out, int D, int out_stride, int col) { + const long long row = blockIdx.x; + for (int i = threadIdx.x + blockIdx.y * blockDim.x; i < D; i += blockDim.x * gridDim.y) + out[row * out_stride + col + i] = + __float2bfloat16_rn(__bfloat162float(x[row * D + i]) + __bfloat162float(pending[row * D + i])); +} + +// The drafter's RMSNorm in fp32: y = bf16(x * rsqrt(mean(x^2) + eps) * w), a 256-thread block a row. +extern "C" __global__ void __launch_bounds__(256) tf_rms_norm(const __nv_bfloat16* __restrict__ x, int x_stride, + const __nv_bfloat16* __restrict__ w, + __nv_bfloat16* __restrict__ y, int D, float eps) { + __shared__ float part[8]; + const long long row = blockIdx.x; + const __nv_bfloat16* xr = x + row * x_stride; + float s = 0.0f; + for (int i = threadIdx.x; i < D; i += 256) { + const float v = __bfloat162float(xr[i]); + s += v * v; + } + for (int off = 16; off > 0; off >>= 1) s += __shfl_xor_sync(0xFFFFFFFFu, s, off); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = s; + __syncthreads(); + float total = 0.0f; + for (int k = 0; k < 8; ++k) total += part[k]; + const float inv = rsqrtf(total / D + eps); + for (int i = threadIdx.x; i < D; i += 256) + y[row * D + i] = __float2bfloat16_rn(__bfloat162float(xr[i]) * inv * __bfloat162float(w[i])); +} + +// The drafter's inverse frequencies as dflash2 makes them on the GPU: 1 / theta ** (2i / dim), fp32 powf then a divide. +extern "C" __global__ void tf_inv_freq(float* __restrict__ inv, float theta, int half, int dim) { + const int i = threadIdx.x; + if (i < half) inv[i] = 1.0f / powf(theta, static_cast(i) * 2.0f / static_cast(dim)); +} + +// dflash2._rotary and add_taps_streams' tables: cos and sin of float(position) * inv_freq, fp32, a block a row. +extern "C" __global__ void tf_rotary(const int* __restrict__ pos, const float* __restrict__ inv, + float* __restrict__ cos_out, float* __restrict__ sin_out, int half) { + const int row = blockIdx.x; + const float p = static_cast(pos[row]); + for (int i = threadIdx.x; i < half; i += blockDim.x) { + const float phase = p * inv[i]; + cos_out[row * half + i] = cosf(phase); + sin_out[row * half + i] = sinf(phase); + } +} diff --git a/zig/kernels/cuda/qwen_vision.cu b/zig/kernels/cuda/qwen_vision.cu new file mode 100644 index 0000000000..4163d5306c --- /dev/null +++ b/zig/kernels/cuda/qwen_vision.cu @@ -0,0 +1,245 @@ +// Qwen3.5 vision tower kernels (0.6.6's --vision in bf16); epilogues add the bias to cuBLASLt's fp32, round once. +#include +#include + +__device__ __forceinline__ float bf(__nv_bfloat16 v) { return __bfloat162float(v); } +__device__ __forceinline__ float rnd(float v) { return __bfloat162float(__float2bfloat16_rn(v)); } + +// Patch embedding plus the resampled position grid: x = bf16(acc + b) + bf16(sum_t pos[idx_t] * w_t). +extern "C" __global__ void __launch_bounds__(256) tf_qv_embed(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + const __nv_bfloat16* __restrict__ pos, + const int* __restrict__ idx, + const float* __restrict__ wts, + __nv_bfloat16* __restrict__ out, int D) { + const long long row = blockIdx.x; + const int* ri = idx + row * 4; + const float* rw = wts + row * 4; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float h = rnd(acc[row * D + i] + bf(bias[i])); + float p = 0.0f; + for (int t = 0; t < 4; ++t) p += bf(pos[(long long)ri[t] * D + i]) * rw[t]; + out[row * D + i] = __float2bfloat16_rn(h + rnd(p)); + } +} + +// LayerNorm of bf16 rows in fp32 (mean, then the biased variance about it), bf16 out; a block a row. +extern "C" __global__ void __launch_bounds__(256) tf_qv_layernorm(const __nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ w, + const __nv_bfloat16* __restrict__ b, + __nv_bfloat16* __restrict__ y, int D, float eps) { + __shared__ float part[32]; + __shared__ float stat; + const long long row = blockIdx.x; + const __nv_bfloat16* xr = x + row * D; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5, warps = blockDim.x >> 5; + float s = 0.0f; + for (int i = threadIdx.x; i < D; i += blockDim.x) s += bf(xr[i]); + for (int o = 16; o; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if (lane == 0) part[warp] = s; + __syncthreads(); + if (threadIdx.x == 0) { + float t = 0.0f; + for (int i = 0; i < warps; ++i) t += part[i]; + stat = t / D; + } + __syncthreads(); + const float mean = stat; + float v = 0.0f; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float d = bf(xr[i]) - mean; + v += d * d; + } + for (int o = 16; o; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + __syncthreads(); + if (lane == 0) part[warp] = v; + __syncthreads(); + if (threadIdx.x == 0) { + float t = 0.0f; + for (int i = 0; i < warps; ++i) t += part[i]; + stat = rsqrtf(t / D + eps); + } + __syncthreads(); + const float r = stat; + for (int i = threadIdx.x; i < D; i += blockDim.x) + y[row * D + i] = __float2bfloat16_rn((bf(xr[i]) - mean) * r * bf(w[i]) + bf(b[i])); +} + +// qkv = bf16(acc + b) split into q, k, v [heads][rows][hd]; q and k get the axial 2-D rotary in fp32 (h, then w). +extern "C" __global__ void __launch_bounds__(128) tf_qv_qkv_rope(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + const int* __restrict__ hw, + const float* __restrict__ inv, + __nv_bfloat16* __restrict__ q, + __nv_bfloat16* __restrict__ k, + __nv_bfloat16* __restrict__ v, int rows, int heads, + int hd) { + const long long row = blockIdx.x; + const int head = blockIdx.y; + const int D = heads * hd; + const int half = hd / 2, quarter = hd / 4; + const float ph = static_cast(hw[row * 2]), pw = static_cast(hw[row * 2 + 1]); + const float* a = acc + row * 3 * D; + const long long o = (static_cast(head) * rows + row) * hd; + for (int j = threadIdx.x; j < hd; j += blockDim.x) { + const int c = head * hd + j; + // rotate_half pairs j with j +- hd/2; angle h * inv[jj] for the first quarter's frequencies, w * inv after + const int pj = j < half ? j + half : j - half; + const int pc = head * hd + pj; + const int jj = j % half; + const float ang = jj < quarter ? ph * inv[jj] : pw * inv[jj - quarter]; + const float cs = cosf(ang), sn = sinf(ang); + const float sign = j < half ? -1.0f : 1.0f; + const float qx = rnd(a[c] + bf(bias[c])), qp = rnd(a[pc] + bf(bias[pc])); + const float kx = rnd(a[D + c] + bf(bias[D + c])), kp = rnd(a[D + pc] + bf(bias[D + pc])); + q[o + j] = __float2bfloat16_rn(qx * cs + sign * qp * sn); + k[o + j] = __float2bfloat16_rn(kx * cs + sign * kp * sn); + v[o + j] = __float2bfloat16_rn(a[2 * D + c] + bf(bias[2 * D + c])); + } +} + +// Attention within one image's rows [s0, s0 + n); a thread a query row, online softmax in fp32, 64-row key tiles. +template +__device__ void qv_attention(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, + const __nv_bfloat16* __restrict__ v, __nv_bfloat16* __restrict__ out, int rows, + int heads, int s0, int n, float scale) { + constexpr int T = 64; + __shared__ float ks[T][HD]; + __shared__ float vs[T][HD]; + const int head = blockIdx.y; + const int qi = blockIdx.x * T + threadIdx.x; + const bool live = qi < n; + const long long base = static_cast(head) * rows + s0; + float qr[HD], acc[HD]; + float m = -INFINITY, l = 0.0f; + if (live) { + const __nv_bfloat16* qp = q + (base + qi) * HD; + for (int d = 0; d < HD; ++d) { + qr[d] = bf(qp[d]) * scale; + acc[d] = 0.0f; + } + } + for (int t0 = 0; t0 < n; t0 += T) { + const int count = min(T, n - t0); + __syncthreads(); + for (int i = threadIdx.x; i < count * HD; i += blockDim.x) { + const int r = i / HD, d = i % HD; + ks[r][d] = bf(k[(base + t0 + r) * HD + d]); + vs[r][d] = bf(v[(base + t0 + r) * HD + d]); + } + __syncthreads(); + if (!live) continue; + for (int r = 0; r < count; ++r) { + float s = 0.0f; +#pragma unroll + for (int d = 0; d < HD; ++d) s += qr[d] * ks[r][d]; + const float mn = fmaxf(m, s); + const float corr = __expf(m - mn); + const float p = __expf(s - mn); + l = l * corr + p; +#pragma unroll + for (int d = 0; d < HD; ++d) acc[d] = acc[d] * corr + p * vs[r][d]; + m = mn; + } + } + if (!live) return; + const float il = 1.0f / l; + __nv_bfloat16* op = out + static_cast(s0 + qi) * heads * HD + head * HD; + for (int d = 0; d < HD; ++d) op[d] = __float2bfloat16_rn(acc[d] * il); +} + +extern "C" __global__ void __launch_bounds__(64) tf_qv_attention72(const __nv_bfloat16* __restrict__ q, + const __nv_bfloat16* __restrict__ k, + const __nv_bfloat16* __restrict__ v, + __nv_bfloat16* __restrict__ out, int rows, + int heads, int s0, int n, float scale) { + qv_attention<72>(q, k, v, out, rows, heads, s0, n, scale); +} + +// y = gelu(bf16(acc + b)), the tanh form (gelu_pytorch_tanh) or the erf form (nn.GELU), computed in fp32, bf16 out. +extern "C" __global__ void __launch_bounds__(256) tf_qv_bias_gelu(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + __nv_bfloat16* __restrict__ y, int D, int tanh_form) { + const long long row = blockIdx.x; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float x = rnd(acc[row * D + i] + bf(bias[i])); + float g; + if (tanh_form) { + const float kBeta = 0.7978845608028654f; // sqrt(2 / pi) + g = 0.5f * x * (1.0f + tanhf(kBeta * (x + 0.044715f * x * x * x))); + } else { + g = 0.5f * x * (1.0f + erff(x * 0.7071067811865476f)); + } + y[row * D + i] = __float2bfloat16_rn(g); + } +} + +// x += bf16(acc + b), the residual add in bf16 (both operands bf16, the sum rounded). +extern "C" __global__ void __launch_bounds__(256) tf_qv_bias_residual(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + __nv_bfloat16* __restrict__ x, int D) { + const long long row = blockIdx.x; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float y = rnd(acc[row * D + i] + bf(bias[i])); + x[row * D + i] = __float2bfloat16_rn(bf(x[row * D + i]) + y); + } +} + +// y = bf16(acc + b): the merger's last Linear. +extern "C" __global__ void __launch_bounds__(256) tf_qv_bias_cast(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + __nv_bfloat16* __restrict__ y, int D) { + const long long row = blockIdx.x; + for (int i = threadIdx.x; i < D; i += blockDim.x) y[row * D + i] = __float2bfloat16_rn(acc[row * D + i] + bf(bias[i])); +} + +// Image rows into a prompt chunk's embeddings: row r of `x` (stride D) takes feature row src[r] where src[r] >= 0. +extern "C" __global__ void __launch_bounds__(256) tf_qv_splice(__nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ features, + const int* __restrict__ src, int D) { + const long long row = blockIdx.x; + const int s = src[row]; + if (s < 0) return; + for (int i = threadIdx.x; i < D; i += blockDim.x) x[row * D + i] = features[static_cast(s) * D + i]; +} + +// glue._attn_prep with MROPE: q or k RMS-normed to bf16, then rotate-half by t, h or w position; a block a (row, head). +extern "C" __global__ void __launch_bounds__(256) tf_qv_attn_prep_mrope( + const __nv_bfloat16* __restrict__ qg, const __nv_bfloat16* __restrict__ kv, const __nv_bfloat16* __restrict__ qn, + const __nv_bfloat16* __restrict__ kn, const int* __restrict__ pos, const float* __restrict__ inv, + __nv_bfloat16* __restrict__ qout, __nv_bfloat16* __restrict__ kout, float eps, int H, int HKV, int D, int HALF, + int rows, int hsec, int wsec) { + __shared__ float part[8]; + __shared__ float vals[256]; + const int row = blockIdx.x; + const int head = blockIdx.y; + const int d = threadIdx.x; + const bool is_q = head < H; + const __nv_bfloat16* src = is_q ? qg + (static_cast(row) * H + head) * 2 * D + : kv + (static_cast(row) * HKV + head - H) * D; + const __nv_bfloat16* wn = is_q ? qn : kn; + const float x = bf(src[d]); + float s = x * x; + for (int o = 16; o; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if ((d & 31) == 0) part[d >> 5] = s; + __syncthreads(); + float tot = 0.0f; + for (int i = 0; i < (D >> 5); ++i) tot += part[i]; + const float r = 1.0f / sqrtf(tot / D + eps); + const float xn = rnd(x * r * bf(wn[d])); + vals[d] = xn; + __syncthreads(); + float out = xn; + if (d < 2 * HALF) { + const int i = d < HALF ? d : d - HALF; + // Qwen's interleaved sections: axis 1 where i % 3 == 1 and i < 3 * hsec, 2 where i % 3 == 2 and i < 3 * wsec + const int axis = (i % 3 == 1 && i < 3 * hsec) ? 1 : ((i % 3 == 2 && i < 3 * wsec) ? 2 : 0); + const float ang = static_cast(pos[axis * rows + row]) * inv[i]; + const float cs = cosf(ang), sn = sinf(ang); + const float xp = vals[d < HALF ? d + HALF : d - HALF]; + out = d < HALF ? xn * cs - xp * sn : xn * cs + xp * sn; + } + __nv_bfloat16* dst = is_q ? qout + (static_cast(row) * H + head) * D + : kout + (static_cast(row) * HKV + head - H) * D; + dst[d] = __float2bfloat16_rn(out); +} diff --git a/zig/kernels/metal/glm_vision.metal b/zig/kernels/metal/glm_vision.metal new file mode 100644 index 0000000000..cf79f43b03 --- /dev/null +++ b/zig/kernels/metal/glm_vision.metal @@ -0,0 +1,225 @@ +// GLM-5.3-Flash's image tower, MLX's per-op bf16 arithmetic as mlx-vlm runs it; needs prefill/gemm_nax.metal first. + +// ---- the projections and attention products: tfp::gemm_nax (bm64 bn128 bk256 wm2 wn4) by operand layout ---- +#define GLMV_GEMM(NAME, T, TA, TB, AM, AN) \ + [[max_total_threads_per_threadgroup(256)]] [[kernel]] void NAME( \ + const device T* A [[buffer(0)]], const device T* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], \ + device T* D [[buffer(3)]], uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ + tfp::gemm_nax(A, B, D, P, tg, sg, lane); \ + } +// x [M, K] w^T: every linear layer (bf16 in and out, fp32 sums) +GLMV_GEMM(glmv_gemm_bf16_nt_00, bfloat16_t, false, true, false, false) +GLMV_GEMM(glmv_gemm_bf16_nt_01, bfloat16_t, false, true, false, true) +GLMV_GEMM(glmv_gemm_bf16_nt_10, bfloat16_t, false, true, true, false) +GLMV_GEMM(glmv_gemm_bf16_nt_11, bfloat16_t, false, true, true, true) +// q k^T per head in fp32 (the scores MLX's attention keeps in fp32) +GLMV_GEMM(glmv_gemm_f32_nt_00, float, false, true, false, false) +GLMV_GEMM(glmv_gemm_f32_nt_01, float, false, true, false, true) +GLMV_GEMM(glmv_gemm_f32_nt_10, float, false, true, true, false) +GLMV_GEMM(glmv_gemm_f32_nt_11, float, false, true, true, true) +// p v per head in fp32 +GLMV_GEMM(glmv_gemm_f32_nn_00, float, false, false, false, false) +GLMV_GEMM(glmv_gemm_f32_nn_01, float, false, false, false, true) +GLMV_GEMM(glmv_gemm_f32_nn_10, float, false, false, true, false) +GLMV_GEMM(glmv_gemm_f32_nn_11, float, false, false, true, true) + +struct GlmvRows { + uint rows; + uint width; + float eps; +}; + +inline float glmv_bf(float x) { return float(bfloat(x)); } + +// One threadgroup's sum of every thread's `v` (at most 1024 threads), returned to all of them. +inline float glmv_group_sum(float v, threadgroup float* part, uint t, uint n, uint lane, uint sg) { + v = simd_sum(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float s = lane < (n + 31) / 32 ? part[lane] : 0.0f; + s = simd_sum(s); + if (lane == 0) part[32] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float out = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return out; +} + +// y[r, c] = y + b[c] (a linear layer's bias, added after its product as nn.Linear's bf16 add rounds it) +[[kernel]] void glmv_bias(device bfloat* y [[buffer(0)]], const device bfloat* b [[buffer(1)]], + constant uint& width [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { + const ulong i = ulong(at.y) * width + at.x; + y[i] = bfloat(float(y[i]) + float(b[at.x])); +} + +// x += y (a block's residual) +[[kernel]] void glmv_add(device bfloat* x [[buffer(0)]], const device bfloat* y [[buffer(1)]], + uint i [[thread_position_in_grid]]) { + x[i] = bfloat(float(x[i]) + float(y[i])); +} + +// mx.fast.rms_norm, one threadgroup a row: w * bf16(x * rsqrt(mean(x^2) + eps)) +[[kernel]] void glmv_rms(const device bfloat* x [[buffer(0)]], const device bfloat* w [[buffer(1)]], + device bfloat* y [[buffer(2)]], constant GlmvRows& p [[buffer(3)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]], + uint n [[threads_per_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device bfloat* xr = x + ulong(row) * p.width; + device bfloat* yr = y + ulong(row) * p.width; + float s = 0.0f; + for (uint i = t; i < p.width; i += n) { + const float v = float(xr[i]); + s += v * v; + } + s = glmv_group_sum(s, part, t, n, lane, sg); + const float inv = metal::precise::rsqrt(s / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) yr[i] = bfloat(float(w[i]) * glmv_bf(float(xr[i]) * inv)); +} + +// mx.fast.layer_norm with weight and bias, one threadgroup a row: w * bf16((x - mean) * rsqrt(var + eps)) + b +[[kernel]] void glmv_layer_norm(const device bfloat* x [[buffer(0)]], const device bfloat* w [[buffer(1)]], + const device bfloat* b [[buffer(2)]], device bfloat* y [[buffer(3)]], + constant GlmvRows& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device bfloat* xr = x + ulong(row) * p.width; + device bfloat* yr = y + ulong(row) * p.width; + float s = 0.0f; + for (uint i = t; i < p.width; i += n) s += float(xr[i]); + const float mean = glmv_group_sum(s, part, t, n, lane, sg) / float(p.width); + float v = 0.0f; + for (uint i = t; i < p.width; i += n) { + const float d = float(xr[i]) - mean; + v += d * d; + } + const float inv = metal::precise::rsqrt(glmv_group_sum(v, part, t, n, lane, sg) / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) { + yr[i] = bfloat(glmv_bf(float(w[i]) * glmv_bf((float(xr[i]) - mean) * inv)) + float(b[i])); + } +} + +struct GlmvQkv { + uint L; // rows (patches) of this image + float eps; // the q and k norms' +}; + +// A simdgroup a (row, head, q|k|v) of qkv [L, 3, 16, 64]: q and k RMS-normed and 2-D rotated; out head-major fp32. +[[kernel]] void glmv_qkv(const device bfloat* qkv [[buffer(0)]], const device bfloat* qn [[buffer(1)]], + const device bfloat* kn [[buffer(2)]], const device float* cs [[buffer(3)]], + const device float* sn [[buffer(4)]], device float* Q [[buffer(5)]], + device float* K [[buffer(6)]], device float* V [[buffer(7)]], + constant GlmvQkv& p [[buffer(8)]], uint g [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint which = g % 3, h = (g / 3) % 16, r = g / 48; + const device bfloat* src = qkv + ulong(r) * 3072 + which * 1024 + h * 64; + const ulong out = (ulong(h) * p.L + r) * 64; + const float a = float(src[lane]), b = float(src[lane + 32]); + if (which == 2) { + V[out + lane] = a; + V[out + lane + 32] = b; + return; + } + const device bfloat* w = which == 0 ? qn : kn; + const float inv = metal::precise::rsqrt(simd_sum(a * a + b * b) / 64.0f + p.eps); + const float na = glmv_bf(float(w[lane]) * glmv_bf(a * inv)); + const float nb = glmv_bf(float(w[lane + 32]) * glmv_bf(b * inv)); + // cos and sin [L, 64]: the height's 16 frequencies, then the width's, twice + const device float* c = cs + ulong(r) * 64; + const device float* s = sn + ulong(r) * 64; + device float* dst = which == 0 ? Q : K; + dst[out + lane] = glmv_bf(na * c[lane] - nb * s[lane]); + dst[out + lane + 32] = glmv_bf(nb * c[lane + 32] + na * s[lane + 32]); +} + +// Each row of S [rows, n] (fp32 scores) as softmax(scale * s), in place; one threadgroup a row. +[[kernel]] void glmv_softmax(device float* S [[buffer(0)]], constant uint& n [[buffer(1)]], + constant float& scale [[buffer(2)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint tn [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + device float* s = S + ulong(row) * n; + float m = -INFINITY; + for (uint i = t; i < n; i += tn) m = max(m, s[i] * scale); + m = simd_max(m); + if (lane == 0) part[sg] = m; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float v = lane < (tn + 31) / 32 ? part[lane] : -INFINITY; + v = simd_max(v); + if (lane == 0) part[32] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + m = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float z = 0.0f; + for (uint i = t; i < n; i += tn) { + const float e = metal::precise::exp(s[i] * scale - m); + s[i] = e; + z += e; + } + const float inv = 1.0f / glmv_group_sum(z, part, t, tn, lane, sg); + for (uint i = t; i < n; i += tn) s[i] *= inv; +} + +// O [16, rows, 64] (fp32, one chunk's attention) into rows [r0, r0 + rows) of out [L, 1024] (bf16, heads side by side) +[[kernel]] void glmv_heads(const device float* O [[buffer(0)]], device bfloat* out [[buffer(1)]], + constant uint2& p [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { + const uint rows = p.x, r0 = p.y, h = at.x / 64, d = at.x % 64, r = at.y; + out[ulong(r0 + r) * 1024 + at.x] = bfloat(O[(ulong(h) * rows + r) * 64 + d]); +} + +// The vision MLP's and merger's gate: silu(min(g, limit)) * clip(u, -limit, limit), each op rounded as MLX does. +[[kernel]] void glmv_swiglu(const device bfloat* g [[buffer(0)]], const device bfloat* u [[buffer(1)]], + device bfloat* act [[buffer(2)]], constant float& limit [[buffer(3)]], + uint i [[thread_position_in_grid]]) { + const float gate = glmv_bf(min(float(g[i]), limit)); + const float up = glmv_bf(clamp(float(u[i]), -limit, limit)); + const float sig = glmv_bf(1.0f / (1.0f + metal::precise::exp(-gate))); + act[i] = bfloat(glmv_bf(gate * sig) * up); +} + +// erf to fp32 precision (W. J. Cody's rational approximations, as libm's erff). +inline float glmv_erf(float x) { + const float ax = fabs(x); + if (ax < 0.84375f) { + const float z = x * x; + const float r = 1.28379167e-01f + z * (-3.25042108e-01f + z * (-2.84817495e-02f + z * (-5.77027029e-03f + z * -2.37630166e-05f))); + const float s = 1.0f + z * (3.97917233e-01f + z * (6.50222499e-02f + z * (5.08130628e-03f + z * (1.32494738e-04f + z * -3.96022827e-06f)))); + return x + x * (r / s); + } + if (ax < 1.25f) { + const float s = ax - 1.0f; + const float P = -2.36211857e-03f + s * (4.14856106e-01f + s * (-3.72207481e-01f + s * (3.18346620e-01f + s * (-1.10894694e-01f + s * (3.54783031e-02f + s * -2.16637559e-03f))))); + const float Q = 1.0f + s * (1.06420882e-01f + s * (5.40397942e-01f + s * (7.18286547e-02f + s * (1.26171216e-01f + s * (1.36370836e-02f + s * 1.19844998e-02f))))); + const float e = 8.45062911e-01f + P / Q; + return x >= 0 ? e : -e; + } + if (ax >= 6.0f) return x >= 0 ? 1.0f : -1.0f; + const float s = 1.0f / (ax * ax); + float R, S; + if (ax < 1.0f / 0.35f) { + R = -9.86494403e-03f + s * (-6.93858570e-01f + s * (-1.05586262e+01f + s * (-6.23753357e+01f + s * (-1.62396660e+02f + s * (-1.84605087e+02f + s * (-8.12874374e+01f + s * -9.81432934e+00f)))))); + S = 1.0f + s * (1.96512714e+01f + s * (1.37657754e+02f + s * (4.34565887e+02f + s * (6.45387268e+02f + s * (4.29008148e+02f + s * (1.08635002e+02f + s * (6.57024977e+00f + s * -6.04244141e-02f))))))); + } else { + R = -9.86494310e-03f + s * (-7.99283242e-01f + s * (-1.77579556e+01f + s * (-1.60636383e+02f + s * (-6.37566467e+02f + s * (-1.02509509e+03f + s * -4.83519196e+02f))))); + S = 1.0f + s * (3.03380604e+01f + s * (3.25792511e+02f + s * (1.53672961e+03f + s * (3.19985820e+03f + s * (2.55305029e+03f + s * (4.74528534e+02f + s * -2.24409515e+01f)))))); + } + const float zh = as_type(as_type(ax) & 0xfffff000u); + const float r = metal::precise::exp(-zh * zh - 0.5625f) * metal::precise::exp((zh - ax) * (zh + ax) + R / S); + const float e = 1.0f - r / ax; + return x >= 0 ? e : -e; +} + +// nn.gelu (exact): x * (1 + erf(x / sqrt(2))) / 2, each op rounded to bf16 as the compiled MLX graph does +[[kernel]] void glmv_gelu(device bfloat* x [[buffer(0)]], uint i [[thread_position_in_grid]]) { + const float v = float(x[i]); + const float t = glmv_bf(v / 1.41421356237309504880f); + const float e = glmv_bf(glmv_erf(t)); + const float w = glmv_bf(v * glmv_bf(1.0f + e)); + x[i] = bfloat(w / 2.0f); +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 74d24354e9..015e12383a 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -91,6 +91,8 @@ pub const glm_glue = @embedFile("glm_glue.metal"); pub const glm_rows = @embedFile("glm_rows.metal"); /// GLM-5.3-Flash's latent attention for rows that read every key: 64 heads as one matrix on the tensor units. pub const glm_attn = @embedFile("glm_attn.metal"); +/// GLM-5.3-Flash's image tower: the prefill GEMM template's projections and attention products, then its own steps. +pub const glm_vision = @embedFile("prefill/gemm_nax.metal") ++ @embedFile("glm_vision.metal"); /// A prompt chunk's KDA layer in three passes, appended to the generated kda_rows source (its helpers). pub const glm_kda_prompt = @embedFile("glm_kda_prompt.metal"); /// GLM-5.3-Flash speed-up mode's exchange kernels (families/glm/ep.zig). diff --git a/zig/src/cli/qwen27_cuda.zig b/zig/src/cli/qwen27_cuda.zig new file mode 100644 index 0000000000..a45ee50316 --- /dev/null +++ b/zig/src/cli/qwen27_cuda.zig @@ -0,0 +1,547 @@ +//! tf-qwen27-cuda: the 27B's Zig CUDA engine against the Python engine's capture (prompts.json, results.json). + +const std = @import("std"); +const cuda = @import("cuda"); +const qwen = @import("qwen27"); + +const usage = + \\usage: tf-qwen27-cuda run MODEL --kernels DIR --prompts prompts.json [--expect results.json] + \\ [--max-tokens N] [--context N] [--device N] + \\ Greedy, drafts off: each prompt's tokens and their sha against the capture's. + \\ tf-qwen27-cuda windows MODEL --kernels DIR --prompts windows.json + \\ capture_windows.py's chains and shared rounds: each row's logits against the capture's sha256. + \\ tf-qwen27-cuda draft MODEL --kernels DIR --drafter DIR --prompts prompts.json [--expect draft.json] + \\ draft_decode with DFlash2, greedy: tokens (equal to serial) and rounds against capture_draft.py's. + \\ tf-qwen27-cuda rounds MODEL --kernels DIR --prompts windows.json [--max-tokens ROUNDS] + \\ Greedy shared rounds of one row a stream over every prompt, timed. + \\ tf-qwen27-cuda multi MODEL --kernels DIR --drafter DIR --prompts multi.json + \\ capture_multi.py's drafted shared rounds: each round's windows and every reply against the capture's. + \\ tf-qwen27-cuda kvcompare MODEL --kernels DIR --prompts prompts.json [--max-tokens N] + \\ --kv-cache fp8 against bf16, teacher-forced on bf16's greedy reply: top-1 agreement and KL a token. + \\ tf-qwen27-cuda vision MODEL --fixtures DIR + \\ The image tower on recorded 0.6.6 fixtures' patches: each image's rows against 0.6.6's (cosine, max error). + \\ +; + +const Options = struct { + model: []const u8, + kernels: []const u8 = "", + prompts: []const u8 = "", + expect: ?[]const u8 = null, + max_tokens: usize = 128, + context: usize = 16384, + device: c_int = 0, + dump: ?[]const u8 = null, // windows: a case's per-norm rows into this folder + cases: ?[]const u8 = null, // windows: only these cases, comma separated + drafter: ?[]const u8 = null, // draft: the DFlash2 checkpoint + kv8: bool = false, // --kv-cache fp8: e4m3 attention caches +}; + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + const windows = args.len >= 2 and std.mem.eql(u8, args[1], "windows"); + const rounds = args.len >= 2 and std.mem.eql(u8, args[1], "rounds"); + const drafting = args.len >= 2 and std.mem.eql(u8, args[1], "draft"); + const multi = args.len >= 2 and std.mem.eql(u8, args[1], "multi"); + const kvcompare = args.len >= 2 and std.mem.eql(u8, args[1], "kvcompare"); + if (args.len >= 5 and std.mem.eql(u8, args[1], "vision") and std.mem.eql(u8, args[3], "--fixtures")) + return @import("qwen27_vision_check.zig").checkVision(gpa, arena, init.io, args[2], args[4]); + if (args.len < 3 or !(std.mem.eql(u8, args[1], "run") or windows or rounds or drafting or multi or kvcompare)) { + std.debug.print("{s}", .{usage}); + return 2; + } + var o: Options = .{ .model = args[2] }; + var i: usize = 3; + while (i + 1 < args.len) : (i += 2) { + const k = args[i]; + const v = args[i + 1]; + if (std.mem.eql(u8, k, "--kernels")) o.kernels = v else if (std.mem.eql(u8, k, "--prompts")) o.prompts = v else if (std.mem.eql(u8, k, "--expect")) o.expect = v else if (std.mem.eql(u8, k, "--max-tokens")) o.max_tokens = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--context")) o.context = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--device")) o.device = try std.fmt.parseInt(c_int, v, 10) else if (std.mem.eql(u8, k, "--dump")) o.dump = v else if (std.mem.eql(u8, k, "--cases")) o.cases = v else if (std.mem.eql(u8, k, "--drafter")) o.drafter = v else if (std.mem.eql(u8, k, "--kv-cache")) o.kv8 = std.mem.eql(u8, v, "fp8") else { + std.debug.print("unknown option {s}\n{s}", .{ k, usage }); + return 2; + } + } + if (o.kernels.len == 0 or o.prompts.len == 0) { + std.debug.print("{s}", .{usage}); + return 2; + } + const prompts = try readJson(arena, init.io, o.prompts); + const expect = if (o.expect) |p| try readJson(arena, init.io, p) else null; + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, o.device); + defer ctx.deinit(); + const clock = std.Io.Clock.awake; + var t0 = clock.now(init.io).toNanoseconds(); + const e = try qwen.Engine.init(gpa, init.io, &ctx, o.model, o.kernels, .{ .context = o.context, .kv8 = o.kv8 }); + defer e.deinit(); + try e.fit(16); // the shared rounds' partials: up to 16 streams of the context (windows' are 4096) + std.debug.print("loaded in {d:.1}s, weights {d:.2} GiB\n", .{ @as(f64, @floatFromInt(clock.now(init.io).toNanoseconds() - t0)) / 1e9, @as(f64, @floatFromInt(e.w.bytes())) / (1 << 30) }); + if (windows) return checkWindows(gpa, arena, init.io, e, prompts, o.dump, o.cases); + if (rounds) return benchRounds(gpa, arena, init.io, e, prompts, o.max_tokens); + if (drafting) return runDrafted(gpa, arena, init.io, e, o, prompts, expect); + if (multi) return runMulti(gpa, arena, init.io, e, o, prompts); + if (kvcompare) return compareKv(arena, e, prompts, o.max_tokens); + var seq = try e.sequence(o.context); + defer seq.deinit(); + var mismatches: usize = 0; + var it = prompts.object.iterator(); + while (it.next()) |entry| { + const name = entry.key_ptr.*; + const ids = try tokenList(arena, entry.value_ptr.*); + var out: std.ArrayList(u32) = .empty; + defer out.deinit(gpa); + t0 = clock.now(init.io).toNanoseconds(); + try e.generate(&seq, ids, o.max_tokens, &out); + const seconds = @as(f64, @floatFromInt(clock.now(init.io).toNanoseconds() - t0)) / 1e9; + const sha = try sha12(arena, out.items); + var verdict: []const u8 = ""; + if (expect) |x| blk: { + const want_v = (x.object.get("results") orelse break :blk).object.get(name) orelse break :blk; + const want = try tokenList(arena, want_v.object.get("tokens").?); + const same = std.mem.eql(u32, want, out.items); + if (!same) mismatches += 1; + var first: usize = 0; + while (first < @min(want.len, out.items.len) and want[first] == out.items[first]) first += 1; + verdict = if (same) " MATCH" else try std.fmt.allocPrint(arena, " DIFFER at token {d} (python sha {s})", .{ first, try sha12(arena, want) }); + } + std.debug.print("{s}: prompt {d}, {d} tokens sha {s} in {d:.2}s{s}\n", .{ name, ids.len, out.items.len, sha, seconds, verdict }); + } + return if (mismatches == 0) 0 else 1; +} + +/// The scratch's first logits row as fp64 log-probabilities. +fn logProbs(f: *qwen.Forward, bits: []u16, out: []f64) !void { + try f.ops.download(std.mem.sliceAsBytes(bits), f.s.logits); + try f.ops.s.synchronize(); + var most: f64 = -std.math.inf(f64); + for (bits, out) |b, *x| { + x.* = @floatCast(@as(f32, @bitCast(@as(u32, b) << 16))); + most = @max(most, x.*); + } + var total: f64 = 0; + for (out) |x| total += @exp(x - most); + const log_total = most + @log(total); + for (out) |*x| x.* -= log_total; +} + +fn argmaxOf(x: []const f64) u32 { + var best: usize = 0; + for (x, 0..) |v, i| if (v > x[best]) { + best = i; + }; + return @intCast(best); +} + +/// kvcompare: bf16 and fp8 streams fed bf16's greedy tokens; per step top-1 agreement, KL and bf16's pick's logprob. +fn compareKv(arena: std.mem.Allocator, e: *qwen.Engine, prompts: std.json.Value, steps: usize) !u8 { + const vocab = qwen.config.vocab; + const bits = try arena.alloc(u16, vocab); + const pa = try arena.alloc(f64, vocab); + const pb = try arena.alloc(f64, vocab); + var f = e.forward(); + var it = prompts.object.iterator(); + var all_agree: usize = 0; + var all_n: usize = 0; + while (it.next()) |entry| { + const ids = try tokenList(arena, entry.value_ptr.*); + const cap = ids.len + steps + 16; + e.kv8 = false; + var a = try e.sequence(cap); + defer a.deinit(); + e.kv8 = true; + var b = try e.sequence(cap); + defer b.deinit(); + e.kv8 = false; + var agree: usize = 0; + var kl_sum: f64 = 0; + var kl_most: f64 = 0; + var lp_sum: f64 = 0; + var tok: u32 = 0; + for (0..steps) |step| { + for ([_]*qwen.state.Seq{ &a, &b }, [_][]f64{ pa, pb }) |seq, out| { + if (step == 0) { + try e.prefill(seq, ids); + try f.head(seq); + } else { + const part = [_]qwen.Part{.{ .seq = seq, .tokens = &.{tok} }}; + try f.round(&part); + try f.commit(&part, &.{&.{0}}); + } + try logProbs(&f, bits, out); + } + const top_a = argmaxOf(pa); + if (top_a == argmaxOf(pb)) agree += 1; + var kl: f64 = 0; + for (pa, pb) |x, y| kl += @exp(x) * (x - y); + kl_sum += kl; + kl_most = @max(kl_most, kl); + lp_sum += pa[top_a] - pb[top_a]; + tok = top_a; + } + const n: f64 = @floatFromInt(steps); + std.debug.print("{s}: prompt {d}, {d} steps: top-1 agree {d}/{d}, KL mean {d:.5} max {d:.5} nats, pick logprob gap {d:.5}\n", .{ entry.key_ptr.*, ids.len, steps, agree, steps, kl_sum / n, kl_most, lp_sum / n }); + all_agree += agree; + all_n += steps; + } + std.debug.print("overall top-1 agree {d}/{d}\n", .{ all_agree, all_n }); + return 0; +} + +fn readJson(a: std.mem.Allocator, io: std.Io, path: []const u8) !std.json.Value { + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 30)); + return (try std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{})); +} + +fn tokenList(a: std.mem.Allocator, v: std.json.Value) ![]u32 { + if (v != .array) return error.BadPromptFile; + const out = try a.alloc(u32, v.array.items.len); + for (v.array.items, out) |x, *t| t.* = @intCast(x.integer); + return out; +} + +/// The capture's sha12: sha256 of json.dumps(tokens), "[1, 2, 3]", its first 12 hex digits. +fn sha12(a: std.mem.Allocator, tokens: []const u32) ![]const u8 { + var text: std.ArrayList(u8) = .empty; + try text.append(a, '['); + for (tokens, 0..) |t, i| { + if (i > 0) try text.appendSlice(a, ", "); + try text.print(a, "{d}", .{t}); + } + try text.append(a, ']'); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(text.items, &digest, .{}); + const hex = std.fmt.bytesToHex(digest, .lower); + return a.dupe(u8, hex[0..12]); +} + +/// Each case's streams prefilled afresh, its round run, every row's logits hashed; shared cases commit and go on. +fn checkWindows(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, doc: std.json.Value, dump: ?[]const u8, only: ?[]const u8) !u8 { + const root = doc.object; + const prompts = root.get("prompts").?.array.items; + const cases = root.get("cases").?.array.items; + var bad: usize = 0; + const row_bytes = qwen.config.vocab * 2; + const host = try gpa.alloc(u8, row_bytes); + defer gpa.free(host); + for (cases, 0..) |case, ci| { + if (only) |list| { + var it = std.mem.splitScalar(u8, list, ','); + const listed = while (it.next()) |x| { + if (std.fmt.parseInt(usize, x, 10) catch null == ci) break true; + } else false; + if (!listed) continue; + } + const streams = case.object.get("streams").?.array.items; + std.debug.print("case {d}: {s}, {d} streams\n", .{ ci, case.object.get("kind").?.string, streams.len }); + var seqs: [qwen.state.max_streams]qwen.state.Seq = undefined; + var parts: [qwen.state.max_streams]qwen.Part = undefined; + var made: usize = 0; + defer for (seqs[0..made]) |*sq| sq.deinit(); + for (streams, 0..) |sv, k| { + const sid: usize = @intCast(sv.object.get("stream").?.integer); + const ids = try tokenList(a, prompts[sid]); + seqs[k] = try e.sequence(4096); + made += 1; + try e.prefill(&seqs[k], ids); + parts[k] = .{ .seq = &seqs[k], .tokens = try tokenList(a, sv.object.get("tokens").?) }; + if (sv.object.get("parents")) |pv| { + const ps = try a.alloc(i32, pv.array.items.len); + for (pv.array.items, ps) |x, *y| y.* = @intCast(x.integer); + parts[k].parents = ps; + } + } + const n = streams.len; + var f = e.forward(); + if (dump) |dir| f.dump = .{ .io = io, .dir = dir }; + try f.round(parts[0..n]); + f.dump = null; + bad += try compareRows(&f, host, case.object.get("rows").?.array.items, ci, "rows"); + if (case.object.get("paths")) |paths_v| { + var paths: [qwen.state.max_streams][]const u32 = undefined; + var next: [qwen.state.max_streams]u32 = undefined; + for (paths_v.array.items, 0..) |pv, k| paths[k] = try tokenList(a, pv); + try f.commit(parts[0..n], paths[0..n]); + for (case.object.get("next").?.array.items, 0..) |nv, k| { + next[k] = @intCast(nv.integer); + parts[k].tokens = next[k .. k + 1]; + parts[k].parents = null; + } + try f.round(parts[0..n]); + bad += try compareRows(&f, host, case.object.get("after").?.array.items, ci, "after"); + } + if (case.object.get("keep")) |keep_v| { + var kept: [qwen.state.max_streams]usize = undefined; + var next: [qwen.state.max_streams]u32 = undefined; + const prefix = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + var paths: [qwen.state.max_streams][]const u32 = undefined; + for (keep_v.array.items, 0..) |kv, k| { + kept[k] = @intCast(kv.integer); + paths[k] = prefix[0..kept[k]]; + } + try f.commit(parts[0..n], paths[0..n]); + const reply_rows = doc.object.get("replies").?.array.items; + for (streams, 0..) |sv, k| { + const sid: usize = @intCast(sv.object.get("stream").?.integer); + next[k] = @intCast(reply_rows[sid].array.items[kept[k]].integer); + parts[k].tokens = next[k .. k + 1]; + } + try f.round(parts[0..n]); + bad += try compareRows(&f, host, case.object.get("after").?.array.items, ci, "after"); + } + } + std.debug.print("{d} cases, {d} rows differ\n", .{ cases.len, bad }); + return if (bad == 0) 0 else 1; +} + +fn compareRows(f: *qwen.Forward, host: []u8, want: []const std.json.Value, case: usize, what: []const u8) !usize { + var bad: usize = 0; + for (want, 0..) |rv, r| { + try f.ops.download(host, f.s.logits + r * host.len); + try f.ops.s.synchronize(); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(host, &digest, .{}); + const hex = std.fmt.bytesToHex(digest, .lower); + if (!std.mem.eql(u8, &hex, rv.object.get("sha").?.string)) { + std.debug.print("case {d} {s} row {d}: logits differ\n", .{ case, what, r }); + bad += 1; + } + } + return bad; +} + +/// Every prompt prefilled, then greedy shared rounds of one row a stream; ms a round and tokens a second. +fn benchRounds(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, doc: std.json.Value, count: usize) !u8 { + { + // the served engine's cost curve: the forward's ms by a round's rows + var lanes_ = try qwen.Lanes.init(gpa, e, qwen.state.max_streams); + defer lanes_.deinit(); + try lanes_.calibrate(io, qwen.state.max_streams); + for (lanes_.costs[0..lanes_.cost_count]) |cst| std.debug.print("{d} rows: {d:.2} ms\n", .{ cst.width, cst.ms }); + } + const prompts = doc.object.get("prompts").?.array.items; + const n = @min(prompts.len, qwen.state.max_streams); + var seqs: [qwen.state.max_streams]qwen.state.Seq = undefined; + var parts: [qwen.state.max_streams]qwen.Part = undefined; + var next: [qwen.state.max_streams]u32 = undefined; + var ones: [qwen.state.max_streams][]const u32 = @splat(&.{0}); + var made: usize = 0; + defer for (seqs[0..made]) |*sq| sq.deinit(); + var f = e.forward(); + for (prompts[0..n], 0..) |pv, k| { + seqs[k] = try e.sequence(4096); + made += 1; + try e.prefill(&seqs[k], try tokenList(a, pv)); + try f.head(&seqs[k]); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + next[k] = pick[0]; + } + const clock = std.Io.Clock.awake; + const t0 = clock.now(io).toNanoseconds(); + for (0..count) |_| { + for (0..n) |k| parts[k] = .{ .seq = &seqs[k], .tokens = next[k .. k + 1] }; + try f.round(parts[0..n]); + try f.picks(n, next[0..n]); + try f.commit(parts[0..n], ones[0..n]); + } + try f.ops.s.synchronize(); + const ms = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; + std.debug.print("{d} streams, {d} rounds: {d:.2} ms a round, {d:.1} tok/s\n", .{ n, count, ms / @as(f64, @floatFromInt(count)), @as(f64, @floatFromInt(n * count)) / ms * 1e3 }); + return 0; +} + +/// Each prompt drafted with DFlash2 as capture_draft.py runs it: tokens, rounds and accepted drafts. +fn runDrafted(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, o: Options, prompts: std.json.Value, expect: ?std.json.Value) !u8 { + const clock = std.Io.Clock.awake; + var t0 = clock.now(io).toNanoseconds(); + const f0 = e.forward(); + const d = try qwen.draft.DFlash2.init(gpa, io, f0.ops, f0.t, &e.w, o.drafter orelse return error.NoDrafter, o.model); + defer d.deinit(); + std.debug.print("drafter loaded in {d:.1}s\n", .{@as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9}); + var ctx = try qwen.draft.Context.init(f0.ops.k.d); + defer ctx.deinit(); + var seq = try e.sequence(o.context); + defer seq.deinit(); + var bad: usize = 0; + var it = prompts.object.iterator(); + while (it.next()) |entry| { + const name = entry.key_ptr.*; + const ids = try tokenList(a, entry.value_ptr.*); + var out: std.ArrayList(u32) = .empty; + defer out.deinit(gpa); + var stats: qwen.lone.Stats = .{}; + t0 = clock.now(io).toNanoseconds(); + try qwen.lone.prefill(e, &seq, &ctx, d, ids); + var f = e.forward(); + try f.head(&seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + const t1 = clock.now(io).toNanoseconds(); + try qwen.lone.decode(e, &seq, &ctx, d, ids, pick[0], o.max_tokens, 12, &out, &stats); + const secs = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t1)) / 1e9; + var verdict: []const u8 = ""; + if (expect) |x| blk: { + const want_v = (x.object.get("results") orelse break :blk).object.get(name) orelse break :blk; + const want = try tokenList(a, want_v.object.get("tokens").?); + const same = std.mem.eql(u32, want, out.items); + if (!same) bad += 1; + verdict = try std.fmt.allocPrint(a, " {s}; python rounds {d} accepted {d}", .{ if (same) "MATCH" else "DIFFER", want_v.object.get("rounds").?.integer, want_v.object.get("accepted").?.integer }); + } + std.debug.print("{s}: {d} tokens sha {s}, rounds {d} accepted {d}, {d:.1} tok/s{s}\n", .{ name, out.items.len, try sha12(a, out.items), stats.rounds, stats.accepted, @as(f64, @floatFromInt(out.items.len)) / secs, verdict }); + } + return if (bad == 0) 0 else 1; +} + +/// One stream of the multi check: its state, drafting, context (prompt and reply) and reply. +const MultiStream = struct { + seq: qwen.state.Seq, + d: qwen.drafts.Stream, + context: std.ArrayList(u32) = .empty, + out: std.ArrayList(u32) = .empty, + done: bool = false, + rounds: usize = 0, + accepted: usize = 0, +}; + +/// MultiDecoder's rounds as capture_multi.py runs them (greedy, no costs: whole trees, blocks of 16 rows). +fn runMulti(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, o: Options, doc: std.json.Value) !u8 { + const clock = std.Io.Clock.awake; + const f0 = e.forward(); + const d = try qwen.draft.DFlash2.init(gpa, io, f0.ops, f0.t, &e.w, o.drafter orelse return error.NoDrafter, o.model); + defer d.deinit(); + const prompts = doc.object.get("prompts").?.array.items; + const count: usize = @intCast(doc.object.get("max_tokens").?.integer); + const want_rounds = doc.object.get("rounds").?.array.items; + const S = prompts.len; + const ms = try a.alloc(MultiStream, S); + var made: usize = 0; + defer for (ms[0..made]) |*m| { + m.seq.deinit(); + m.d.deinit(); + m.context.deinit(gpa); + m.out.deinit(gpa); + }; + for (prompts, ms) |pv, *m| { + const ids = try tokenList(a, pv); + m.* = .{ .seq = try e.sequence(o.context), .d = qwen.drafts.Stream.init(gpa, try qwen.draft.Context.init(f0.ops.k.d)) }; + made += 1; + try qwen.lone.prefill(e, &m.seq, &m.d.ctx, d, ids); + var f = e.forward(); + try f.head(&m.seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + try m.context.appendSlice(gpa, ids); + try m.context.append(gpa, pick[0]); + try m.out.append(gpa, pick[0]); + } + var differ: usize = 0; + var round: usize = 0; + const t0 = clock.now(io).toNanoseconds(); + var tokens: [qwen.state.round_rows]u32 = undefined; + var parents: [qwen.state.round_rows]i32 = undefined; + var picks: [qwen.state.round_rows]u32 = undefined; + var path_rows: [qwen.state.round_rows]u32 = undefined; + var kept_rows: [qwen.state.round_rows]u32 = undefined; + while (true) : (round += 1) { + var live: [qwen.state.max_streams]usize = undefined; + var n: usize = 0; + for (ms, 0..) |m, k| if (!m.done) { + live[n] = k; + n += 1; + }; + if (n == 0) break; + var asks: [qwen.state.max_streams]qwen.drafts.Ask = undefined; + for (live[0..n], 0..) |k, j| asks[j] = .{ .x = &ms[k].d, .context = ms[k].context.items, .sampling = null }; + try qwen.drafts.propose(d, asks[0..n]); + // the windows: the pending token, then the drafts (tree parents shifted under it) + var parts: [qwen.state.max_streams]qwen.Part = undefined; + var starts: [qwen.state.max_streams + 1]usize = undefined; + var total: usize = 0; + const want = if (round < want_rounds.len) want_rounds[round].array.items else &.{}; + for (live[0..n], 0..) |k, j| { + const m = &ms[k]; + starts[j] = total; + tokens[total] = m.out.items[m.out.items.len - 1]; + parents[total] = -1; + for (m.d.tokens.items, m.d.parents.items, 1..) |t, p, r| { + tokens[total + r] = t; + parents[total + r] = if (p < 0) 0 else p + 1; + } + const rows = 1 + m.d.tokens.items.len; + parts[j] = .{ .seq = &m.seq, .tokens = tokens[total..][0..rows], .parents = parents[total..][0..rows] }; + if (j < want.len) { + const w = want[j].object; + const wt = try tokenList(a, w.get("tokens").?); + const wp = w.get("parents").?.array.items; + var same = @as(usize, @intCast(w.get("stream").?.integer)) == k and std.mem.eql(u32, wt, tokens[total..][0..rows]) and wp.len == rows; + if (same) for (wp, parents[total..][0..rows]) |x, y| { + if (x.integer != y) same = false; + }; + if (!same) { + differ += 1; + if (differ == 1) std.debug.print("round {d} stream {d}: first window that differs from Python's ({s} {d} rows, python {s} {d})\n", .{ round, k, @tagName(m.d.kind), rows, w.get("mode").?.string, wt.len }); + } + } else differ += 1; + total += rows; + } + starts[n] = total; + var f = e.forward(); + f.taps = e.scratch.taps; + try f.round(parts[0..n]); + try f.picks(total, &picks); + var paths: [qwen.state.max_streams][]const u32 = undefined; + var kept: [qwen.state.max_streams]qwen.drafts.Kept = undefined; + for (live[0..n], 0..) |k, j| { + const m = &ms[k]; + const base = starts[j]; + const rows = starts[j + 1] - base; + const room = count - m.out.items.len; + // accept: children equal to their parent's draw, within the room, none past an end token + var len: usize = 1; + path_rows[base] = 0; + var terminal = picks[base]; + while (len < room and !e.w.isEos(terminal)) { + const child = for (1..rows) |r| { + if (parents[base + r] == @as(i32, @intCast(path_rows[base + len - 1])) and tokens[base + r] == terminal) break r; + } else break; + path_rows[base + len] = @intCast(child); + len += 1; + terminal = picks[base + child]; + } + paths[j] = path_rows[base..][0..len]; + for (paths[j], kept_rows[base..][0..len]) |r, *g| g.* = @intCast(base + r); + kept[j] = .{ .x = &m.d, .rows = kept_rows[base..][0..len] }; + for (paths[j][1..]) |r| { + try m.out.append(gpa, tokens[base + r]); + try m.context.append(gpa, tokens[base + r]); + } + try m.out.append(gpa, terminal); + try m.context.append(gpa, terminal); + m.rounds += 1; + m.accepted += len - 1; + } + try f.commit(parts[0..n], paths[0..n]); + try qwen.drafts.absorb(d, f.ops, e.scratch.taps, e.scratch.copy_items, kept[0..n]); + for (live[0..n]) |k| { + const m = &ms[k]; + if (m.out.items.len >= count or e.w.isEos(m.out.items[m.out.items.len - 1])) m.done = true; + } + } + const secs = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9; + if (round != want_rounds.len) differ += 1; + var bad: usize = 0; + var produced: usize = 0; + const results = doc.object.get("results").?.array.items; + for (ms, results, 0..) |m, rv, k| { + const want = try tokenList(a, rv.object.get("tokens").?); + const same = std.mem.eql(u32, want, m.out.items); + if (!same or m.rounds != rv.object.get("rounds").?.integer) bad += 1; + produced += m.out.items.len; + std.debug.print("stream {d}: {d} tokens sha {s} rounds {d} accepted {d} {s}; python rounds {d} accepted {d}\n", .{ k, m.out.items.len, try sha12(a, m.out.items), m.rounds, m.accepted, if (same) "MATCH" else "DIFFER", rv.object.get("rounds").?.integer, rv.object.get("accepted").?.integer }); + } + // replies and every stream's rounds must match; a tree may order its nodes otherwise where drafts round otherwise + std.debug.print("{d} rounds (python {d}), {d} windows differ from Python's, {d} replies differ; {d:.1} tok/s\n", .{ round, want_rounds.len, differ, bad, @as(f64, @floatFromInt(produced)) / secs }); + return if (bad == 0 and round == want_rounds.len) 0 else 1; +} diff --git a/zig/src/cli/qwen27_vision_check.zig b/zig/src/cli/qwen27_vision_check.zig new file mode 100644 index 0000000000..cbedfc6859 --- /dev/null +++ b/zig/src/cli/qwen27_vision_check.zig @@ -0,0 +1,95 @@ +//! `tf-qwen27-cuda vision`: the vision tower, image decode and patches against a manifest recorded from 0.6.6. +const std = @import("std"); +const cuda = @import("cuda"); +const qwen = @import("qwen27"); + +/// The tower against a 0.6.6 manifest recorded outside the tree: per image, the row cosines and largest error. +pub fn checkVision(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: std.Io, model: []const u8, dir: []const u8) !u8 { + const V = qwen.vision; + const manifest = try readJson(arena, io, try std.fs.path.join(arena, &.{ dir, "manifest.json" })); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const gpu: V.Gpu = .{ .d = &driver, .s = stream, .discrete = try ctx.attribute(.integrated) == 0 }; + const clock = std.Io.Clock.awake; + var t0 = clock.now(io).toNanoseconds(); + const tower = try V.Tower.load(gpa, io, gpu, model); + defer tower.deinit(); + std.debug.print("tower loaded in {d:.1}s, {d:.2} GiB\n", .{ @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9, @as(f64, @floatFromInt(tower.weight_bytes)) / (1 << 30) }); + var worst: f64 = 1; + for (manifest.object.get("images").?.array.items) |img| { + const name = img.object.get("name").?.string; + const grid = img.object.get("grid").?.array.items; + const g: V.Grid = .{ .h = @intCast(grid[0].integer), .w = @intCast(grid[1].integer) }; + const px_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("pixels").?.string }), arena, .limited(1 << 30)); + const want_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("features").?.string }), arena, .limited(1 << 30)); + const px = try arena.alloc(f32, px_bytes.len / 4); + @memcpy(std.mem.sliceAsBytes(px), px_bytes[0 .. px.len * 4]); + { // our decode and patches from the image's file, against 0.6.6's + const file = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("file").?.string }), arena, .limited(1 << 30)); + const want_rgb = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("rgb").?.string }), arena, .limited(1 << 30)); + const rgb = try qwen.image.decode(gpa, file); + defer rgb.deinit(gpa); + var px_diff: usize = 0; + if (rgb.px.len == want_rgb.len) { + for (rgb.px, want_rgb) |a, b| px_diff += @intFromBool(a != b); + } else px_diff = std.math.maxInt(usize); + const prep = try qwen.image.prepare(gpa, file, 4096); + defer gpa.free(prep.pixels); + var patch_diff: usize = 0; + if (prep.gh == g.h and prep.gw == g.w and prep.pixels.len == px.len) { + for (prep.pixels, px) |a, b| patch_diff += @intFromBool(@as(u32, @bitCast(a)) != @as(u32, @bitCast(b))); + } else patch_diff = std.math.maxInt(usize); + std.debug.print("{s}: decode {d}x{d}, {d} of {d} bytes differ from PIL's; patches grid {d}x{d}, {d} of {d} values differ\n", .{ name, rgb.w, rgb.h, px_diff, want_rgb.len, prep.gh, prep.gw, patch_diff, px.len }); + } + const rows = @as(usize, g.h) * g.w / 4; + var out = try cuda.DeviceBuffer.alloc(&driver, rows * V.out_hidden * 2); + defer out.free(); + t0 = clock.now(io).toNanoseconds(); + try tower.encode(gpu, px, &.{g}, out.ptr); + const ms = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; + const got = try arena.alloc(u16, rows * V.out_hidden); + try driver.check(driver.api.cuMemcpyDtoH_v2(@ptrCast(got.ptr), out.ptr, got.len * 2), "cuMemcpyDtoH"); + const want: []align(1) const u16 = std.mem.bytesAsSlice(u16, want_bytes); + if (want.len != got.len) { + std.debug.print("{s}: {d} features, 0.6.6 has {d}\n", .{ name, got.len, want.len }); + return 1; + } + var min_cos: f64 = 1; + var sum_cos: f64 = 0; + var max_err: f64 = 0; + var equal: usize = 0; + for (0..rows) |r| { + var dot: f64 = 0; + var na: f64 = 0; + var nb: f64 = 0; + for (0..V.out_hidden) |c| { + const a = bf(got[r * V.out_hidden + c]); + const b = bf(want[r * V.out_hidden + c]); + if (got[r * V.out_hidden + c] == want[r * V.out_hidden + c]) equal += 1; + dot += a * b; + na += a * a; + nb += b * b; + max_err = @max(max_err, @abs(a - b)); + } + const cs = dot / @sqrt(na * nb); + min_cos = @min(min_cos, cs); + sum_cos += cs; + } + worst = @min(worst, min_cos); + std.debug.print("{s}: grid {d}x{d}, {d} rows in {d:.1} ms; row cosine min {d:.5} mean {d:.5}; max error {d:.4}; {d:.1}% values equal\n", .{ name, g.h, g.w, rows, ms, min_cos, sum_cos / @as(f64, @floatFromInt(rows)), max_err, 100 * @as(f64, @floatFromInt(equal)) / @as(f64, @floatFromInt(got.len)) }); + } + return if (worst > 0.98) 0 else 1; +} + +fn bf(v: u16) f64 { + return @as(f32, @bitCast(@as(u32, v) << 16)); +} + +fn readJson(a: std.mem.Allocator, io: std.Io, path: []const u8) !std.json.Value { + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 30)); + return (try std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{})); +} diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 903dc4d40b..2b0915bca4 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -9,6 +9,9 @@ pub const Id = u64; /// One request's sampling (Python's exact_sampling.Sampling); a request without one decodes greedily. pub const Sampling = lanes.Sampling; +/// One image of a request (``Request.images``): the tower's input and the placeholder rows its output replaces. +pub const Image = lanes.stream.Image; + /// A prompt's reproducible seed (``seed_for``), for requests that name none. pub const seedFor = lanes.sampling.seedFor; @@ -88,8 +91,42 @@ pub const Request = struct { logprobs: ?u8 = null, /// Rows for each prompt token after the first, with ranks and this many best tokens, when ``Info.prompt_logprobs``. prompt_logprobs: ?u8 = null, + /// Images whose rows replace placeholder tokens of ``prompt``, in order; only when ``Info.vision`` is set. + images: []const Image = &.{}, + /// The prompt as the prompt cache matches it (each image's placeholders by its content); empty: ``prompt``. + cache_key: []const u32 = &.{}, + + /// The prompt as the prompt cache matches it: an image request's placeholders stand for their images. + pub fn cacheKey(r: *const Request) []const u32 { + return if (r.cache_key.len > 0) r.cache_key else r.prompt; + } + + /// The decoded prompt rows, for a backend that keeps their bits (``decoded_rows``); otherwise none. + pub fn cacheSpans(r: *const Request, decoded_rows: bool) []const [2]u32 { + return if (decoded_rows) r.decode_spans else &.{}; + } }; +/// An image prepared for the engine's tower (``Vision.prepare``): patches, patch grid, tokens and a content hash. +pub const PreparedImage = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + +/// Image input an engine serves (``Info.vision``): image bytes to tower input, and what a request may hold. +pub const Vision = struct { + ctx: *anyopaque, + /// The image's bytes (any format the platform decodes) at most ``max_tokens`` tokens; allocated in ``a``. + prepare: *const fn (ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!PreparedImage, + /// The token the chat template writes once per image, expanded to the image's tokens. + image_token: u32, + /// The tokens the template wraps an image in (the image token among them): text that spells one stays text. + markers: []const u32 = &.{}, + /// Image tokens one request may hold in all, and images. + image_tokens: u32, + max_images: u32, +}; + +/// --vision: image input's limits (``Open.vision``). +pub const VisionOpen = struct { image_tokens: u32 = 4096, max_images: u32 = 4 }; + pub const Reason = enum { stop, length, cancelled, failed }; /// What a finished reply's rounds did, for its runtime fields and /metrics. @@ -160,6 +197,8 @@ pub const Info = struct { plain_only: bool = false, /// The immutable retained-prefix plan applied at startup, not a process memory limit or current cache occupancy. prompt_cache_plan: ?PromptCachePlan = null, + /// Image input (--vision); null: text only. + vision: ?Vision = null, /// The engine decodes greedily only: the server refuses a request with a temperature before admitting it. greedy_only: bool = false, /// Whether a request's caches fit beside the running streams' now (null: a free lane does); else it waits in order. @@ -225,6 +264,10 @@ pub const Open = struct { master_port: u16 = 29551, /// --policy: the engine's policy as `key=value,...`; empty: its defaults. policy: []const u8 = "", + /// --vision: load the checkpoint's image tower (null: text only; an engine without one refuses). + vision: ?VisionOpen = null, + /// --kv-cache fp8: attention caches as e4m3 with a scale a row (the CUDA Qwen3.8-27B engine only). + kv8: bool = false, }; /// An opened engine; ``close`` stops its thread and frees its backend. diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index 4394fdac05..acac2dd352 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -77,7 +77,7 @@ pub const LaneHost = struct { fn kept(ptr: *anyopaque, s: *lanes.Stream, at: u32) void { const job: *Job = @ptrCast(@alignCast(ptr)); job.reported(); // before a keep can evict the entry the pass restored - if (job.host.cache) |store| _ = store.keepBorn(job.request.prompt, born(job.request), at, s, job.request.chunks, job.host.spans(job.request)); + if (job.host.cache) |store| _ = store.keepBorn(job.request.cacheKey(), born(job.request), at, s, job.request.chunks, job.host.spans(job.request)); } /// Report a restored prefix or its failed copy; an untouched prefix remains kept. @@ -87,7 +87,7 @@ pub const LaneHost = struct { const store = job.host.cache orelse return; if (!job.started) return; job.stream.reuse.saved = null; // the backend restores before its first chunk; a later keep may free it - if (job.stream.reuse_failed) store.resumed(e, job.request.prompt, false) else if (job.stream.cached == e.at) store.resumed(e, job.request.prompt, true); + if (job.stream.reuse_failed) store.resumed(e, job.request.cacheKey(), false) else if (job.stream.cached == e.at) store.resumed(e, job.request.cacheKey(), true); } }; @@ -309,7 +309,7 @@ pub const LaneHost = struct { if (r.background and r.max_tokens == 0 and h.warm_quiet > 0 and !h.quiet(job)) return h.cancel(job); // other work came first: it never ran var reuse: lanes.stream.Reuse = .{}; // the entry stays alive until the backend restores it: nothing keeps between here and this stream's own pass - if (h.cache) |store| if (r.prompt_logprobs == null and !r.untaught) if (store.lookupRewind(h.gpa, r.prompt, born(r), r.history_len, r.rewind_len, r.shared_prefixes, r.chunks, h.spans(r))) |l| { + if (h.cache) |store| if (r.prompt_logprobs == null and !r.untaught) if (store.lookupRewind(h.gpa, r.cacheKey(), born(r), r.history_len, r.rewind_len, r.shared_prefixes, r.chunks, h.spans(r))) |l| { job.entry = l.entry; job.kept0 = store.counts.kept; job.marks = l.marks; @@ -341,8 +341,9 @@ pub const LaneHost = struct { job.proposer.deinit(); return h.drop(job, if (e == error.OutOfMemory) "out of memory" else "the reply's grammar could not start (xgrammar)"); } else null, - .decode_spans = h.spans(r), + .decode_spans = r.cacheSpans(h.decoded_rows), .decide = r.decide, + .images = r.images, .untaught = r.untaught, }) catch { job.proposer.deinit(); diff --git a/zig/src/core/lane_host_reuse_test.zig b/zig/src/core/lane_host_reuse_test.zig index 01b1fc6bec..69fca5ae1f 100644 --- a/zig/src/core/lane_host_reuse_test.zig +++ b/zig/src/core/lane_host_reuse_test.zig @@ -106,6 +106,94 @@ test "a lane host resumes a conversation from its kept prompt state and reports try std.testing.expectEqual(@as(usize, 2), store.entries.items.len); } +test "an image's placeholders are cached by its content: another image under the same ids resumes none of it" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + const Snaps = struct { + fn bytes(_: *anyopaque, at: u32) u64 { + return 64 + 4 * @as(u64, at); + } + fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { + return error.BackendRestores; // lane-core backends restore inside their own prompt pass + } + fn drop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } + }; + var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .min_gap = 4, .min_prompt = 0 }, 1 << 20); + defer store.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + host.cache = &store; + try host.start(); + defer host.stop(); + const Box = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + cached: ?u32 = null, + done: ?Reason = null, + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const b: *@This() = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(std.testing.io); + defer b.mutex.unlock(std.testing.io); + switch (e.*) { + .prefilled => |c| b.cached = c, + .logprobs, .prompt_logprobs => {}, + .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, + .finished => |f| b.done = f.reason, + } + } + fn wait(b: *@This()) Reason { + while (true) { + b.mutex.lockUncancelable(std.testing.io); + const d = b.done; + b.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + const e = host.engine(); + // prompt ids 3..5 are one image's placeholders (token 9); cache_key holds ids derived from each image's content + const t1 = [_]u32{ 3, 1, 9, 9, 9, 9, 2, 6, 5, 3 }; + var key_a = t1; + var key_b = t1; + for (2..6) |k| { + key_a[k] = 0x8000_0000 + @as(u32, @intCast(k)); + key_b[k] = 0x9000_0000 + @as(u32, @intCast(k)); + } + var b1: Box = .{}; + defer b1.tokens.deinit(gpa); + const r1: Request = .{ .prompt = &t1, .max_tokens = 6, .history_len = 8, .cache_key = &key_a }; + try e.submit(1, &r1, .{ .ctx = &b1, .event = Box.event }); + try std.testing.expectEqual(Reason.length, b1.wait()); + try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); // image A's state at 8, past its image + // the same text and placeholder ids with image B: the kept state is A's, so B resumes none of it + var b2: Box = .{}; + defer b2.tokens.deinit(gpa); + const r2: Request = .{ .prompt = &t1, .max_tokens = 6, .history_len = 8, .cache_key = &key_b }; + try e.submit(2, &r2, .{ .ctx = &b2, .event = Box.event }); + try std.testing.expectEqual(Reason.length, b2.wait()); + try std.testing.expectEqual(@as(?u32, 0), b2.cached); + // image A again resumes its own state + var b3: Box = .{}; + defer b3.tokens.deinit(gpa); + const r3: Request = .{ .prompt = &t1, .max_tokens = 6, .history_len = 8, .cache_key = &key_a }; + try e.submit(3, &r3, .{ .ctx = &b3, .event = Box.event }); + try std.testing.expectEqual(Reason.length, b3.wait()); + try std.testing.expectEqual(@as(?u32, 8), b3.cached); +} + test "a turn's mark evicting the state it resumed from: the hit is reported first and the entry freed once" { const gpa = std.testing.allocator; var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index fe26d3f003..7d2eb1fb08 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -68,6 +68,8 @@ pub const Backend = struct { prefill: *const fn (ptr: *anyopaque, s: *Stream) anyerror!void, /// One chunk of the prompt pass, false while chunks remain; null: the pass runs whole. prefill_step: ?*const fn (ptr: *anyopaque, s: *Stream) anyerror!bool = null, + /// Prefill several streams in shared passes, each with `prefill`'s bits; `errs[i]` for a failure. + prefill_many: ?*const fn (ptr: *anyopaque, streams: []const *Stream, errs: []?anyerror) anyerror!void = null, /// Draw the first token from the prompt's last row at `position`; a handle to it. first: *const fn (ptr: *anyopaque, s: *Stream, position: u64) anyerror!u64, /// Feed one token and queue the draw of the next at `position` (a one-token round); a handle to it. diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index f028d10cc4..5c7edbd003 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -97,6 +97,9 @@ pub const Held = struct { parents: ?[]i32 = null, }; +/// One image of a prompt: tower input (patches [gh * gw, width]) for the `tokens` placeholder rows from `at`. +pub const Image = struct { pixels: []const f32, gh: u32, gw: u32, at: u32, tokens: u32 }; + pub const Spec = struct { id: []const u8, prompt: []const u32, @@ -123,6 +126,7 @@ pub const Spec = struct { prompt_logprobs: ?u8 = null, // and for each prompt token after the first, with ranks (the prompt pass starts at 0) grammar: ?*grammar.Constraint = null, // structured output: the reply stays in it (the creator frees it) decode_spans: []const [2]u32 = &.{}, // prompt rows an earlier reply decoded (Request.decode_spans), for backends that keep their bits + images: []const Image = &.{}, // in prompt order; the backend's tower fills their rows }; pub const Stream = struct { @@ -154,6 +158,7 @@ pub const Stream = struct { reuse: Reuse = .{}, decode_spans: []const [2]u32 = &.{}, decide: ?u32 = null, + images: []const Image = &.{}, untaught: bool = false, cached: u32 = 0, // prompt tokens the backend restored from `reuse` (its prompt pass started there) reuse_failed: bool = false, // the backend's restore of `reuse` failed: it prefilled from 0 @@ -216,6 +221,7 @@ pub const Stream = struct { .prompt_logprobs = spec.prompt_logprobs, .grammar = spec.grammar, .decode_spans = spec.decode_spans, + .images = spec.images, }; // under a grammar a forced close ends at the think end: the grammar takes the reply from the next token if (spec.grammar) |g| if (g.after) |end| if (std.mem.indexOfScalar(u32, s.think_close, end)) |at| { diff --git a/zig/src/core/tokenizer/tokenizer.zig b/zig/src/core/tokenizer/tokenizer.zig index d856838549..d71bdca162 100644 --- a/zig/src/core/tokenizer/tokenizer.zig +++ b/zig/src/core/tokenizer/tokenizer.zig @@ -133,6 +133,22 @@ pub const Tokenizer = struct { return a.dupe(u32, ids.items); } + /// `encode` with no added token matched: text that spells one (a quoted marker) is ordinary text. + pub fn encodePlain(t: *const Tokenizer, a: Allocator, text: []const u8) Error![]u32 { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + var ctx = steps.Context{ .a = arena.allocator(), .matcher = .{ .a = arena.allocator() } }; + var valid = text; + if (!std.unicode.utf8ValidateSlice(text)) { + var fixed: std.ArrayList(u8) = .empty; + try unicode.appendLossy(&fixed, ctx.a, text); + valid = fixed.items; + } + var ids: std.ArrayList(u32) = .empty; + if (valid.len > 0) try t.encodeTextWith(&ctx, valid, true, &ids, false); + return a.dupe(u32, ids.items); + } + /// encodeText through the memo for a long segment: its kept ids, else encoded and kept. fn encodeSegment(t: *const Tokenizer, ctx: *steps.Context, text: []const u8, first: bool, ids: *std.ArrayList(u32)) Error!void { const m = t.memo orelse return t.encodeText(ctx, text, first, ids); @@ -144,9 +160,15 @@ pub const Tokenizer = struct { } fn encodeText(t: *const Tokenizer, ctx: *steps.Context, text: []const u8, first: bool, ids: *std.ArrayList(u32)) Error!void { + return t.encodeTextWith(ctx, text, first, ids, true); + } + + fn encodeTextWith(t: *const Tokenizer, ctx: *steps.Context, text: []const u8, first: bool, ids: *std.ArrayList(u32), added: bool) Error!void { var zero: usize = if (first) unicode.decodeAt(text, 0).len else 0; const normalized = if (t.normalizer) |*n| try n.apply(ctx, text, &zero) else text; - for (try t.splitAdded(ctx, &t.normalized, normalized)) |seg| { + const whole = [_]Segment{.{ .start = 0, .end = normalized.len, .id = null }}; + const segs: []const Segment = if (added) try t.splitAdded(ctx, &t.normalized, normalized) else &whole; + for (segs) |seg| { if (seg.id) |id| { try ids.append(ctx.a, id); continue; diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 0fa8bf6e28..8ff900952c 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -13,6 +13,7 @@ fn Blob(comptime import_name: []const u8) type { pub const available = options.with_kernels; pub const gdn: []const u8 = if (available) &Blob("fatbin_gdn").bytes else &.{}; +pub const gdn_prefill: []const u8 = if (available) &Blob("fatbin_gdn_prefill").bytes else &.{}; pub const probe: []const u8 = if (available) &Blob("fatbin_probe").bytes else &.{}; pub const qmm_group: []const u8 = if (available) &Blob("fatbin_qmm_group").bytes else &.{}; pub const qmm_prefill: []const u8 = if (available) &Blob("fatbin_qmm_prefill").bytes else &.{}; @@ -28,6 +29,8 @@ pub const fp8_experts: []const u8 = if (available) &Blob("fatbin_fp8_experts").b pub const exlr8: []const u8 = if (available) &Blob("fatbin_exlr8").bytes else &.{}; pub const exlr8_dense: []const u8 = if (available) &Blob("fatbin_exlr8_dense").bytes else &.{}; pub const nvfp4_experts: []const u8 = if (available) &Blob("fatbin_nvfp4_experts").bytes else &.{}; +pub const qwen_ops: []const u8 = if (available) &Blob("fatbin_qwen_ops").bytes else &.{}; +pub const qwen_vision: []const u8 = if (available) &Blob("fatbin_qwen_vision").bytes else &.{}; pub const sample: []const u8 = if (available) &Blob("fatbin_sample").bytes else &.{}; pub const train: []const u8 = if (available) &Blob("fatbin_train").bytes else &.{}; pub const qmmf: []const u8 = if (available) &Blob("fatbin_qmmf").bytes else &.{}; @@ -44,6 +47,7 @@ pub const nemotron_route: []const u8 = if (available) &Blob("fatbin_nemotron_rou pub const nemotron_mamba: []const u8 = if (available) &Blob("fatbin_nemotron_mamba").bytes else &.{}; pub const nemotron_attention: []const u8 = if (available) &Blob("fatbin_nemotron_attention").bytes else &.{}; pub const nemotron_keyed: []const u8 = if (available) &Blob("fatbin_nemotron_keyed").bytes else &.{}; +pub const torch_norm_rotary: []const u8 = if (available) &Blob("fatbin_torch_norm_rotary").bytes else &.{}; pub const norms: []const u8 = if (available) &Blob("fatbin_norms").bytes else &.{}; pub const embed_rows: []const u8 = if (available) &Blob("fatbin_embed_rows").bytes else &.{}; diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 85b6f8c78e..416ea57b7a 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -3,6 +3,7 @@ const std = @import("std"); const lanes = @import("lanes"); const st = @import("state.zig"); const slots_mod = @import("slots.zig"); +const slot_images = @import("slot_images.zig"); const pool = @import("pool.zig"); const mirror = @import("mirror.zig"); const snapshot = @import("snapshot.zig"); @@ -101,6 +102,11 @@ pub const Backend = struct { try mirror.send(e, .begin, b.words.items); try b.sl.begin(i, prompt, s.drafts); s.cached = 0; + if (s.images.len > 0) { // the images through the tower first: the chunks inject their rows + if (e.ep != null) return error.VisionOnPair; + try slot_images.encode(b.sl, i, s.images); + } + defer if (s.images.len > 0) slot_images.end(b.sl); var at: u32 = 0; if (s.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); diff --git a/zig/src/families/glm/checks.zig b/zig/src/families/glm/checks.zig index 98404ca22a..50c0285c40 100644 --- a/zig/src/families/glm/checks.zig +++ b/zig/src/families/glm/checks.zig @@ -168,7 +168,7 @@ pub fn checkMatmul(e: *Engine, prompt: []const u32) !void { const out = try e.arena.buffer(@as(usize, rows) * N * 2); var x = e.ctx(); const b = e.begin(); - fwd.embed(&x, b.enc, e.prompt_ids, rows); + fwd.embed(&x, b.enc, e.prompt_ids, rows, 0); fwd.boundary(&x, b.enc, rows, false, L.hc.?[0], L.in_norm); fwd.qmv(&x, b.enc, e.k.qmv_kda_in, e.sc.normed, a.in_proj, out, rows); affine_mm.rowSums(b.enc, e.k.mm_bf16, 64, e.sc.normed, pr.sums, rows, a.in_proj.k); diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index e1ffe5ac41..9b33850a46 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -4,6 +4,7 @@ const mtl = @import("metal"); const cfg = @import("config.zig"); const wts = @import("weights.zig"); const page_cache = @import("page_cache.zig"); +const vision_mod = @import("vision.zig"); const st = @import("state.zig"); const fwd = @import("forward.zig"); const mtp = @import("mtp.zig"); @@ -84,6 +85,9 @@ pub const Engine = struct { rank_log: bool = false, // GLM_RANKS=1: each MTP depth's logits kept, and the target's rank in them where drafts miss ep_arena: std.heap.ArenaAllocator, // the link settings, alive as long as the link residency: ?mtl.ResidencySet = null, + vision: ?*vision_mod.Vision = null, // --vision: the image tower + vision_rows: Ref = undefined, // bf16 [image tokens, hidden]: a prompt's image rows (vision only) + vision_limits: vision_mod.Limits = .{}, keepalive_sets: [1]mtl.ResidencySet = undefined, // the residency set, for the idle keepalive's commit keepalive_target: mtl.keepalive.Target = undefined, // the engine's queue, set at load for the server's ticker load_seconds: f64 = 0, @@ -95,11 +99,11 @@ pub const Engine = struct { /// The checkpoint in `dir`, caches for `cap` tokens; GLM_LAYERS=N: the first N layers only; GLM_EP=settings: half the experts. pub fn load(gpa: std.mem.Allocator, dir: []const u8, cap: u32) !*Engine { - return loadWith(gpa, dir, cap, if (std.c.getenv("GLM_EP")) |v| std.mem.span(v) else null, false); + return loadWith(gpa, dir, cap, if (std.c.getenv("GLM_EP")) |v| std.mem.span(v) else null, false, null); } - /// `load` with expert parallel over the link in `ep_path` (this Mac's settings), or on one Mac when null. - pub fn loadWith(gpa: std.mem.Allocator, dir: []const u8, cap: u32, ep_path: ?[]const u8, learn: bool) !*Engine { + /// `load` with expert parallel over `ep_path`'s link (one Mac when null) and `vision`'s image tower and rows. + pub fn loadWith(gpa: std.mem.Allocator, dir: []const u8, cap: u32, ep_path: ?[]const u8, learn: bool, vision: ?vision_mod.Limits) !*Engine { const e = try gpa.create(Engine); // undefined memory: every field is set below errdefer gpa.destroy(e); const pool = mtl.objc.Pool.push(); @@ -108,6 +112,7 @@ pub const Engine = struct { e.gpa = gpa; e.ev = 0; e.residency = null; + e.vision = null; e.gpu = .{ 0, 0 }; e.fused_route = if (std.c.getenv("GLM_ROUTE")) |v| v[0] != '0' else true; e.draft_vocab = if (std.c.getenv("GLM_DRAFT_VOCAB")) |v| std.fmt.parseInt(u32, std.mem.span(v), 10) catch 0 else 0; @@ -215,10 +220,13 @@ pub const Engine = struct { me.rest[2] = @intFromBool(learn); // --learn on both Macs or neither: each holds its half of a learned state e.ep = try ep_mod.Ep.init(gpa, e.device, s, me); } + if (vision) |lim| try vision_mod.attach(e, gpa, dir, f.bytes[0..f.size], lim); // --vision: the tower and its rows + errdefer if (e.vision) |v| v.deinit(); // opt-in: wiring 181 GB leaves macOS nothing to reclaim if another model shares the Mac (Flash Next runs without) - if (std.c.getenv("GLM_RESIDENCY") == null) {} else if (e.device.residencySet(e.w.buffers.items.len + e.arena.buffers.items.len)) |set| { + if (std.c.getenv("GLM_RESIDENCY") == null) {} else if (e.device.residencySet(e.w.buffers.items.len + e.arena.buffers.items.len + if (e.vision) |v| v.buffers().len else 0)) |set| { for (e.w.buffers.items) |b| set.add(b); for (e.arena.buffers.items) |b| set.add(b); + if (e.vision) |v| for (v.buffers()) |b| set.add(b); set.commit(); set.requestResidency(); e.queue.addResidencySet(set); @@ -268,6 +276,7 @@ pub const Engine = struct { set.deinit(); } if (e.ep) |ep| ep.deinit(gpa); + if (e.vision) |v| v.deinit(); e.ep_arena.deinit(); if (e.pr) |*p| p.deinit(); if (e.round_fence) |f| f.deinit(); diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 330d9324e6..5d1801caee 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -31,8 +31,29 @@ pub const Ctx = struct { draft_vocab: u32 = 154880, // the MTP head's tokens: the vocabulary's first this many m_row: u32 = 0, // the MTP head's logits row in m_logits (a rank log keeps each depth's in its own row) segs: []const Seg = &.{}, // a shared window's streams in row order (empty: every row is `s`'s) + inject: ?*const Inject = null, // a prompt pass's image rows over its placeholder embeddings }; +/// An image prompt's tower output: prompt rows [at, at + n) of each span embed as rows [row, row + n) of `rows`. +pub const Inject = struct { rows: Ref, spans: []const Span }; +pub const Span = struct { at: u32, n: u32, row: u32 }; + +/// The image rows among `rows` embedding rows (positions pos..) written over `out`; nothing without an injection. +pub fn inject(x: *const Ctx, e: mtl.ComputeEncoder, out: Ref, rows: u32, pos: u32) void { + const inj = x.inject orelse return; + const D: usize = x.c.hidden; + for (inj.spans) |sp| { + const lo = @max(sp.at, pos); + const hi = @min(sp.at + sp.n, pos + rows); + if (lo >= hi) continue; + const n: usize = hi - lo; + e.setPipeline(x.k.copy_u32); + bind(e, 0, .{ inj.rows.at((sp.row + lo - sp.at) * D * 2), out.at((lo - pos) * D * 2) }); + e.setValue(@as(u32, @intCast(n * D / 2)), 2); + e.dispatchThreads(size(n * D / 2, 1, 1), size(256, 1, 1)); + } +} + /// One stream's rows in a shared window: its caches, its first row, its rows and the position of the first. pub const Seg = struct { s: *st.State, row0: u32, rows: u32, pos: u32 }; @@ -136,11 +157,12 @@ pub fn scale(x: *const Ctx, e: mtl.ComputeEncoder, in: Ref, out: Ref, rows: u32, e.dispatchThreads(size(width, rows, 1), size(@min(width, 256), 1, 1)); } -/// The window's tokens (`ids`, u32) as embedding rows in all four streams. -pub fn embed(x: *Ctx, e: mtl.ComputeEncoder, ids: Ref, rows: u32) void { +/// The window's tokens (`ids`, u32, at positions pos..) as embedding rows in all four streams, image rows injected. +pub fn embed(x: *Ctx, e: mtl.ComputeEncoder, ids: Ref, rows: u32, pos: u32) void { const sc = x.sc; const D = x.c.hidden; embedRows(x, e, ids, sc.h, rows); + inject(x, e, sc.h, rows, pos); e.setPipeline(x.k.streams); bind(e, 0, .{ sc.h, sc.x[0] }); e.setValue([2]u32{ D, rows }, 2); @@ -438,7 +460,7 @@ pub fn backbone(x: *Ctx, e: mtl.ComputeEncoder, ids: Ref, rows: u32, pos: u32) v const c = x.c; const sc = x.sc; const k = x.skip; - if (k & Class.ends == 0) embed(x, e, ids, rows); + if (k & Class.ends == 0) embed(x, e, ids, rows, pos); const plane = @as(usize, rows) * c.hidden * 2; snap(x, e, sc.h, plane); var pending = false; diff --git a/zig/src/families/glm/glm.zig b/zig/src/families/glm/glm.zig index 11a7502c8f..9167917d93 100644 --- a/zig/src/families/glm/glm.zig +++ b/zig/src/families/glm/glm.zig @@ -13,6 +13,8 @@ pub const pool = @import("pool.zig"); pub const backend = @import("backend.zig"); pub const mirror = @import("mirror.zig"); pub const timing = @import("timing.zig"); +pub const vision = @import("vision.zig"); +pub const image = @import("image.zig"); pub const affine = @import("affine.zig"); pub const wide = @import("wide.zig"); @@ -33,6 +35,8 @@ test { _ = @import("kept.zig"); _ = mirror; _ = timing; + _ = vision; + _ = image; _ = @import("quant.zig"); _ = @import("affine.zig"); _ = @import("names.zig"); diff --git a/zig/src/families/glm/image.zig b/zig/src/families/glm/image.zig new file mode 100644 index 0000000000..0ff08383ca --- /dev/null +++ b/zig/src/families/glm/image.zig @@ -0,0 +1,445 @@ +//! An image's bytes to GLM5-Next vision patches as TensorFold 0.6.6's --vision makes them (PIL, then mlx-vlm). +const std = @import("std"); +const vision = @import("vision.zig"); + +pub const Rgb = struct { + w: u32, + h: u32, + px: []u8, // row-major RGB, 3 bytes a pixel + + pub fn deinit(r: Rgb, gpa: std.mem.Allocator) void { + gpa.free(r.px); + } +}; + +/// One image ready for the tower: its patches, its patch grid and its tokens (gh * gw / 4). +pub const Prepared = struct { + pixels: []f32, // [gh * gw, 1176] + gh: u32, + gw: u32, + tokens: u32, + hash: u64, // of the image's bytes: two prompts with the same placeholders but other images are other prompts +}; + +pub const Error = error{ BadImage, ImageTooLarge, Animated, ImageTooSmall, OutOfMemory }; + +/// images.py's ImageLimits: an image's encoded bytes, sides and pixels. +pub const max_bytes = 10 << 20; +pub const max_side = 8192; +pub const max_pixels = 16 << 20; + +// ---- ImageIO and CoreGraphics (C APIs; the server binary links both frameworks) ---- +const CF = *anyopaque; +const CGRect = extern struct { x: f64, y: f64, w: f64, h: f64 }; +extern "c" fn CFDataCreate(alloc: ?CF, bytes: [*]const u8, len: isize) ?CF; +extern "c" fn CFDataGetBytePtr(data: CF) [*]const u8; +extern "c" fn CFDataGetLength(data: CF) isize; +extern "c" fn CFRelease(cf: CF) void; +extern "c" fn CGImageSourceCreateWithData(data: CF, options: ?CF) ?CF; +extern "c" fn CGImageSourceGetCount(src: CF) usize; +extern "c" fn CGImageSourceCreateImageAtIndex(src: CF, index: usize, options: ?CF) ?CF; +extern "c" fn CGImageGetWidth(img: CF) usize; +extern "c" fn CGImageGetHeight(img: CF) usize; +extern "c" fn CGImageGetBitsPerComponent(img: CF) usize; +extern "c" fn CGImageGetBitsPerPixel(img: CF) usize; +extern "c" fn CGImageGetBytesPerRow(img: CF) usize; +extern "c" fn CGImageGetBitmapInfo(img: CF) u32; +extern "c" fn CGImageGetColorSpace(img: CF) ?CF; +extern "c" fn CGColorSpaceGetModel(cs: CF) i32; +extern "c" fn CGImageGetDataProvider(img: CF) ?CF; +extern "c" fn CGDataProviderCopyData(p: CF) ?CF; +extern "c" fn CGColorSpaceCreateDeviceRGB() ?CF; +extern "c" fn CGColorSpaceRelease(cs: CF) void; +extern "c" fn CGBitmapContextCreate(data: ?*anyopaque, w: usize, h: usize, bpc: usize, bpr: usize, cs: CF, info: u32) ?CF; +extern "c" fn CGContextDrawImage(ctx: CF, rect: CGRect, img: CF) void; +extern "c" fn CGContextRelease(ctx: CF) void; +extern "c" fn CGContextSetRGBFillColor(ctx: CF, r: f64, g: f64, b: f64, a: f64) void; +extern "c" fn CGContextFillRect(ctx: CF, rect: CGRect) void; +extern "c" fn CGImageSourceCopyPropertiesAtIndex(src: CF, index: usize, options: ?CF) ?CF; +extern "c" fn CFDictionaryGetValue(dict: CF, key: ?*const anyopaque) ?CF; +extern "c" fn CFNumberGetValue(num: CF, kind: isize, out: *anyopaque) bool; +extern var kCGImagePropertyOrientation: ?*const anyopaque; + +const alpha_mask: u32 = 0x1f; +const order_mask: u32 = 0x7000; +const order_32_little: u32 = 0x2000; +const order_16_little: u32 = 0x1000; +const float_components: u32 = 0x100; + +/// Any single-frame image ImageIO reads as 8-bit RGB, upright by its EXIF orientation and over white where alpha. +pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { + if (bytes.len == 0) return error.BadImage; + if (bytes.len > max_bytes) return error.ImageTooLarge; + const data = CFDataCreate(null, bytes.ptr, @intCast(bytes.len)) orelse return error.OutOfMemory; + defer CFRelease(data); + const src = CGImageSourceCreateWithData(data, null) orelse return error.BadImage; + defer CFRelease(src); + const frames = CGImageSourceGetCount(src); + if (frames == 0) return error.BadImage; + if (frames > 1) return error.Animated; // images.py: animated and multipage images are refused + const img = CGImageSourceCreateImageAtIndex(src, 0, null) orelse return error.BadImage; + defer CFRelease(img); + const w = CGImageGetWidth(img); + const h = CGImageGetHeight(img); + if (w == 0 or h == 0) return error.BadImage; + if (w > max_side or h > max_side or w * h > max_pixels) return error.ImageTooLarge; + const out = try gpa.alloc(u8, w * h * 3); + errdefer gpa.free(out); + if (!(try raw(img, w, h, out))) try drawn(img, w, h, out); + const rgb: Rgb = .{ .w = @intCast(w), .h = @intCast(h), .px = out }; + const o = orientation(src); + if (o <= 1 or o > 8) return rgb; + defer rgb.deinit(gpa); + return orient(gpa, rgb, o); +} + +/// The first image's EXIF orientation (1-8; 1 or 0: as stored). +fn orientation(src: CF) u32 { + const props = CGImageSourceCopyPropertiesAtIndex(src, 0, null) orelse return 1; + defer CFRelease(props); + const num = CFDictionaryGetValue(props, kCGImagePropertyOrientation) orelse return 1; + var v: i32 = 1; + if (!CFNumberGetValue(num, 9, &v)) return 1; // kCFNumberIntType + return if (v < 1) 1 else @intCast(v); +} + +/// PIL's exif_transpose: EXIF orientation 2-8 applied, each output pixel read from its source pixel. +pub fn orient(gpa: std.mem.Allocator, src: Rgb, o: u32) Error!Rgb { + const w: usize = src.w; + const h: usize = src.h; + const swap = o >= 5; + const ow = if (swap) h else w; + const oh = if (swap) w else h; + const out = try gpa.alloc(u8, ow * oh * 3); + for (0..oh) |y| for (0..ow) |x| { + const s: [2]usize = switch (o) { + 2 => .{ w - 1 - x, y }, + 3 => .{ w - 1 - x, h - 1 - y }, + 4 => .{ x, h - 1 - y }, + 5 => .{ y, x }, + 6 => .{ y, h - 1 - x }, + 7 => .{ w - 1 - y, h - 1 - x }, + else => .{ w - 1 - y, x }, + }; + @memcpy(out[(y * ow + x) * 3 ..][0..3], src.px[(s[1] * w + s[0]) * 3 ..][0..3]); + }; + return .{ .w = @intCast(ow), .h = @intCast(oh), .px = out }; +} + +/// PIL's paste of a pixel with alpha `a` onto white: DIV255(255 * (255 - a) + c * a). +fn overWhite(c: u8, a: u8) u8 { + const t: u32 = 255 * (255 - @as(u32, a)) + @as(u32, c) * a + 128; + return @intCast(((t >> 8) + t) >> 8); +} + +/// The decoder's own values for 8- and 16-bit gray and RGB layouts (what PIL reads); false for any other layout. +fn raw(img: CF, w: usize, h: usize, out: []u8) Error!bool { + const info = CGImageGetBitmapInfo(img); + if (info & float_components != 0) return false; + const cs = CGImageGetColorSpace(img) orelse return false; + const model = CGColorSpaceGetModel(cs); // 0 monochrome, 1 RGB + if (model != 0 and model != 1) return false; + const bpc = CGImageGetBitsPerComponent(img); + const bpp = CGImageGetBitsPerPixel(img); + if (bpc != 8 and bpc != 16) return false; + const alpha = info & alpha_mask; // 0 none, 1/2 premultiplied last/first, 3/4 last/first, 5/6 skip last/first + if (alpha == 1 or alpha == 2 or alpha > 6) return false; + const colours: usize = if (model == 1) 3 else 1; + const comps: usize = colours + @intFromBool(alpha != 0); + if (bpp != comps * bpc) return false; + const first = alpha == 2 or alpha == 4 or alpha == 6; // the alpha (or skipped) component leads + const order = info & order_mask; + const little = (bpc == 8 and order == order_32_little) or (bpc == 16 and order == order_16_little); + if (bpc == 8 and order != 0 and order != order_32_little) return false; + if (bpc == 8 and little and comps != 4) return false; + const provider = CGImageGetDataProvider(img) orelse return false; + const data = CGDataProviderCopyData(provider) orelse return false; + defer CFRelease(data); + const base = CFDataGetBytePtr(data); + const len: usize = @intCast(CFDataGetLength(data)); + const bpr = CGImageGetBytesPerRow(img); + if (bpr * (h - 1) + w * bpp / 8 > len) return false; + const step = bpc / 8; + for (0..h) |y| { + const row = base + y * bpr; + for (0..w) |x| { + const px = row + x * comps * step; + var c: [4]u8 = undefined; + for (0..comps) |i| { + // a 32-bit little-endian pixel stores its components reversed; a 16-bit one each component's bytes + const slot = if (bpc == 8 and little) comps - 1 - i else i; + const at = px + slot * step; + c[i] = if (step == 1) at[0] else if (little) at[1] else at[0]; // 16 bits: the high byte, as PIL's 8-bit view + } + const lead: usize = @intFromBool(first and alpha != 0); + const o = out[(y * w + x) * 3 ..][0..3]; + if (colours == 3) { + o.* = .{ c[lead], c[lead + 1], c[lead + 2] }; + } else { + o.* = .{ c[lead], c[lead], c[lead] }; + } + if (alpha == 3 or alpha == 4) { // a real alpha band: over white, as images.py pastes it + const a = if (first) c[0] else c[comps - 1]; + for (o) |*v| v.* = overWhite(v.*, a); + } + } + } + return true; +} + +/// Any other layout (palette, CMYK, float, premultiplied): drawn into an RGB context over white. +fn drawn(img: CF, w: usize, h: usize, out: []u8) Error!void { + const cs = CGColorSpaceCreateDeviceRGB() orelse return error.BadImage; + defer CGColorSpaceRelease(cs); + const tmp = std.heap.page_allocator.alloc(u8, w * h * 4) catch return error.OutOfMemory; + defer std.heap.page_allocator.free(tmp); + @memset(tmp, 0); + const ctx = CGBitmapContextCreate(tmp.ptr, w, h, 8, w * 4, cs, 5) orelse return error.BadImage; // RGBX + defer CGContextRelease(ctx); + CGContextSetRGBFillColor(ctx, 1, 1, 1, 1); + CGContextFillRect(ctx, .{ .x = 0, .y = 0, .w = @floatFromInt(w), .h = @floatFromInt(h) }); + CGContextDrawImage(ctx, .{ .x = 0, .y = 0, .w = @floatFromInt(w), .h = @floatFromInt(h) }, img); + for (0..w * h) |i| @memcpy(out[i * 3 ..][0..3], tmp[i * 4 ..][0..3]); +} + +// ---- the processor's geometry ---- + +pub const Geometry = struct { target_h: u32, target_w: u32, content_h: u32, content_w: u32 }; + +fn alignUp(v: u64, f: u64) u64 { + return (v + f - 1) / f * f; +} + +/// smart_resize and _resize_geometry: the padded canvas under `max_tokens` (at least `min_tokens`), the content size. +pub fn geometry(h: u32, w: u32, min_tokens: u32, max_tokens: u32) Error!Geometry { + const factor: u64 = vision.patch * vision.merge; + const frames: u64 = vision.temporal; + const per_token = frames * factor * factor; + const min_px = @as(u64, min_tokens) * per_token; + const max_px = @as(u64, max_tokens) * per_token; + if (min_tokens == 0 or max_tokens < min_tokens) return error.ImageTooSmall; + const H: u64 = h; + const W: u64 = w; + var ah = alignUp(H, factor); + var aw = alignUp(W, factor); + var pixels = frames * ah * aw; + if (pixels < min_px) { + const scale = @sqrt(@as(f64, @floatFromInt(min_px)) / @as(f64, @floatFromInt(frames * H * W))); + ah = alignUp(@max(1, @as(u64, @intFromFloat(@ceil(@as(f64, @floatFromInt(H)) * scale)))), factor); + aw = alignUp(@max(1, @as(u64, @intFromFloat(@ceil(@as(f64, @floatFromInt(W)) * scale)))), factor); + pixels = frames * ah * aw; + } + if (pixels > max_px) { // the tallest content that fits, by bisection on its height + if (max_px < frames * factor * factor) return error.ImageTooSmall; + var best: [2]u64 = .{ factor, factor }; + var low: i64 = 1; + var high: i64 = @intCast(H); + while (low <= high) { + const ch: u64 = @intCast(@divFloor(low + high, 2)); + const cw: u64 = @max(1, W * ch / H); // math.floor(width * content_h / height) + const cand: [2]u64 = .{ alignUp(ch, factor), alignUp(cw, factor) }; + if (frames * cand[0] * cand[1] <= max_px) { + best = cand; + low = @as(i64, @intCast(ch)) + 1; + } else high = @as(i64, @intCast(ch)) - 1; + } + ah = best[0]; + aw = best[1]; + } + var scale = @min(@as(f64, @floatFromInt(ah)) / @as(f64, @floatFromInt(H)), @as(f64, @floatFromInt(aw)) / @as(f64, @floatFromInt(W))); + if (frames * H * W >= min_px) scale = @min(1.0, scale); + const chf: u64 = @intFromFloat(@floor(@as(f64, @floatFromInt(H)) * scale)); + const cwf: u64 = @intFromFloat(@floor(@as(f64, @floatFromInt(W)) * scale)); + return .{ .target_h = @intCast(ah), .target_w = @intCast(aw), .content_h = @intCast(@max(1, @min(ah, chf))), .content_w = @intCast(@max(1, @min(aw, cwf))) }; +} + +// ---- PIL's ImagingResample for 8-bit images (Resample.c), bicubic (a = -0.5) ---- + +const precision_bits = 32 - 8 - 2; + +fn bicubic(x0: f64) f64 { + const a = -0.5; + const x = @abs(x0); + if (x < 1.0) return ((a + 2.0) * x - (a + 3.0)) * x * x + 1; + if (x < 2.0) return (((x - 5) * x + 8) * x - 4) * a; + return 0; +} + +const Coeffs = struct { bounds: []u32, kk: []i32, ksize: usize }; + +/// precompute_coeffs and normalize_coeffs_8bpc: each output pixel's first input pixel, count and fixed-point weights. +fn coeffs(gpa: std.mem.Allocator, in_size: u32, out_size: u32) Error!Coeffs { + const scale = @as(f64, @floatFromInt(in_size)) / @as(f64, @floatFromInt(out_size)); + const filterscale = @max(scale, 1.0); + const support = 2.0 * filterscale; + const ksize: usize = @as(usize, @intFromFloat(@ceil(support))) * 2 + 1; + const bounds = try gpa.alloc(u32, @as(usize, out_size) * 2); + errdefer gpa.free(bounds); + const kk = try gpa.alloc(i32, @as(usize, out_size) * ksize); + errdefer gpa.free(kk); + var pre = try gpa.alloc(f64, ksize); + defer gpa.free(pre); + const ss = 1.0 / filterscale; + for (0..out_size) |xx| { + const center = (@as(f64, @floatFromInt(xx)) + 0.5) * scale; + var xmin_i: i64 = @intFromFloat(center - support + 0.5); // (int) truncates toward zero, as C does + if (xmin_i < 0) xmin_i = 0; + var xmax_i: i64 = @intFromFloat(center + support + 0.5); + if (xmax_i > in_size) xmax_i = in_size; + xmax_i -= xmin_i; + const xmin: usize = @intCast(xmin_i); + const xmax: usize = @intCast(xmax_i); + var ww: f64 = 0; + for (0..xmax) |x| { + const w = bicubic((@as(f64, @floatFromInt(x + xmin)) - center + 0.5) * ss); + pre[x] = w; + ww += w; + } + for (0..ksize) |x| { + const k = if (x < xmax) (if (ww != 0) pre[x] / ww else pre[x]) else 0; + const v = k * @as(f64, @floatFromInt(@as(i64, 1) << precision_bits)); + kk[xx * ksize + x] = @intFromFloat(if (v < 0) v - 0.5 else v + 0.5); // C's (int) of the rounded value + } + bounds[xx * 2] = @intCast(xmin); + bounds[xx * 2 + 1] = @intCast(xmax); + } + return .{ .bounds = bounds, .kk = kk, .ksize = ksize }; +} + +fn clip8(v: i64) u8 { + const s = v >> precision_bits; + return if (s < 0) 0 else if (s > 255) 255 else @intCast(s); +} + +/// Image.resize((w, h), BICUBIC) on an 8-bit RGB image: horizontal pass, then vertical, each rounded to 8 bits. +pub fn resize(gpa: std.mem.Allocator, src: Rgb, w: u32, h: u32) Error!Rgb { + var cur = src; + var owned = false; + errdefer if (owned) cur.deinit(gpa); + if (w != src.w) { // horizontal (PIL limits it to the rows the vertical pass reads: all of them here) + const c = try coeffs(gpa, src.w, w); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, w) * cur.h * 3); + for (0..cur.h) |y| for (0..w) |xx| { + const xmin = c.bounds[xx * 2]; + const xmax = c.bounds[xx * 2 + 1]; + const k = c.kk[xx * c.ksize ..]; + for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..xmax) |x| ss += @as(i64, cur.px[(y * cur.w + x + xmin) * 3 + ch]) * k[x]; + out[(y * w + xx) * 3 + ch] = clip8(ss); + } + }; + if (owned) cur.deinit(gpa); + cur = .{ .w = w, .h = cur.h, .px = out }; + owned = true; + } + if (h != src.h) { + const c = try coeffs(gpa, src.h, h); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, cur.w) * h * 3); + for (0..h) |yy| { + const ymin = c.bounds[yy * 2]; + const ymax = c.bounds[yy * 2 + 1]; + const k = c.kk[yy * c.ksize ..]; + for (0..cur.w) |x| for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..ymax) |y| ss += @as(i64, cur.px[((y + ymin) * cur.w + x) * 3 + ch]) * k[y]; + out[(yy * cur.w + x) * 3 + ch] = clip8(ss); + }; + } + if (owned) cur.deinit(gpa); + cur = .{ .w = cur.w, .h = h, .px = out }; + owned = true; + } + if (!owned) cur = .{ .w = src.w, .h = src.h, .px = try gpa.dupe(u8, src.px) }; + return cur; +} + +/// The resized content padded with black, scaled, normalized and cut into 2x2 windows of 14x14 patches, row-major. +pub fn patchify(gpa: std.mem.Allocator, content: Rgb, g: Geometry, mean: [3]f32, sd: [3]f32) Error![]f32 { + const P = vision.patch; + const M = vision.merge; + const gh = g.target_h / P; + const gw = g.target_w / P; + const out = try gpa.alloc(f32, @as(usize, gh) * gw * vision.patch_width); + const rescale: f32 = @floatCast(@as(f64, 1.0) / 255.0); + var row: usize = 0; + for (0..gh / M) |wy| for (0..gw / M) |wx| for (0..M) |my| for (0..M) |mx| { + const py0 = (wy * M + my) * P; + const px0 = (wx * M + mx) * P; + const dst = out[row * vision.patch_width ..][0..vision.patch_width]; + for (0..3) |ch| for (0..vision.temporal) |t| for (0..P) |dy| for (0..P) |dx| { + const y = py0 + dy; + const x = px0 + dx; + const v: u8 = if (y < content.h and x < content.w) content.px[(y * content.w + x) * 3 + ch] else 0; + const f = @as(f32, @floatFromInt(v)) * rescale; + dst[((ch * vision.temporal + t) * P + dy) * P + dx] = (f - mean[ch]) / sd[ch]; + }; + row += 1; + }; + return out; +} + +/// Bytes to patches: decoded, sized for `max_tokens` (at least min(16, max_tokens)), resized, padded and cut. +pub fn prepare(gpa: std.mem.Allocator, bytes: []const u8, c: vision.Config, max_tokens: u32) Error!Prepared { + const img = try decode(gpa, bytes); + defer img.deinit(gpa); + return prepareRgb(gpa, img, std.hash.Wyhash.hash(0x1a6e, bytes), c, max_tokens); +} + +pub fn prepareRgb(gpa: std.mem.Allocator, img: Rgb, hash: u64, c: vision.Config, max_tokens: u32) Error!Prepared { + const g = try geometry(img.h, img.w, @min(c.min_tokens, max_tokens), max_tokens); + const content = try resize(gpa, img, g.content_w, g.content_h); + defer content.deinit(gpa); + const pixels = try patchify(gpa, content, g, c.mean, c.std); + const gh = g.target_h / vision.patch; + const gw = g.target_w / vision.patch; + return .{ .pixels = pixels, .gh = gh, .gw = gw, .tokens = gh * gw / vision.patches_per_token, .hash = hash }; +} + +test "geometry follows smart_resize" { + // the reference dumps' grids: 517x389 pads to 532x392 unscaled; 96x96 grows to 112; 20x15 to the 16-token floor + try std.testing.expectEqual(Geometry{ .target_h = 392, .target_w = 532, .content_h = 389, .content_w = 517 }, try geometry(389, 517, 16, 4096)); + try std.testing.expectEqual(Geometry{ .target_h = 112, .target_w = 112, .content_h = 112, .content_w = 112 }, try geometry(96, 96, 16, 4096)); + const tiny = try geometry(15, 20, 16, 4096); + try std.testing.expectEqual(@as(u32, 8 * 14), tiny.target_h); + try std.testing.expectEqual(@as(u32, 10 * 14), tiny.target_w); + // a large image under a small budget: the canvas fits it + const big = try geometry(1500, 2000, 16, 256); + try std.testing.expect(@as(u64, big.target_h) * big.target_w * 2 <= 256 * 2 * 28 * 28); + try std.testing.expect(big.content_h <= big.target_h and big.content_w <= big.target_w); +} + +test "orientations move pixels as PIL's transposes do" { + const gpa = std.testing.allocator; + // a 3x2 image of pixel indices: 0 1 2 / 3 4 5 + var px: [18]u8 = undefined; + for (0..6) |i| @memset(px[i * 3 ..][0..3], @intCast(i)); + const src: Rgb = .{ .w = 3, .h = 2, .px = &px }; + const want = [_][]const u8{ &.{ 2, 1, 0, 5, 4, 3 }, &.{ 5, 4, 3, 2, 1, 0 }, &.{ 3, 4, 5, 0, 1, 2 }, &.{ 0, 3, 1, 4, 2, 5 }, &.{ 3, 0, 4, 1, 5, 2 }, &.{ 5, 2, 4, 1, 3, 0 }, &.{ 2, 5, 1, 4, 0, 3 } }; + for (want, 2..) |w, o| { + const out = try orient(gpa, src, @intCast(o)); + defer out.deinit(gpa); + for (w, 0..) |v, i| try std.testing.expectEqual(v, out.px[i * 3]); + } +} + +test "alpha over white follows PIL's DIV255" { + try std.testing.expectEqual(@as(u8, 255), overWhite(0, 0)); + try std.testing.expectEqual(@as(u8, 10), overWhite(10, 255)); + try std.testing.expectEqual(@as(u8, 132), overWhite(10, 128)); // DIV255(255 * 127 + 10 * 128) +} + +test "resize keeps a flat image flat and its size" { + const gpa = std.testing.allocator; + const px = try gpa.alloc(u8, 7 * 5 * 3); + defer gpa.free(px); + @memset(px, 200); + const out = try resize(gpa, .{ .w = 7, .h = 5, .px = px }, 13, 3); + defer out.deinit(gpa); + try std.testing.expectEqual(@as(u32, 13), out.w); + for (out.px) |v| try std.testing.expectEqual(@as(u8, 200), v); +} diff --git a/zig/src/families/glm/mtp.zig b/zig/src/families/glm/mtp.zig index 2f1234c1fb..ee88c7e7f8 100644 --- a/zig/src/families/glm/mtp.zig +++ b/zig/src/families/glm/mtp.zig @@ -35,6 +35,7 @@ pub fn absorb(x: *fwd.Ctx, e: mtl.ComputeEncoder, h: Ref, next: Ref, rows: u32, const L = &x.w.layers[c.layers]; const m = x.w.mtp.?; fwd.embedRows(x, e, next, sc.m_emb, rows); + fwd.inject(x, e, sc.m_emb, rows, pos + 1); // the head reads each row's next token: an image's rows one place on fwd.rms(x, e, sc.m_emb, m.enorm, sc.m_eh, rows, D, D, 2 * D, c.eps); fwd.rms(x, e, h, m.hnorm, sc.m_eh.at(@as(usize, D) * 2), rows, D, D, 2 * D, c.eps); if (m.eh_bf16) |eh| { // stored unquantized (mlx-lm's): fp32 sums of its bf16 rows diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index 4f73d916b0..cb7134e4f3 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -470,7 +470,7 @@ pub fn backbone(p: *const Prompt, x: *fwd.Ctx, e: mtl.ComputeEncoder, ids: Ref, std.debug.assert(x.sc == ss and M <= p.rows); const s = x.skip; // classes a profile leaves out const Class = fwd.Class; - if (s & Class.ends == 0) fwd.embed(x, e, ids, M); + if (s & Class.ends == 0) fwd.embed(x, e, ids, M, pos); const plane = @as(usize, M) * c.hidden * 2; // a trace's capture points: the decode backbone's fwd.snap(x, e, ss.h, plane); var pending = false; @@ -532,6 +532,7 @@ pub fn mtp(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, h: Ref, n const L = &x.w.layers[c.layers]; const m = x.w.mtp.?; fwd.embedRows(x, e, next, p.m_emb, M); + fwd.inject(x, e, p.m_emb, M, pos + 1); // the head reads each row's next token: an image's rows one place on fwd.rms(x, e, p.m_emb, m.enorm, p.m_eh, M, D, D, 2 * D, c.eps); fwd.rms(x, e, h, m.hnorm, p.m_eh.at(@as(usize, D) * 2), M, D, D, 2 * D, c.eps); if (m.eh_bf16) |eh| wide.bf16(&p.mm.wide.?, e, eh, D, 2 * D, .{ .in = p.m_eh, .ldx = 2 * D, .out = p.m_x, .ldo = D, .rows = M }) else qmm(p, e, p.m_eh, m.eh_proj, p.m_x, M); diff --git a/zig/src/families/glm/slot_images.zig b/zig/src/families/glm/slot_images.zig new file mode 100644 index 0000000000..8b41b53d05 --- /dev/null +++ b/zig/src/families/glm/slot_images.zig @@ -0,0 +1,35 @@ +//! A stream's images through the tower into the engine's image rows, injected over placeholders by its prompt chunks. +const std = @import("std"); +const mtl = @import("metal"); +const vision_mod = @import("vision.zig"); +const Slots = @import("slots.zig").Slots; +const Image = @import("lanes").stream.Image; + +/// Slot `i`'s images into the engine's image rows, one image a command buffer: the tower's host scratch is shared. +pub fn encode(sl: *Slots, i: u32, imgs: []const Image) !void { + const e = sl.e; + const v = e.vision orelse return error.NoVision; + if (imgs.len > e.vision_limits.max_images) return error.TooManyImages; + if (i >= sl.slots.len or !sl.slots[i].used) return error.SlotOutOfStep; + v.spans.clearRetainingCapacity(); + try sl.flush(); + e.sync(); + var row: u32 = 0; + for (imgs) |img| { + if (row + img.tokens > e.vision_limits.image_tokens or img.gh * img.gw != img.tokens * vision_mod.patches_per_token) return error.ImageTooLarge; + if (img.at + img.tokens > sl.slots[i].prompt_len) return error.ImageOutOfPrompt; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const b = e.begin(); + try v.encode(b.enc, img.pixels, img.gh, img.gw, e.vision_rows.at(@as(usize, row) * e.c.hidden * 2), null); + try e.finish(b.cb, b.enc); + try v.spans.append(v.gpa, .{ .at = img.at, .n = img.tokens, .row = row }); + row += img.tokens; + } + v.inject = .{ .slot = i, .v = .{ .rows = e.vision_rows, .spans = v.spans.items } }; +} + +/// The stream's prompt pass is over: the chunks after it inject nothing. +pub fn end(sl: *Slots) void { + if (sl.e.vision) |v| v.inject = null; +} diff --git a/zig/src/families/glm/slots.zig b/zig/src/families/glm/slots.zig index 90aa566962..98a69baf7d 100644 --- a/zig/src/families/glm/slots.zig +++ b/zig/src/families/glm/slots.zig @@ -219,6 +219,7 @@ pub const Slots = struct { const pool = mtl.objc.Pool.push(); defer pool.pop(); var x = sl.ctx(slot); + x.inject = if (e.vision) |v| v.injected(i) else null; // an image prompt's rows over its placeholders (slot_images.zig) const b = e.begin(); const ids = e.prompt_ids.at(@as(usize, at) * 4); const next = e.prompt_ids.at(@as(usize, at + 1) * 4); diff --git a/zig/src/families/glm/vision.zig b/zig/src/families/glm/vision.zig new file mode 100644 index 0000000000..50021c8a05 --- /dev/null +++ b/zig/src/families/glm/vision.zig @@ -0,0 +1,533 @@ +//! GLM-5.3-Flash's image tower on the GPU (mlx-vlm's glm5_next/vision.py in bf16): patches to `<|image|>` rows. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const frags = @import("../../core/frags.zig"); +const st = @import("../../core/safetensors.zig"); +const wts = @import("weights.zig"); +const fwd = @import("forward.zig"); +const readAll = @import("weights_fix.zig").readAll; +const Engine = @import("engine.zig").Engine; +const Ref = wts.Ref; + +// The tower this file reads; `Config.parse` refuses a checkpoint whose vision_config differs. +pub const hidden = 1024; +pub const heads = 16; +pub const head_dim = 64; +pub const depth = 24; +pub const mlp_inter = 4096; +pub const out_hidden = 4096; // the language model's width +pub const merger_inter = 10240; +pub const patch = 14; +pub const temporal = 2; +pub const merge = 2; +pub const patch_width = 3 * temporal * patch * patch; // 1176: a patch's values, channel by frame by row by column +pub const patches_per_token = merge * merge; + +/// --vision's limits: image tokens a prompt may hold in all (scratch and rows are sized for them), and images. +pub const Limits = struct { image_tokens: u32 = 4096, max_images: u32 = 4 }; + +pub const Config = struct { + eps: f32 = 1e-5, + limit: f32 = 10, // swiglu_limit + image_token: u32, + image_start: u32, + image_end: u32, + mean: [3]f32, + std: [3]f32, + min_tokens: u32, + max_tokens: u32, + + /// config.json's vision_config and image token ids, processor_config.json's image processor; null: no tower. + pub fn parse(arena: std.mem.Allocator, config_json: []const u8, processor_json: ?[]const u8) !?Config { + const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, config_json, .{}); + const vc = doc.object.get("vision_config") orelse return null; + if (vc != .object) return null; + const want = .{ .{ "depth", depth }, .{ "hidden_size", hidden }, .{ "num_heads", heads }, .{ "intermediate_size", mlp_inter }, .{ "out_hidden_size", out_hidden }, .{ "projection_intermediate_size", merger_inter }, .{ "patch_size", patch }, .{ "temporal_patch_size", temporal }, .{ "spatial_merge_size", merge }, .{ "in_channels", 3 } }; + inline for (want) |kv| { + const v = vc.object.get(kv[0]) orelse return error.VisionConfig; + if (v != .integer or v.integer != kv[1]) { + std.log.err("glm vision: vision_config.{s} is {f}; this tower reads {d}", .{ kv[0], std.json.fmt(v, .{}), kv[1] }); + return error.VisionConfig; + } + } + const act = vc.object.get("hidden_act") orelse return error.VisionConfig; + if (act != .string or !std.mem.eql(u8, act.string, "silu")) return error.VisionConfig; + var c: Config = .{ .image_token = 0, .image_start = 0, .image_end = 0, .mean = .{ 0.48145466, 0.4578275, 0.40821073 }, .std = .{ 0.26862954, 0.26130258, 0.27577711 }, .min_tokens = 16, .max_tokens = 8000 }; + if (vc.object.get("rms_norm_eps")) |v| c.eps = @floatCast(number(v) orelse return error.VisionConfig); + if (vc.object.get("swiglu_limit")) |v| c.limit = @floatCast(number(v) orelse return error.VisionConfig); + inline for (.{ .{ "image_token_id", "image_token" }, .{ "image_start_token_id", "image_start" }, .{ "image_end_token_id", "image_end" } }) |kv| { + const v = doc.object.get(kv[0]) orelse return error.VisionConfig; + if (v != .integer) return error.VisionConfig; + @field(c, kv[1]) = @intCast(v.integer); + } + const pj = processor_json orelse return c; + const pdoc = try std.json.parseFromSliceLeaky(std.json.Value, arena, pj, .{}); + const ip = pdoc.object.get("image_processor") orelse return c; + if (ip != .object) return error.VisionConfig; + inline for (.{ .{ "patch_size", patch }, .{ "temporal_patch_size", temporal }, .{ "merge_size", merge } }) |kv| { + if (ip.object.get(kv[0])) |v| if (v != .integer or v.integer != kv[1]) return error.VisionConfig; + } + if (ip.object.get("patch_expand_factor")) |v| if (v != .integer or v.integer != 1) return error.VisionConfig; + inline for (.{ "image_mean", "image_std" }, .{ &c.mean, &c.std }) |key, dst| if (ip.object.get(key)) |v| { + if (v != .array or v.array.items.len != 3) return error.VisionConfig; + for (v.array.items, 0..) |x, i| dst[i] = @floatCast(number(x) orelse return error.VisionConfig); + }; + if (ip.object.get("min_image_tokens")) |v| c.min_tokens = @intCast(v.integer); + if (ip.object.get("max_image_tokens")) |v| c.max_tokens = @intCast(v.integer); + return c; + } + + fn number(v: std.json.Value) ?f64 { + return switch (v) { + .float => |f| f, + .integer => |i| @floatFromInt(i), + else => null, + }; + } +}; + +const Kernels = struct { + lib: mtl.Library, + gemm: [3][2][2]mtl.Pipeline, // [bf16 nt, f32 nt, f32 nn][M % 64 == 0][N % 128 == 0] + bias: mtl.Pipeline, + add: mtl.Pipeline, + rms: mtl.Pipeline, + layer_norm: mtl.Pipeline, + qkv: mtl.Pipeline, + softmax: mtl.Pipeline, + heads_: mtl.Pipeline, + swiglu: mtl.Pipeline, + gelu: mtl.Pipeline, + + fn load(gpa: std.mem.Allocator, device: mtl.Device) !Kernels { + const src = try frags.source(device, gpa, sources.glm_vision); + defer gpa.free(src); + const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + var k: Kernels = undefined; + k.lib = lib; + const kinds = [_][]const u8{ "bf16_nt", "f32_nt", "f32_nn" }; + for (kinds, 0..) |kind, ki| for (0..2) |m| for (0..2) |n| { + var name: [64]u8 = undefined; + const full = try std.fmt.bufPrint(&name, "glmv_gemm_{s}_{d}{d}", .{ kind, m, n }); + k.gemm[ki][m][n] = try mtl.Pipeline.init(device, lib, full, false); + }; + inline for (.{ .{ "bias", "glmv_bias" }, .{ "add", "glmv_add" }, .{ "rms", "glmv_rms" }, .{ "layer_norm", "glmv_layer_norm" }, .{ "qkv", "glmv_qkv" }, .{ "softmax", "glmv_softmax" }, .{ "heads_", "glmv_heads" }, .{ "swiglu", "glmv_swiglu" }, .{ "gelu", "glmv_gelu" } }) |kv| { + @field(k, kv[0]) = try mtl.Pipeline.init(device, lib, kv[1], false); + } + return k; + } + + fn deinit(k: *Kernels) void { + for (&k.gemm) |*a| for (a) |*b| for (b) |p| p.deinit(); + inline for (.{ "bias", "add", "rms", "layer_norm", "qkv", "softmax", "heads_", "swiglu", "gelu" }) |f| @field(k, f).deinit(); + k.lib.deinit(); + } +}; + +const Block = struct { norm1: Ref, norm2: Ref, qkv_w: Ref, qkv_b: Ref, proj_w: Ref, proj_b: Ref, q_norm: Ref, k_norm: Ref, gate_w: Ref, gate_b: Ref, up_w: Ref, up_b: Ref, down_w: Ref, down_b: Ref }; + +const Weights = struct { + buf: mtl.Buffer, + patch_w: Ref, + patch_b: Ref, + blocks: [depth]Block, + post_norm: Ref, + down_w: Ref, // [4096, 2, 2, 1024]: the merge's kernel with its taps outermost, as four neighbouring patch rows read it + down_b: Ref, + m_proj: Ref, + m_norm_w: Ref, + m_norm_b: Ref, + m_gate: Ref, + m_up: Ref, + m_down: Ref, +}; + +/// The tower: kernels, weights (bf16, about 0.9 GiB) and scratch for `max_tokens` image tokens a request. +pub const Vision = struct { + gpa: std.mem.Allocator, + inject: ?struct { slot: u32, v: fwd.Inject } = null, // an image prompt's rows while its pass runs (slot_images.zig) + spans: std.ArrayList(fwd.Span) = .empty, + c: Config, + k: Kernels, + w: Weights, + scratch: mtl.Buffer, + max_patches: u32, + chunk: u32, // query rows an attention pass scores at once (bounds the fp32 score buffer) + // scratch views + patches: Ref, // [P, 1176] bf16 + cos: Ref, // [P, 64] f32 + sin: Ref, + x: Ref, // [P, 1024] bf16: the residual stream + xn: Ref, // [P, 1024]: a norm's output; the merger's first [T, 4096] + att: Ref, // [P, 1024]: heads side by side; the merger's second [T, 4096] + branch: Ref, // [P, 1024] + qkv: Ref, // [P, 3072] + q: Ref, // [16, P, 64] f32 + k_: Ref, + v: Ref, + s: Ref, // [16, chunk, P] f32 + o: Ref, // [16, chunk, 64] f32 + g: Ref, // [P, 4096] bf16 (the merger's [T, 10240] fits: T * 10240 < P * 4096) + u: Ref, + act: Ref, + bytes: usize, + + pub fn load(gpa: std.mem.Allocator, device: mtl.Device, dir: []const u8, c: Config, max_tokens: u32) !*Vision { + const v = try gpa.create(Vision); + errdefer gpa.destroy(v); + v.gpa = gpa; + v.inject = null; + v.spans = .empty; + v.c = c; + v.k = try Kernels.load(gpa, device); + errdefer v.k.deinit(); + v.w = try loadWeights(gpa, device, dir); + errdefer v.w.buf.deinit(); + const P: usize = @as(usize, max_tokens) * patches_per_token; + v.max_patches = @intCast(P); + // the scores take at most 256 MiB: 16 heads of `chunk` rows by P keys in fp32 + v.chunk = @intCast(std.math.clamp((256 << 20) / (heads * P * 4) / 64 * 64, 64, 4096)); + const parts = [_]usize{ P * patch_width * 2, P * 64 * 4, P * 64 * 4, P * hidden * 2, P * hidden * 2, P * hidden * 2, P * hidden * 2, P * 3 * hidden * 2, P * hidden * 4, P * hidden * 4, P * hidden * 4, @as(usize, heads) * v.chunk * P * 4, @as(usize, heads) * v.chunk * head_dim * 4, P * mlp_inter * 2, P * mlp_inter * 2, P * mlp_inter * 2 }; + var total: usize = 0; + for (parts) |n| total += std.mem.alignForward(usize, n, 256); + v.scratch = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer v.scratch.deinit(); + var at: usize = 0; + const views = [_]*Ref{ &v.patches, &v.cos, &v.sin, &v.x, &v.xn, &v.att, &v.branch, &v.qkv, &v.q, &v.k_, &v.v, &v.s, &v.o, &v.g, &v.u, &v.act }; + for (views, parts) |view, n| { + view.* = .{ .buf = v.scratch, .off = at }; + at += std.mem.alignForward(usize, n, 256); + } + v.bytes = total + v.w.buf.length(); + return v; + } + + pub fn deinit(v: *Vision) void { + v.spans.deinit(v.gpa); + v.scratch.deinit(); + v.w.buf.deinit(); + v.k.deinit(); + v.gpa.destroy(v); + } + + /// Slot `i`'s image rows for its prompt pass, while its images' pass runs; null for any other slot. + pub fn injected(v: *const Vision, i: u32) ?*const fwd.Inject { + if (v.inject) |*inj| if (inj.slot == i) return &inj.v; + return null; + } + + /// Buffers to keep resident with the engine's. + pub fn buffers(v: *const Vision) [2]mtl.Buffer { + return .{ v.w.buf, v.scratch }; + } + + /// One image's patches ([gh * gw, 1176] fp32) into its rows `out`; `stop`: end after that block, residual in `x`. + pub fn encode(v: *Vision, enc: mtl.ComputeEncoder, pixels: []const f32, gh: u32, gw: u32, out: Ref, stop: ?u32) !void { + const P: u32 = gh * gw; + if (P == 0 or gh % merge != 0 or gw % merge != 0) return error.ImageGrid; + if (P > v.max_patches) return error.ImageTooLarge; + if (pixels.len != @as(usize, P) * patch_width) return error.ImageGrid; + const T: u32 = P / patches_per_token; + // host: the patches in bf16 (MLX's astype), and each patch's rotary angles + const dst: [*]u16 = @ptrCast(@alignCast(v.patches.addr())); + for (pixels, 0..) |p, i| dst[i] = bf16(p); + rotary(v, gh, gw); + + v.gemmLinear(enc, v.patches, v.w.patch_w, v.x, P, hidden, patch_width); + v.biasAdd(enc, v.x, v.w.patch_b, P, hidden); + if (stop) |s| if (s == 0) return; + for (v.w.blocks, 0..) |b, i| { + v.block(enc, b, P); + if (stop) |s| if (s == i + 1) return; + } + v.rms(enc, v.x, v.w.post_norm, v.xn, P, hidden); + // the merge: four neighbouring patches' rows are one row of xn read as [T, 4096] + const m0 = v.xn; + const m1 = v.att; + v.gemmLinear(enc, m0, v.w.down_w, m1, T, out_hidden, patches_per_token * hidden); + v.biasAdd(enc, m1, v.w.down_b, T, out_hidden); + v.gemmLinear(enc, m1, v.w.m_proj, m0, T, out_hidden, out_hidden); + v.layerNorm(enc, m0, v.w.m_norm_w, v.w.m_norm_b, m1, T, out_hidden); + enc.setPipeline(v.k.gelu); + enc.setBuffer(m1.buf, m1.off, 0); + enc.dispatchThreads(mtl.Size.of(@as(usize, T) * out_hidden, 1, 1), mtl.Size.of(256, 1, 1)); + v.gemmLinear(enc, m1, v.w.m_gate, v.g, T, merger_inter, out_hidden); + v.gemmLinear(enc, m1, v.w.m_up, v.u, T, merger_inter, out_hidden); + v.swiglu(enc, @as(usize, T) * merger_inter); + v.gemmLinear(enc, v.act, v.w.m_down, out, T, out_hidden, merger_inter); + } + + fn block(v: *Vision, enc: mtl.ComputeEncoder, b: Block, P: u32) void { + v.rms(enc, v.x, b.norm1, v.xn, P, hidden); + v.gemmLinear(enc, v.xn, b.qkv_w, v.qkv, P, 3 * hidden, hidden); + v.biasAdd(enc, v.qkv, b.qkv_b, P, 3 * hidden); + enc.setPipeline(v.k.qkv); + const bufs = [_]Ref{ v.qkv, b.q_norm, b.k_norm, v.cos, v.sin, v.q, v.k_, v.v }; + for (bufs, 0..) |r, i| enc.setBuffer(r.buf, r.off, i); + enc.setValue(extern struct { L: u32, eps: f32 }{ .L = P, .eps = v.c.eps }, 8); + enc.dispatchGroups(mtl.Size.of(@as(usize, P) * heads * 3, 1, 1), mtl.Size.of(32, 1, 1)); + var q0: u32 = 0; + while (q0 < P) : (q0 += v.chunk) { + const lc = @min(v.chunk, P - q0); + // scores of this chunk's queries against every key, each head a batch + v.gemm(enc, 1, v.q.at(@as(usize, q0) * head_dim * 4), v.k_, v.s, lc, P, head_dim, head_dim, head_dim, P, heads, @as(usize, P) * head_dim, @as(usize, P) * head_dim, @as(usize, lc) * P); + enc.setPipeline(v.k.softmax); + enc.setBuffer(v.s.buf, v.s.off, 0); + enc.setValue(P, 1); + enc.setValue(@as(f32, 0.125), 2); // head_dim ** -0.5 + enc.dispatchGroups(mtl.Size.of(@as(usize, heads) * lc, 1, 1), mtl.Size.of(256, 1, 1)); + v.gemm(enc, 2, v.s, v.v, v.o, lc, head_dim, P, P, head_dim, head_dim, heads, @as(usize, lc) * P, @as(usize, P) * head_dim, @as(usize, lc) * head_dim); + enc.setPipeline(v.k.heads_); + enc.setBuffer(v.o.buf, v.o.off, 0); + enc.setBuffer(v.att.buf, v.att.off, 1); + enc.setValue([2]u32{ lc, q0 }, 2); + enc.dispatchThreads(mtl.Size.of(hidden, lc, 1), mtl.Size.of(256, 1, 1)); + } + v.gemmLinear(enc, v.att, b.proj_w, v.branch, P, hidden, hidden); + v.biasAdd(enc, v.branch, b.proj_b, P, hidden); + v.add(enc, v.x, v.branch, @as(usize, P) * hidden); + v.rms(enc, v.x, b.norm2, v.xn, P, hidden); + v.gemmLinear(enc, v.xn, b.gate_w, v.g, P, mlp_inter, hidden); + v.biasAdd(enc, v.g, b.gate_b, P, mlp_inter); + v.gemmLinear(enc, v.xn, b.up_w, v.u, P, mlp_inter, hidden); + v.biasAdd(enc, v.u, b.up_b, P, mlp_inter); + v.swiglu(enc, @as(usize, P) * mlp_inter); + v.gemmLinear(enc, v.act, b.down_w, v.branch, P, hidden, mlp_inter); + v.biasAdd(enc, v.branch, b.down_b, P, hidden); + v.add(enc, v.x, v.branch, @as(usize, P) * hidden); + } + + /// y [M, N] = x [M, K] w^T in bf16 (w as stored, [N, K]). + fn gemmLinear(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, M: u32, N: u32, K: u32) void { + v.gemm(enc, 0, x, w, y, M, N, K, K, K, N, 1, 0, 0, 0); + } + + /// tfp::gemm_nax: d [batch, M, N] = a x b (kind 0: bf16 a b^T, 1: fp32 a b^T, 2: fp32 a b), batches `s*` apart. + fn gemm(v: *Vision, enc: mtl.ComputeEncoder, kind: usize, a: Ref, b: Ref, d: Ref, M: u32, N: u32, K: u32, lda: u32, ldb: u32, ldd: u32, batch: u32, sa: usize, sb: usize, sd: usize) void { + const tn = (N + 127) / 128; + const tm = (M + 63) / 64; + enc.setPipeline(v.k.gemm[kind][@intFromBool(M % 64 == 0)][@intFromBool(N % 128 == 0)]); + enc.setBuffer(a.buf, a.off, 0); + enc.setBuffer(b.buf, b.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ M, N, K, lda, ldb, ldd, tn, tm, 2, K / 256, sa, sb, sd, 0, 0 }; + for (vals, 0..) |x, i| p[i] = @intCast(x); + enc.setBytes(std.mem.asBytes(&p), 2); + enc.setBuffer(d.buf, d.off, 3); + enc.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, @as(usize, batch) * 2), mtl.Size.of(32, 4, 2)); + } + + fn biasAdd(v: *Vision, enc: mtl.ComputeEncoder, y: Ref, b: Ref, rows: u32, width: u32) void { + enc.setPipeline(v.k.bias); + enc.setBuffer(y.buf, y.off, 0); + enc.setBuffer(b.buf, b.off, 1); + enc.setValue(width, 2); + enc.dispatchThreads(mtl.Size.of(width, rows, 1), mtl.Size.of(256, 1, 1)); + } + + fn add(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, y: Ref, n: usize) void { + enc.setPipeline(v.k.add); + enc.setBuffer(x.buf, x.off, 0); + enc.setBuffer(y.buf, y.off, 1); + enc.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + } + + fn rms(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, rows: u32, width: u32) void { + enc.setPipeline(v.k.rms); + enc.setBuffer(x.buf, x.off, 0); + enc.setBuffer(w.buf, w.off, 1); + enc.setBuffer(y.buf, y.off, 2); + enc.setValue(extern struct { rows: u32, width: u32, eps: f32 }{ .rows = rows, .width = width, .eps = v.c.eps }, 3); + enc.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + fn layerNorm(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, y: Ref, rows: u32, width: u32) void { + enc.setPipeline(v.k.layer_norm); + const bufs = [_]Ref{ x, w, b, y }; + for (bufs, 0..) |r, i| enc.setBuffer(r.buf, r.off, i); + enc.setValue(extern struct { rows: u32, width: u32, eps: f32 }{ .rows = rows, .width = width, .eps = 1e-5 }, 4); + enc.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + fn swiglu(v: *Vision, enc: mtl.ComputeEncoder, n: usize) void { + enc.setPipeline(v.k.swiglu); + enc.setBuffer(v.g.buf, v.g.off, 0); + enc.setBuffer(v.u.buf, v.u.off, 1); + enc.setBuffer(v.act.buf, v.act.off, 2); + enc.setValue(v.c.limit, 3); + enc.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + } +}; + +/// fp32 to bf16, round to nearest even (MLX's astype). +pub fn bf16(x: f32) u16 { + const b: u32 = @bitCast(x); + if (b & 0x7fffffff > 0x7f800000) return @truncate((b >> 16) | 0x40); // NaN stays NaN + return @truncate((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +/// Each patch's 2-D rotary cos and sin: its row and column in the patch grid times the 16 frequencies 10000^(-k/16). +fn rotary(v: *Vision, gh: u32, gw: u32) void { + var inv: [16]f32 = undefined; + for (&inv, 0..) |*f, k| f.* = 1.0 / @as(f32, @floatCast(std.math.pow(f64, 10000.0, @as(f64, @floatFromInt(2 * k)) / 32.0))); + const cs: [*]f32 = @ptrCast(@alignCast(v.cos.addr())); + const sn: [*]f32 = @ptrCast(@alignCast(v.sin.addr())); + const wx_n = gw / merge; + var i: usize = 0; + var wy: u32 = 0; + while (wy < gh / merge) : (wy += 1) { + var wx: u32 = 0; + while (wx < wx_n) : (wx += 1) { + for (0..merge) |my| for (0..merge) |mx| { + const h: f32 = @floatFromInt(wy * merge + my); + const w: f32 = @floatFromInt(wx * merge + mx); + for (0..32) |j| { + const angle: f32 = if (j < 16) h * inv[j] else w * inv[j - 16]; + const c: f32 = @floatCast(@cos(@as(f64, angle))); + const s: f32 = @floatCast(@sin(@as(f64, angle))); + cs[i * 64 + j] = c; + cs[i * 64 + j + 32] = c; + sn[i * 64 + j] = s; + sn[i * 64 + j + 32] = s; + } + i += 1; + }; + } + } +} + +/// model.visual.* from the checkpoint's shards into one buffer, the merge kernel's taps moved outermost. +fn loadWeights(gpa: std.mem.Allocator, device: mtl.Device, dir: []const u8) !Weights { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const Src = struct { path: [:0]const u8, off: u64, len: u64, dtype: st.DType, shape: []const usize }; + var names: std.StringHashMapUnmanaged(Src) = .empty; + { + const path = try std.fmt.allocPrintSentinel(arena, "{s}/model.safetensors.index.json", .{dir}, 0); + const f = try mtl.MappedFile.open(path); + defer f.deinit(); + const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, f.bytes[0..f.size], .{ .allocate = .alloc_always }); + var files: std.StringArrayHashMapUnmanaged(void) = .empty; + var it = doc.object.get("weight_map").?.object.iterator(); + while (it.next()) |kv| if (std.mem.startsWith(u8, kv.key_ptr.*, "model.visual.")) try files.put(arena, kv.value_ptr.string, {}); + if (files.count() == 0) return error.NoVisionTower; + for (files.keys()) |name| { + const full = try std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ dir, name }, 0); + const fd = std.c.open(full, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return error.OpenFailed; + defer _ = std.c.close(fd); + var head: [8]u8 = undefined; + try readAll(fd, &head, 0); + const hlen = std.mem.readInt(u64, &head, .little); + const header = try arena.alloc(u8, hlen); + try readAll(fd, header, 8); + const end: u64 = @intCast(std.c.lseek(fd, 0, std.c.SEEK.END)); + // read here, not by core/safetensors.zig: the patch kernel is 5-D, past its max_rank + const doc2 = try std.json.parseFromSliceLeaky(std.json.Value, arena, header, .{}); + var eit = doc2.object.iterator(); + while (eit.next()) |kv| { + if (!std.mem.startsWith(u8, kv.key_ptr.*, "model.visual.")) continue; + const o = kv.value_ptr.object; + const dtype = st.DType.parse(o.get("dtype").?.string) orelse return error.UnsupportedDType; + const dims = o.get("shape").?.array.items; + const shape = try arena.alloc(usize, dims.len); + var n: u64 = dtype.size(); + for (dims, shape) |d, *s| { + s.* = @intCast(d.integer); + n *= s.*; + } + const offs = o.get("data_offsets").?.array.items; + const b: u64 = @intCast(offs[0].integer); + const e: u64 = @intCast(offs[1].integer); + if (e < b or e - b != n or 8 + hlen + e > end) return error.BadSafetensors; + try names.put(arena, kv.key_ptr.*, .{ .path = full, .off = 8 + hlen + b, .len = e - b, .dtype = dtype, .shape = shape }); + } + } + } + // every tensor's place in one buffer, 256-aligned + const Want = struct { name: []const u8, shape: []const usize, ref: *Ref }; + var w: Weights = undefined; + var wants: std.ArrayList(Want) = .empty; + try wants.append(arena, .{ .name = "patch_embed.proj.weight", .shape = &.{ hidden, 3, temporal, patch, patch }, .ref = &w.patch_w }); + try wants.append(arena, .{ .name = "patch_embed.proj.bias", .shape = &.{hidden}, .ref = &w.patch_b }); + for (&w.blocks, 0..) |*b, i| { + const fields = .{ .{ "norm1.weight", &b.norm1, &[_]usize{hidden} }, .{ "norm2.weight", &b.norm2, &[_]usize{hidden} }, .{ "attn.qkv.weight", &b.qkv_w, &[_]usize{ 3 * hidden, hidden } }, .{ "attn.qkv.bias", &b.qkv_b, &[_]usize{3 * hidden} }, .{ "attn.proj.weight", &b.proj_w, &[_]usize{ hidden, hidden } }, .{ "attn.proj.bias", &b.proj_b, &[_]usize{hidden} }, .{ "attn.q_norm.weight", &b.q_norm, &[_]usize{head_dim} }, .{ "attn.k_norm.weight", &b.k_norm, &[_]usize{head_dim} }, .{ "mlp.gate_proj.weight", &b.gate_w, &[_]usize{ mlp_inter, hidden } }, .{ "mlp.gate_proj.bias", &b.gate_b, &[_]usize{mlp_inter} }, .{ "mlp.up_proj.weight", &b.up_w, &[_]usize{ mlp_inter, hidden } }, .{ "mlp.up_proj.bias", &b.up_b, &[_]usize{mlp_inter} }, .{ "mlp.down_proj.weight", &b.down_w, &[_]usize{ hidden, mlp_inter } }, .{ "mlp.down_proj.bias", &b.down_b, &[_]usize{hidden} } }; + inline for (fields) |f| try wants.append(arena, .{ .name = try std.fmt.allocPrint(arena, "blocks.{d}.{s}", .{ i, f[0] }), .shape = f[2], .ref = f[1] }); + } + try wants.append(arena, .{ .name = "post_layernorm.weight", .shape = &.{hidden}, .ref = &w.post_norm }); + try wants.append(arena, .{ .name = "downsample.weight", .shape = &.{ out_hidden, hidden, merge, merge }, .ref = &w.down_w }); + try wants.append(arena, .{ .name = "downsample.bias", .shape = &.{out_hidden}, .ref = &w.down_b }); + try wants.append(arena, .{ .name = "merger.proj.weight", .shape = &.{ out_hidden, out_hidden }, .ref = &w.m_proj }); + try wants.append(arena, .{ .name = "merger.post_projection_norm.weight", .shape = &.{out_hidden}, .ref = &w.m_norm_w }); + try wants.append(arena, .{ .name = "merger.post_projection_norm.bias", .shape = &.{out_hidden}, .ref = &w.m_norm_b }); + try wants.append(arena, .{ .name = "merger.gate_proj.weight", .shape = &.{ merger_inter, out_hidden }, .ref = &w.m_gate }); + try wants.append(arena, .{ .name = "merger.up_proj.weight", .shape = &.{ merger_inter, out_hidden }, .ref = &w.m_up }); + try wants.append(arena, .{ .name = "merger.down_proj.weight", .shape = &.{ out_hidden, merger_inter }, .ref = &w.m_down }); + const srcs = try arena.alloc(Src, wants.items.len); + var total: usize = 0; + for (wants.items, srcs) |want, *s| { + const full = try std.fmt.allocPrint(arena, "model.visual.{s}", .{want.name}); + s.* = names.get(full) orelse { + std.log.err("glm vision: the checkpoint has no tensor {s}", .{full}); + return error.MissingTensor; + }; + if (s.dtype != .bf16 or !std.mem.eql(usize, s.shape, want.shape)) { + std.log.err("glm vision: {s} is {t} {any}; the tower reads bf16 {any}", .{ full, s.dtype, s.shape, want.shape }); + return error.UnexpectedTensor; + } + total = std.mem.alignForward(usize, total, 256) + s.len; + } + w.buf = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer w.buf.deinit(); + var at: usize = 0; + for (wants.items, srcs) |want, s| { + at = std.mem.alignForward(usize, at, 256); + want.ref.* = .{ .buf = w.buf, .off = at }; + const fd = std.c.open(s.path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return error.OpenFailed; + defer _ = std.c.close(fd); + _ = std.c.fcntl(fd, 48, @as(c_int, 1)); // F_NOCACHE, as the language model's shards + const dst = w.buf.contents()[at..][0..s.len]; + try readAll(fd, dst, s.off); + at += s.len; + } + // downsample [O, C, 2, 2] -> [O, 2, 2, C]: a merge window's four patch rows, tap by tap + const dw: [*]u16 = @ptrCast(@alignCast(w.down_w.addr())); + const tmp = try gpa.alloc(u16, hidden * merge * merge); + defer gpa.free(tmp); + for (0..out_hidden) |o| { + const row = dw[o * hidden * 4 ..][0 .. hidden * 4]; + @memcpy(tmp, row); + for (0..hidden) |ch| for (0..4) |tap| { + row[tap * hidden + ch] = tmp[ch * 4 + tap]; + }; + } + return w; +} + +/// `e` reads images: the tower loaded beside its weights (about 0.9 GiB with scratch) and the rows images fill. +pub fn attach(e: *Engine, gpa: std.mem.Allocator, dir: []const u8, config: []const u8, lim: Limits) !void { + if (e.ep != null) return error.VisionOnPair; + const pj: ?mtl.MappedFile = blk: { + const pp = try std.fmt.allocPrintSentinel(gpa, "{s}/processor_config.json", .{dir}, 0); + defer gpa.free(pp); + break :blk mtl.MappedFile.open(pp) catch null; + }; + defer if (pj) |m| m.deinit(); + var cfg_arena = std.heap.ArenaAllocator.init(gpa); + defer cfg_arena.deinit(); + const vc = (try Config.parse(cfg_arena.allocator(), config, if (pj) |m| m.bytes[0..m.size] else null)) orelse return error.NoVisionTower; + e.vision = try Vision.load(gpa, e.device, dir, vc, lim.image_tokens); + e.vision_rows = try e.arena.buffer(@as(usize, lim.image_tokens) * e.c.hidden * 2); + e.vision_limits = lim; + std.log.info("glm: image tower loaded ({d:.2} GiB with scratch for {d} image tokens a prompt)", .{ @as(f64, @floatFromInt(e.vision.?.bytes)) / (1 << 30), lim.image_tokens }); +} + +test "bf16 rounds to nearest even" { + try std.testing.expectEqual(@as(u16, 0x3f80), bf16(1.0)); + try std.testing.expectEqual(@as(u16, 0x3f80), bf16(@bitCast(@as(u32, 0x3f808000)))); // a tie to even (down) + try std.testing.expectEqual(@as(u16, 0x3f82), bf16(@bitCast(@as(u32, 0x3f818000)))); // a tie to even (up) + try std.testing.expectEqual(@as(u16, 0x3f81), bf16(@bitCast(@as(u32, 0x3f808001)))); +} diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index cb2fa934a1..d1d01b14ad 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -25,6 +25,8 @@ pub const glue_ref = @import("glue_ref.zig"); pub const glue_math = @import("glue_math.zig"); pub const reuse = @import("cuda_reuse.zig"); pub const slide = @import("cuda_slide.zig"); +pub const source = @import("cuda_source.zig"); +pub const torch_ops = @import("cuda_torch_ops.zig"); test { _ = @import("config.zig"); diff --git a/zig/src/families/nemotron/cuda_source.zig b/zig/src/families/nemotron/cuda_source.zig index ffc4ba2eec..dcf89a40d4 100644 --- a/zig/src/families/nemotron/cuda_source.zig +++ b/zig/src/families/nemotron/cuda_source.zig @@ -33,9 +33,20 @@ const Job = struct { } }; +/// Where a Source's copies go: the driver, the stream, and whether the card has its own memory. +pub const Target = struct { + d: *const cuda.Driver, + s: cuda.Stream, + discrete: bool, + + pub fn of(ops: kern.Ops) Target { + return .{ .d = ops.k.d, .s = ops.s, .discrete = ops.k.discrete }; + } +}; + pub const Source = struct { gpa: std.mem.Allocator, - ops: kern.Ops, + ops: Target, files: std.ArrayList(Mapped) = .empty, slots: [slot_count]dio.Buffer = undefined, pinned: [slot_count]?cuda.HostBuffer = @splat(null), // a discrete card's slots, page-locked: copies run at the link's speed @@ -48,21 +59,21 @@ pub const Source = struct { next: u64 = 0, /// Page-aligned slots; on a discrete card page-locked, each with an event its copies record. - pub fn init(gpa: std.mem.Allocator, ops: kern.Ops) !Source { + pub fn init(gpa: std.mem.Allocator, ops: Target) !Source { var s: Source = .{ .gpa = gpa, .ops = ops }; var made: usize = 0; errdefer s.freeSlots(made); while (made < slot_count) : (made += 1) { - if (!ops.k.discrete) { + if (!ops.discrete) { s.slots[made] = try gpa.alignedAlloc(u8, .fromByteUnits(dio.alignment), slot_bytes); continue; } - var h = try cuda.HostBuffer.alloc(ops.k.d, slot_bytes); + var h = try cuda.HostBuffer.alloc(ops.d, slot_bytes); if (@intFromPtr(h.bytes.ptr) % dio.alignment != 0) { h.free(); return error.UnalignedPinnedSlot; } - s.copied[made] = cuda.Event.init(ops.k.d, false) catch |err| { + s.copied[made] = cuda.Event.init(ops.d, false) catch |err| { h.free(); return err; }; @@ -126,7 +137,8 @@ pub const Source = struct { pub fn upload(s: *Source, dst: u64, bytes: []const u8) !void { const at = s.locate(bytes) orelse { try s.flush(); - return s.ops.upload(dst, bytes); + if (bytes.len == 0) return; + return s.ops.d.check(s.ops.d.api.cuMemcpyHtoDAsync_v2(dst, bytes.ptr, bytes.len, s.ops.s.handle), "cuMemcpyHtoDAsync"); }; var done: usize = 0; while (done < bytes.len) { @@ -212,7 +224,7 @@ pub const Source = struct { /// Page-locked slots record their copy event; pageable slots wait for the driver to stage their bytes. fn finish(s: *Source, k: usize, p: Pending, got: []u8) !void { if (got.len == 0) return; - try s.ops.k.d.check(s.ops.k.d.api.cuMemcpyHtoDAsync_v2(p.dst, got.ptr, got.len, s.ops.s.handle), "cuMemcpyHtoDAsync"); + try s.ops.d.check(s.ops.d.api.cuMemcpyHtoDAsync_v2(p.dst, got.ptr, got.len, s.ops.s.handle), "cuMemcpyHtoDAsync"); if (s.copied[k]) |e| return e.record(s.ops.s); try s.ops.s.synchronize(); } diff --git a/zig/src/families/nemotron/cuda_train.zig b/zig/src/families/nemotron/cuda_train.zig index 771e472886..504399bb2c 100644 --- a/zig/src/families/nemotron/cuda_train.zig +++ b/zig/src/families/nemotron/cuda_train.zig @@ -267,7 +267,7 @@ pub const Trainer = struct { var ck = try core.Checkpoint.openModel(t.gpa, io, dir); defer ck.close(); // direct reads through the engine loader's slots: copies from the mapping crawl on GB10 - var src = try Source.init(t.gpa, t.e.ops()); + var src = try Source.init(t.gpa, .of(t.e.ops())); defer src.deinit(); try src.add(&ck); var name: [192]u8 = undefined; diff --git a/zig/src/families/nemotron/cuda_weights.zig b/zig/src/families/nemotron/cuda_weights.zig index ff25a8da37..c1d1c7c1ff 100644 --- a/zig/src/families/nemotron/cuda_weights.zig +++ b/zig/src/families/nemotron/cuda_weights.zig @@ -444,7 +444,7 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, if (c.format == .mlx and (c.group_size != 64 or c.bits != 4)) return error.UnsupportedQuantization; var w: Weights = .{ .gpa = gpa, .config = c }; errdefer w.deinit(); - var src = try Source.init(gpa, ops); + var src = try Source.init(gpa, .of(ops)); defer src.deinit(); var L: Loader = .{ .gpa = gpa, .ops = ops, .w = &w, .src = &src, .scratch = try cuda.DeviceBuffer.alloc(ops.k.d, 1 << 20) }; defer { diff --git a/zig/src/families/qwen27/cuda.zig b/zig/src/families/qwen27/cuda.zig new file mode 100644 index 0000000000..3e10f18896 --- /dev/null +++ b/zig/src/families/qwen27/cuda.zig @@ -0,0 +1,39 @@ +//! Qwen3.8-27B on CUDA in Zig: the Python 0.6.6 engine's kernels and layouts, beside the family's Metal engine. + +pub const config = @import("cuda/shape.zig"); +pub const kernels = @import("cuda/kernels.zig"); +pub const triton = @import("cuda/triton.zig"); +pub const weights = @import("cuda/weights.zig"); +pub const state = @import("cuda/state.zig"); +pub const Forward = @import("cuda/forward.zig").Forward; +pub const Part = @import("cuda/forward.zig").Part; +pub const engine = @import("cuda/engine.zig"); +pub const Engine = engine.Engine; +pub const Lanes = @import("cuda/lanes.zig").Cuda; +pub const native = @import("cuda/native.zig"); +pub const draft = @import("cuda/draft.zig"); +pub const lone = @import("cuda/lone.zig"); +pub const drafts = @import("cuda/drafts.zig"); +pub const vision = @import("cuda/vision.zig"); +pub const image = @import("cuda/image.zig"); +pub const reuse = @import("cuda/reuse.zig"); + +test { + _ = config; + _ = kernels; + _ = triton; + _ = weights; + _ = state; + _ = engine; + _ = @import("cuda/forward.zig"); + _ = @import("cuda/lanes.zig"); + _ = @import("cuda/tree.zig"); + _ = @import("cuda/draft_load.zig"); + _ = @import("cuda/draft_policy.zig"); + _ = draft; + _ = lone; + _ = native; + _ = vision; + _ = image; + _ = reuse; +} diff --git a/zig/src/families/qwen27/cuda/draft.zig b/zig/src/families/qwen27/cuda/draft.zig new file mode 100644 index 0000000000..587554ef05 --- /dev/null +++ b/zig/src/families/qwen27/cuda/draft.zig @@ -0,0 +1,423 @@ +//! DFlash2 on CUDA as dflash2's fast path runs it: a context from the target's taps, a masked block, the host tree. + +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const aot = cuda.aot; +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const wts = @import("weights.zig"); +const dl = @import("draft_load.zig"); +const policy = @import("draft_policy.zig"); + +const bf = 2; +const H = dl.hidden; +const D = dl.head_dim; +pub const block = 16; // masked rows a round drafts at most (dflash2.block) +/// Block rows a batch takes: every stream's block in one forward (launch_blocks). +pub const most_rows = block * st.max_streams; +/// Copy items a batch takes: every layer's keys and values of every stream, two pieces a head (or the head's rows). +const most_copies = @max(dl.layers * st.max_streams * 2 * dl.kv_heads * 2, 2 * most_rows); + +/// A stream's drafting context: each layer's keys and values ([kv heads, len, head dim], two buffers to swap). +pub const Context = struct { + arena: st.Arena, + keys: [dl.layers][2]u64, + values: [dl.layers][2]u64, + cur: u1 = 0, + len: usize = 0, // rows held (at most dl.window) + end: usize = 0, // the target position after the last absorbed row + + pub fn bytes() usize { + return dl.layers * 4 * std.mem.alignForward(usize, dl.kv_heads * dl.window * D * bf, 256); + } + + pub fn init(d: *const cuda.Driver) !Context { + var x: Context = .{ .arena = try st.Arena.init(d, bytes()), .keys = undefined, .values = undefined }; + for (0..dl.layers) |l| for (0..2) |j| { + x.keys[l][j] = try x.arena.take(dl.kv_heads * dl.window * D * bf); + x.values[l][j] = try x.arena.take(dl.kv_heads * dl.window * D * bf); + }; + return x; + } + + pub fn deinit(x: *Context) void { + x.arena.deinit(); + } + + /// dflash2.skip: `n` rows go untapped, so the context starts again after them. + pub fn skip(x: *Context, n: usize) void { + x.len = 0; + x.end += n; + } +}; + +/// One stream's share of a batch absorb: its context and how many of the gathered tap rows are its own (in turn). +pub const Absorb = struct { ctx: *Context, rows: usize }; +/// One stream's block: its context and the pending token heading it. +pub const Block = struct { ctx: *const Context, pending: u32 }; + +pub const DFlash2 = struct { + gpa: std.mem.Allocator, + w: dl.Weights, + target: *const wts.Weights, + ops: kern.Ops, + t: tri.Tri, + arena: st.Arena, + inv_freq: u64, // (D / 2) fp32 on the device, as dflash2 makes them + positions: []i32, // a call's row positions on the host + // a block's buffers (block rows) and absorbing's (up to the window's rows) + x: u64, + normed: u64, + conv: u64, + dyn: u64, + xs: u64, + qkv: u64, + q: u64, + k: u64, + v: u64, + attn: u64, + o: u64, + gate: u64, + up: u64, + act: u64, + act_xs: u64, + head_h: u64, + selected: u64, + logits: u64, + logits_tail: u64, + logits32: u64, + cand_values: u64, + cand_ids: u64, + topk_scratch: u64, + pos: u64, + cos: u64, + sin: u64, + table: u64, + copies: u64, + ids: u64, + // host copies of a round's candidates + host_ids: []i64, + host_values: []f32, + host_selected: []u16, + cands: []u32, + unary: []f64, + projected: []f64, + tree: policy.Tree = .{}, + launched: usize = 0, // the last batch's block rows a stream (0: none) + + pub fn init(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, t: tri.Tri, target: *const wts.Weights, dir: []const u8, target_dir: []const u8) !*DFlash2 { + const x = try gpa.create(DFlash2); + errdefer gpa.destroy(x); + x.* = undefined; + x.gpa = gpa; + x.ops = ops; + x.t = t; + x.target = target; + x.tree = .{}; + x.w = try dl.load(gpa, io, ops, dir, target_dir); + errdefer x.w.deinit(); + const R = dl.window + 1; // rows absorbed at once at most (the prompt's tail) + const W = most_rows; + x.arena = .{ .buf = null }; + for (0..2) |pass| { + if (pass == 1) x.arena = try st.Arena.init(ops.k.d, x.arena.used); + x.arena.used = 0; + const A = &x.arena; + x.x = try A.take(R * H * bf); + x.normed = try A.take(R * H * bf); + x.conv = try A.take(W * H * bf); + x.dyn = try A.take(W * 4 * (H / dl.conv_group) * bf); + x.xs = try A.take(R * (H * 5) / 64 * 4); + x.qkv = try A.take(R * (dl.heads + 2 * dl.kv_heads) * D * bf); + x.q = try A.take(W * dl.heads * D * bf); + x.k = try A.take(R * dl.kv_heads * D * bf); + x.v = try A.take(R * dl.kv_heads * D * bf); + x.attn = try A.take(W * dl.heads * D * bf); + x.o = try A.take(W * H * bf); + x.gate = try A.take(W * 17408 * bf); + x.up = try A.take(W * 17408 * bf); + x.act = try A.take(W * 17408 * bf); + x.act_xs = try A.take(W * 17408 / 64 * 4); + x.head_h = try A.take(W * H * bf); + x.selected = try A.take(W * dl.selector_rank * bf); + x.logits = try A.take(W * dl.head_rows * bf); + x.logits_tail = try A.take(W * (dl.spans[1][1] - dl.spans[1][0]) * bf); + x.logits32 = try A.take(W * dl.head_rows * 4); + x.cand_values = try A.take(W * policy.top * 4); + x.cand_ids = try A.take(W * policy.top * 8); + x.topk_scratch = try A.take(kern.torch_ops.topkScratchBytes(W, dl.head_rows)); + x.inv_freq = try A.take(D / 2 * 4); + x.pos = try A.take(R * 4); + x.cos = try A.take(R * D / 2 * 4); + x.sin = try A.take(R * D / 2 * 4); + x.table = try A.take(dl.layers * st.max_streams * 24); + x.copies = try A.take(most_copies * @sizeOf(kern.Copy)); + x.ids = try A.take(W * 4); + } + errdefer x.arena.deinit(); + { + var a: cuda.Args = .{}; + a.add(x.inv_freq); + a.add(@as(f32, @floatCast(dl.theta))); + a.add(@as(c_int, D / 2)); + a.add(@as(c_int, D)); + try cuda.launch.launch(ops.k.inv_freq, .{ .grid = .{ .x = 1 }, .block = .{ .x = D / 2 } }, ops.s, &a); + } + x.positions = try gpa.alloc(i32, dl.window + 1); + errdefer gpa.free(x.positions); + x.host_ids = try gpa.alloc(i64, W * policy.top); + x.host_values = try gpa.alloc(f32, W * policy.top); + x.host_selected = try gpa.alloc(u16, W * dl.selector_rank); + x.cands = try gpa.alloc(u32, W * policy.top); + x.unary = try gpa.alloc(f64, W * policy.top); + x.projected = try gpa.alloc(f64, W * dl.selector_rank); + return x; + } + + pub fn deinit(x: *DFlash2) void { + x.gpa.free(x.positions); + x.gpa.free(x.host_ids); + x.gpa.free(x.host_values); + x.gpa.free(x.host_selected); + x.gpa.free(x.cands); + x.gpa.free(x.unary); + x.gpa.free(x.projected); + x.tree.tokens.deinit(x.gpa); + x.tree.parents.deinit(x.gpa); + x.tree.scores.deinit(x.gpa); + x.arena.deinit(); + x.w.deinit(); + const gpa = x.gpa; + gpa.destroy(x); + } + + /// _lin: a packed projection of `rows` rows (each row's bits its own at any count), group sums first. + fn lin(x: *DFlash2, in: u64, q: kern.QLinear, out: u64, rows: usize) !void { + try x.t.groupSums(in, x.xs, q.k, rows, q.k); + try x.ops.dense(in, x.xs, q, out, rows); + } + + /// F.rms_norm over `rows` contiguous rows of the hidden width (the layers' and the head's norms). + fn torchNorm(x: *DFlash2, in: u64, weight: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(weight); + a.add(out); + a.add(@as(u64, 0)); + a.add(@as(f32, 1e-6)); + try cuda.launch.launch(x.ops.k.torch_rms, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 128 } }, x.ops.s, &a); + } + + fn rmsNorm(x: *DFlash2, in: u64, stride: usize, weight: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(@as(c_int, @intCast(stride))); + a.add(weight); + a.add(out); + a.add(@as(c_int, H)); + a.add(@as(f32, 1e-6)); + try cuda.launch.launch(x.ops.k.rms_norm, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, x.ops.s, &a); + } + + /// dflash2._rotary: cos and sin of each run's positions [start, start + rows) times the inverse frequencies, fp32. + fn rotary(x: *DFlash2, runs: []const [2]usize) !void { + var rows: usize = 0; + for (runs) |run| for (0..run[1]) |j| { + x.positions[rows] = @intCast(run[0] + j); + rows += 1; + }; + try x.ops.upload(x.pos, std.mem.sliceAsBytes(x.positions[0..rows])); + var a: cuda.Args = .{}; + for ([_]u64{ x.pos, x.inv_freq, x.cos, x.sin }) |v| a.add(v); + a.add(@as(c_int, D / 2)); + try cuda.launch.launch(x.ops.k.rotary, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = D / 2 } }, x.ops.s, &a); + } + + /// dflash2._prep: q (heads, rows, D), k and v (kv heads, rows, D) from [q | k | v] rows, normed and rotated. + fn prep(x: *DFlash2, qkv: u64, layer: usize, rows: usize, with_q: bool, q: u64, k: u64, v: u64) !void { + const l = x.w.layers[layer]; + const h: usize = if (with_q) dl.heads else 0; + const stride = (h + 2 * dl.kv_heads) * D; + const p = aot.ptr; + try x.t.set.run(x.t.s, "_prep_kernel", .{ @intCast(rows), @intCast(h + 2 * dl.kv_heads), 1 }, &.{ + p("QKV", "*bf16", qkv), p("QN", "*bf16", l.q_norm), p("KN", "*bf16", l.k_norm), p("COS", "*fp32", x.cos), p("SIN", "*fp32", x.sin), + p("QO", "*bf16", if (with_q) q else qkv), p("KO", "*bf16", k), p("VO", "*bf16", v), aot.int("L", @intCast(rows)), aot.int("stride", @intCast(stride)), + aot.float("eps", 1e-6), + }, &.{ aot.ci("H", @intCast(h)), aot.ci("HKV", dl.kv_heads), aot.ci("HALF", D / 2) }); + } + + /// dflash2._dconv: the two-tap dynamic conv of each `seg`-row block, plus a residual. + fn dconv(x: *DFlash2, in: u64, dyn: u64, base: u64, branch: usize, res: ?u64, out: u64, rows: usize, seg: usize) !void { + const p = aot.ptr; + try x.t.set.run(x.t.s, "_dconv_kernel", .{ @intCast(rows), (H + 1023) / 1024, 1 }, &.{ + p("X", "*bf16", in), p("DYN", "*bf16", dyn), p("BASE", "*bf16", base), p("RES", "*bf16", res orelse in), p("OUT", "*bf16", out), aot.int("SEG", @intCast(seg)), + }, &.{ aot.ci("D", H), aot.ci("G", H / dl.conv_group), aot.ci("GS", dl.conv_group), aot.ci("BRANCH", @intCast(branch)), aot.ci("HAS_RES", @intFromBool(res != null)), aot.ci("BLOCK", 1024) }); + } + + /// add_taps: the target's taps (rows of 5 x hidden bf16) projected into the context's layers. + pub fn absorb(x: *DFlash2, ctx: *Context, taps: u64, rows: usize) !void { + return x.absorbMany(&.{.{ .ctx = ctx, .rows = rows }}, taps); + } + + /// add_taps_streams: every stream's rows (in turn) through each projection once, each context its last window. + pub fn absorbMany(x: *DFlash2, items: []const Absorb, taps: u64) !void { + var total: usize = 0; + for (items) |it| total += it.rows; + if (total == 0) return; + if (total > dl.window + 1 or items.len > st.max_streams) return error.TooManyDraftTaps; + try x.lin(taps, x.w.fc, x.qkv, total); // fc's (rows, hidden) output, in a buffer of the window's rows + try x.rmsNorm(x.qkv, H, x.w.hidden_norm, x.normed, total); + var runs: [st.max_streams][2]usize = undefined; + for (items, 0..) |it, j| runs[j] = .{ it.ctx.end, it.rows }; + try x.rotary(runs[0..items.len]); + // every layer's copies: the last `keep` rows of [context | new rows], a head at a time, both halves once + var list: std.ArrayList(kern.Copy) = .empty; + defer list.deinit(x.gpa); + var starts: [dl.layers + 1]usize = undefined; + for (0..dl.layers) |l| { + starts[l] = list.items.len; + var first: usize = 0; + for (items) |it| { + const ctx = it.ctx; + const keep = @min(dl.window, ctx.len + it.rows); + const old_n = ctx.len; + const drop = old_n + it.rows - keep; // rows of [old | new] that fall out of the window + const from_old = old_n -| drop; + const new_from = drop -| old_n; + const nxt: u1 = ctx.cur ^ 1; + for ([_][2]u64{ x.ctxPair(ctx.keys[l], ctx.cur, nxt), x.ctxPair(ctx.values[l], ctx.cur, nxt) }, [_]u64{ x.k, x.v }) |pair, fresh| { + for (0..dl.kv_heads) |h| { + if (from_old > 0) try list.append(x.gpa, .{ .dst = pair[1] + h * keep * D * bf, .src = pair[0] + (h * old_n + drop) * D * bf, .bytes = from_old * D * bf }); + try list.append(x.gpa, .{ .dst = pair[1] + (h * keep + from_old) * D * bf, .src = fresh + (h * total + first + new_from) * D * bf, .bytes = (it.rows - new_from) * D * bf }); + } + } + first += it.rows; + } + } + starts[dl.layers] = list.items.len; + if (list.items.len > most_copies) return error.TooManyDraftTaps; + try x.ops.upload(x.copies, std.mem.sliceAsBytes(list.items)); + for (0..dl.layers) |l| { + try x.lin(x.normed, x.w.layers[l].kv, x.qkv, total); + try x.prep(x.qkv, l, total, false, 0, x.k, x.v); + try x.ops.copies(x.copies + starts[l] * @sizeOf(kern.Copy), starts[l + 1] - starts[l]); + } + try x.ops.s.synchronize(); + for (items) |it| { + it.ctx.cur ^= 1; + it.ctx.len = @min(dl.window, it.ctx.len + it.rows); + it.ctx.end += it.rows; + } + } + + fn ctxPair(_: *DFlash2, bufs: [2]u64, cur: u1, nxt: u1) [2]u64 { + return .{ bufs[cur], bufs[nxt] }; + } + + /// launch_blocks: each stream's pending token then masks through the layers in one forward; candidates on the host. + pub fn launchMany(x: *DFlash2, blocks: []const Block, L: usize) !void { + const S = blocks.len; + const rows = S * L; + if (S == 0 or S > st.max_streams or L < 2 or L > block) return error.NoDraftContext; + for (blocks) |b| if (b.ctx.len == 0) return error.NoDraftContext; + var ids: [most_rows]i32 = @splat(dl.mask_id); + var runs: [st.max_streams][2]usize = undefined; + // each layer's table: the streams' (keys, values) pointers, then their context lengths + const per = std.mem.alignForward(usize, S * 20, 16); // 16-byte aligned tables, as fresh torch tensors are + var table: [dl.layers * (st.max_streams * 20 + 16)]u8 align(8) = undefined; + for (blocks, 0..) |b, j| { + ids[j * L] = @intCast(b.pending); + runs[j] = .{ b.ctx.end, L }; + for (0..dl.layers) |l| { + const at = table[l * per ..]; + std.mem.writeInt(u64, at[j * 16 ..][0..8], b.ctx.keys[l][b.ctx.cur], .little); + std.mem.writeInt(u64, at[j * 16 + 8 ..][0..8], b.ctx.values[l][b.ctx.cur], .little); + std.mem.writeInt(i32, at[S * 16 + j * 4 ..][0..4], @intCast(b.ctx.len), .little); + } + } + try x.ops.upload(x.ids, std.mem.sliceAsBytes(ids[0..rows])); + try x.ops.upload(x.table, table[0 .. dl.layers * per]); + const tw = x.target; + try x.t.embed(x.ids, tw.embed.w, tw.embed.s, tw.embed.b, x.x, rows, H); + try x.rotary(runs[0..S]); + const scale: f32 = @floatCast(std.math.pow(f64, D, -0.5)); + for (x.w.layers, 0..) |l, i| { + try x.torchNorm(x.x, l.in_norm, x.normed, rows); + try x.lin(x.normed, l.attn_proj, x.dyn, rows); + try x.dconv(x.normed, x.dyn, l.attn_base, 0, null, x.conv, rows, L); + try x.lin(x.conv, l.qkv, x.qkv, rows); + try x.prep(x.qkv, i, rows, true, x.q, x.k, x.v); + const tb = x.table + i * per; + const p = aot.ptr; + try x.t.set.run(x.t.s, "_block_attention", .{ @intCast(S), dl.kv_heads, 1 }, &.{ + p("Q", "*bf16", x.q), p("KB", "*bf16", x.k), p("VB", "*bf16", x.v), p("TABLE", "*i64", tb), p("LENS", "*i32", tb + S * 16), p("O", "*bf16", x.attn), + aot.float("scale", scale), aot.int("window", dl.window), aot.int("R", @intCast(rows)), + }, &.{ aot.ci("G", dl.heads / dl.kv_heads), aot.ci("HKV", dl.kv_heads), aot.ci("L", @intCast(L)), aot.ci("LP", @intCast(@max(16, std.math.ceilPowerOfTwo(usize, L) catch unreachable))), aot.ci("D", D), aot.ci("BN", 64), aot.ci("CAUSAL", 0) }); + try x.lin(x.attn, l.o, x.o, rows); + try x.dconv(x.o, x.dyn, l.attn_base, 1, x.x, x.x, rows, L); + try x.torchNorm(x.x, l.post_norm, x.normed, rows); + try x.lin(x.normed, l.mlp_proj, x.dyn, rows); + try x.dconv(x.normed, x.dyn, l.mlp_base, 0, null, x.conv, rows, L); + try x.t.groupSums(x.conv, x.xs, H, rows, H); + try x.ops.dense(x.conv, x.xs, l.gate, x.gate, rows); + try x.ops.dense(x.conv, x.xs, l.up, x.up, rows); + try x.t.swiglu(x.gate, x.up, x.act, x.act_xs, rows, l.gate.n); + try x.ops.dense(x.act, x.act_xs, l.down, x.o, rows); + try x.dconv(x.o, x.dyn, l.mlp_base, 1, x.x, x.x, rows, L); + } + // every block but its pending row, normed into stacked depths + const depths = L - 1; + const total = S * depths; + for (0..S) |j| try x.torchNorm(x.x + (j * L + 1) * H * bf, x.w.norm, x.head_h + j * depths * H * bf, depths); + try x.lin(x.head_h, x.w.select, x.selected, total); + // matmul_rows: the head's spans at the stacked rows' K split (1), then joined column-wise + try x.t.groupSums(x.head_h, x.xs, H, total, H); + const head = tw.head; + const first: kern.QLinear = .{ .w = head.w, .s = head.s, .b = head.b, .n = dl.spans[0][1], .k = head.k, .npad = head.npad }; + try x.ops.denseSplit(x.head_h, x.xs, first, x.logits32, total, 1); // a scratch of the right size + try x.ops.denseSplit(x.head_h, x.xs, x.w.head_tail, x.logits_tail, total, 1); + var items: std.ArrayList(kern.Copy) = .empty; + defer items.deinit(x.gpa); + const na = dl.spans[0][1]; + const nb = dl.spans[1][1] - dl.spans[1][0]; + for (0..total) |r| { + try items.append(x.gpa, .{ .dst = x.logits + r * dl.head_rows * bf, .src = x.logits32 + r * na * bf, .bytes = na * bf }); + try items.append(x.gpa, .{ .dst = x.logits + (r * dl.head_rows + na) * bf, .src = x.logits_tail + r * nb * bf, .bytes = nb * bf }); + } + try x.ops.upload(x.copies, std.mem.sliceAsBytes(items.items)); + try x.ops.copies(x.copies, items.items.len); + const torch = x.ops.torch(); + try torch.toF32(x.logits, x.logits32, total * dl.head_rows); + try torch.topk(x.logits32, dl.head_rows, total, policy.top, x.cand_values, x.cand_ids, x.topk_scratch); + try x.ops.download(std.mem.sliceAsBytes(x.host_values[0 .. total * policy.top]), x.cand_values); + try x.ops.download(std.mem.sliceAsBytes(x.host_ids[0 .. total * policy.top]), x.cand_ids); + try x.ops.download(std.mem.sliceAsBytes(x.host_selected[0 .. total * dl.selector_rank]), x.selected); + try x.ops.s.synchronize(); + for (0..total * policy.top) |j| { + const local: usize = @intCast(x.host_ids[j]); + x.cands[j] = @intCast(if (local < na) local else dl.spans[1][0] + local - na); + x.unary[j] = x.host_values[j]; + } + for (0..total * dl.selector_rank) |j| x.projected[j] = @as(f32, @bitCast(@as(u32, x.host_selected[j]) << 16)); + x.launched = L; + } + + /// finish_tree for the batch's `j`th block: best_first into `out` (parents -1: under the pending row). + pub fn finish(x: *DFlash2, j: usize, pending: u32, context_length: usize, max_nodes: usize, sampling: ?lanes.Sampling, out: *policy.Tree) !void { + const depths = x.launched - 1; + const at = j * depths; + try policy.bestFirst(x.gpa, .{ .ids = x.cands[at * policy.top ..][0 .. depths * policy.top], .unary = x.unary[at * policy.top ..][0 .. depths * policy.top], .projected = x.projected[at * dl.selector_rank ..][0 .. depths * dl.selector_rank], .depths = depths }, x.w.pred, x.w.succ, pending, @min(127, max_nodes), sampling, context_length, out); + } + + /// finish_tree: best_first over the launched block's candidates; nodes and parents (-1: under the pending row). + pub fn propose(x: *DFlash2, ctx: *const Context, pending: u32, context_length: usize, max_nodes: usize, sampling: ?lanes.Sampling) !struct { tokens: []const u32, parents: []const i32 } { + if (ctx.len == 0 or max_nodes == 0) return .{ .tokens = &.{}, .parents = &.{} }; + const rows: usize = @min(block, max_nodes + 1); + try x.launchMany(&.{.{ .ctx = ctx, .pending = pending }}, rows); + try x.finish(0, pending, context_length, max_nodes, sampling, &x.tree); + return .{ .tokens = x.tree.tokens.items, .parents = x.tree.parents.items }; + } +}; diff --git a/zig/src/families/qwen27/cuda/draft_load.zig b/zig/src/families/qwen27/cuda/draft_load.zig new file mode 100644 index 0000000000..8f9b0a7404 --- /dev/null +++ b/zig/src/families/qwen27/cuda/draft_load.zig @@ -0,0 +1,274 @@ +//! DFlash2's weights as dflash2 holds them: projections quantize4'd and tiled, codebooks fp32 on the host. + +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const kern = @import("kernels.zig"); +const st = @import("state.zig"); + +pub const QLinear = kern.QLinear; +const Tensor = core.checkpoint.Tensor; + +pub const hidden = 5120; +pub const layers = 5; +pub const heads = 32; +pub const kv_heads = 8; +pub const head_dim = 128; +pub const conv_group = 16; +pub const mask_id = 248070; +pub const window = 2047; // sliding_window - 1: context rows each layer keeps +pub const taps = [_]usize{ 5, 19, 33, 47, 61 }; // dflash_config.target_layer_ids +pub const selector_rank = 256; +pub const theta: f64 = 10000000; +/// The head's rows the drafter reads: the first 98,304 tokens and the last 288 (dflash2.vocab_spans). +pub const spans = [2][2]usize{ .{ 0, 98304 }, .{ 248032, 248320 } }; +pub const head_rows = spans[0][1] - spans[0][0] + spans[1][1] - spans[1][0]; + +pub const Layer = struct { + in_norm: u64, + post_norm: u64, + attn_proj: QLinear, // attention_conv.kernel_projection: the conv's dynamic taps (2 x 2 x 320) + attn_base: u64, // attention_conv.base_kernel (2, 2, 5120) bf16 + mlp_proj: QLinear, + mlp_base: u64, + qkv: QLinear, // [q | k | v] stacked + kv: QLinear, // [k | v] stacked: the context's projection + o: QLinear, + q_norm: u64, + k_norm: u64, + gate: QLinear, + up: QLinear, + down: QLinear, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + layers: [layers]Layer = undefined, + fc: QLinear = undefined, // five taps (25,600) to the hidden width + hidden_norm: u64 = 0, + norm: u64 = 0, + select: QLinear = undefined, // candidate_selector.hidden_projection + head_tail: QLinear = undefined, // the target head's last 288 rows, tiled on their own (rows() copies them) + pred: []f32 = &.{}, // candidate_selector.predecessor_codebook (vocab, 256) + succ: []f32 = &.{}, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.pred); + w.gpa.free(w.succ); + w.* = undefined; + } +}; + +fn bf16Value(word: u16) f32 { + return @bitCast(@as(u32, word) << 16); +} + +fn toBf16(x: f32) u16 { + const b: u32 = @bitCast(x); + return @intCast((b + 0x7FFF + ((b >> 16) & 1)) >> 16); +} + +/// torch.round: halves to even. +fn roundEven(x: f32) f32 { + const r = @round(x); + return if (@abs(x - @trunc(x)) == 0.5) 2.0 * @round(x / 2.0) else r; +} + +/// dflash2.quantize4 on the host, bit for bit: (n, k) bf16 to MLX affine 4-bit words, bf16 scales and biases. +pub fn quantize4(src: []const u8, n: usize, k: usize, words: []u32, scales: []u16, biases: []u16) void { + const kg = k / 64; + for (0..n) |r| for (0..kg) |gi| { + var vals: [64]f32 = undefined; + for (&vals, 0..) |*v, j| v.* = bf16Value(std.mem.readInt(u16, src[(r * k + gi * 64 + j) * 2 ..][0..2], .little)); + var lo = vals[0]; + var hi = vals[0]; + for (vals[1..]) |v| { + lo = @min(lo, v); + hi = @max(hi, v); + } + const s = toBf16(@max((hi - lo) / 15.0, 1e-8)); + const b = toBf16(lo); + scales[r * kg + gi] = s; + biases[r * kg + gi] = b; + const sf = bf16Value(s); + const bf = bf16Value(b); + for (0..8) |wi| { + var word: u32 = 0; + for (0..8) |j| { + const q = std.math.clamp(roundEven((vals[wi * 8 + j] - bf) / sf), 0.0, 15.0); + word |= @as(u32, @intFromFloat(q)) << @intCast(4 * j); + } + words[r * (k / 8) + gi * 8 + wi] = word; + } + }; +} + +const Loader = struct { + gpa: std.mem.Allocator, + ops: kern.Ops, + w: *Weights, + words: std.ArrayList(u32) = .empty, + scales: std.ArrayList(u16) = .empty, + biases: std.ArrayList(u16) = .empty, + staging: ?cuda.DeviceBuffer = null, + + fn alloc(L: *Loader, len: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(L.ops.k.d, len); + try L.w.buffers.append(L.gpa, b); + return b.ptr; + } + + fn raw(L: *Loader, t: Tensor) !u64 { + const ptr = try L.alloc(t.bytes.len); + try L.ops.upload(ptr, t.bytes); + try L.ops.s.synchronize(); + return ptr; + } + + /// qmm_fast.tile of host MLX words, scales and biases (n rows of k inputs): the lane matmul's layout. + fn tile(L: *Loader, words: []const u32, scales: []const u16, biases: []const u16, n: usize, k: usize) !QLinear { + const k8 = k / 8; + const kg = k / 64; + const npad = (n + 127) / 128 * 128; + const sizes = [3]usize{ n * k8 * 4, n * kg * 2, n * kg * 2 }; + const total_in = sizes[0] + sizes[1] + sizes[2]; + if (L.staging == null or L.staging.?.len < total_in) { + if (L.staging) |*b| b.free(); + L.staging = try cuda.DeviceBuffer.alloc(L.ops.k.d, total_in); + } + const base = L.staging.?.ptr; + try L.ops.upload(base, std.mem.sliceAsBytes(words)); + try L.ops.upload(base + sizes[0], std.mem.sliceAsBytes(scales)); + try L.ops.upload(base + sizes[0] + sizes[1], std.mem.sliceAsBytes(biases)); + const q: QLinear = .{ .w = try L.alloc(npad * k / 2), .s = try L.alloc(kg * npad * 2), .b = try L.alloc(kg * npad * 2), .n = n, .k = k, .npad = npad }; + const total: u64 = @as(u64, npad / 64) * kg * 512; + var a: cuda.Args = .{}; + a.add(base); + for ([_]usize{ n, k8, kg }) |v| a.add(@as(c_int, @intCast(v))); + a.add(q.w); + a.add(@as(c_longlong, @intCast(total))); + try cuda.launch.launch(L.ops.k.pack_dense, .{ .grid = .{ .x = @intCast((total + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &a); + for ([_]u64{ q.s, q.b }, [_]usize{ sizes[0], sizes[0] + sizes[1] }) |out, off| { + var t: cuda.Args = .{}; + t.add(base + off); + for ([_]usize{ n, kg, npad }) |v| t.add(@as(c_int, @intCast(v))); + t.add(out); + const cells = @as(u64, kg) * npad; + try cuda.launch.launch(L.ops.k.transpose16, .{ .grid = .{ .x = @intCast((cells + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &t); + } + try L.ops.s.synchronize(); // the staging buffer and host arrays are reused next + return q; + } + + /// One bf16 (n, k) checkpoint tensor (or several stacked by rows) quantized and tiled. + fn quantized(L: *Loader, parts: []const Tensor, k: usize) !QLinear { + var n: usize = 0; + for (parts) |t| { + if (t.dtype != .bf16 or t.rank != 2 or t.dim(1) != k) return error.UnexpectedDraftTensor; + n += t.dim(0); + } + try L.words.resize(L.gpa, n * k / 8); + try L.scales.resize(L.gpa, n * k / 64); + try L.biases.resize(L.gpa, n * k / 64); + var row: usize = 0; + for (parts) |t| { + const r = t.dim(0); + quantize4(t.bytes, r, k, L.words.items[row * k / 8 ..][0 .. r * k / 8], L.scales.items[row * k / 64 ..][0 .. r * k / 64], L.biases.items[row * k / 64 ..][0 .. r * k / 64]); + row += r; + } + return L.tile(L.words.items, L.scales.items, L.biases.items, n, k); + } + + fn get(ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype) !Tensor { + var buf: [160]u8 = undefined; + return ck.get(try std.fmt.bufPrint(&buf, fmt, args)); + } + + /// The codebook as fp32 on the host (dflash2 keeps tensor.float().numpy()). + fn codebook(L: *Loader, t: Tensor) ![]f32 { + if (t.dtype != .bf16 or t.rank != 2 or t.dim(1) != selector_rank) return error.UnexpectedDraftTensor; + const out = try L.gpa.alloc(f32, t.dim(0) * selector_rank); + for (out, 0..) |*o, i| o.* = bf16Value(std.mem.readInt(u16, t.bytes[2 * i ..][0..2], .little)); + return out; + } +}; + +/// The drafter at `dir`, and the target head's last span tiled from the target checkpoint at `target_dir`. +pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, target_dir: []const u8) !Weights { + var w: Weights = .{ .gpa = gpa }; + errdefer w.deinit(); + var L: Loader = .{ .gpa = gpa, .ops = ops, .w = &w }; + defer { + L.words.deinit(gpa); + L.scales.deinit(gpa); + L.biases.deinit(gpa); + if (L.staging) |*b| b.free(); + } + var ck = try core.Checkpoint.openModel(gpa, io, dir); + defer ck.close(); + for (&w.layers, 0..) |*l, i| { + const q = try Loader.get(&ck, "layers.{d}.self_attn.q_proj.weight", .{i}); + const k = try Loader.get(&ck, "layers.{d}.self_attn.k_proj.weight", .{i}); + const v = try Loader.get(&ck, "layers.{d}.self_attn.v_proj.weight", .{i}); + l.qkv = try L.quantized(&.{ q, k, v }, hidden); + l.kv = try L.quantized(&.{ k, v }, hidden); + l.o = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.self_attn.o_proj.weight", .{i})}, heads * head_dim); + l.q_norm = try L.raw(try Loader.get(&ck, "layers.{d}.self_attn.q_norm.weight", .{i})); + l.k_norm = try L.raw(try Loader.get(&ck, "layers.{d}.self_attn.k_norm.weight", .{i})); + l.in_norm = try L.raw(try Loader.get(&ck, "layers.{d}.input_layernorm.weight", .{i})); + l.post_norm = try L.raw(try Loader.get(&ck, "layers.{d}.post_attention_layernorm.weight", .{i})); + l.attn_proj = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.attention_conv.kernel_projection.weight", .{i})}, hidden); + l.attn_base = try L.raw(try Loader.get(&ck, "layers.{d}.attention_conv.base_kernel", .{i})); + l.mlp_proj = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.mlp_conv.kernel_projection.weight", .{i})}, hidden); + l.mlp_base = try L.raw(try Loader.get(&ck, "layers.{d}.mlp_conv.base_kernel", .{i})); + l.gate = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.mlp.gate_proj.weight", .{i})}, hidden); + l.up = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.mlp.up_proj.weight", .{i})}, hidden); + const down = try Loader.get(&ck, "layers.{d}.mlp.down_proj.weight", .{i}); + l.down = try L.quantized(&.{down}, down.dim(1)); + } + const fc = try ck.get("fc.weight"); + w.fc = try L.quantized(&.{fc}, fc.dim(1)); + w.hidden_norm = try L.raw(try ck.get("hidden_norm.weight")); + w.norm = try L.raw(try ck.get("norm.weight")); + w.select = try L.quantized(&.{try ck.get("candidate_selector.hidden_projection.weight")}, hidden); + w.pred = try L.codebook(try ck.get("candidate_selector.predecessor_codebook")); + w.succ = try L.codebook(try ck.get("candidate_selector.successor_codebook")); + if (ck.unused() != 0) return error.UnusedDraftTensors; + // dflash2's sub-head: rows() of the tiled head copies a span off the 64-row tile grid, packed on its own + var tk = try core.Checkpoint.openModelPrefix(gpa, io, target_dir, "language_model.lm_head"); + defer tk.close(); + const hw = try tk.get("language_model.lm_head.weight"); + const hs = try tk.get("language_model.lm_head.scales"); + const hb = try tk.get("language_model.lm_head.biases"); + const a = spans[1][0]; + const n = spans[1][1] - a; + const k8 = hidden / 8; + const kg = hidden / 64; + // mapped tensors may sit at odd offsets: the rows go through aligned host arrays + try L.words.resize(gpa, n * k8); + try L.scales.resize(gpa, n * kg); + try L.biases.resize(gpa, n * kg); + @memcpy(std.mem.sliceAsBytes(L.words.items), hw.bytes[a * k8 * 4 ..][0 .. n * k8 * 4]); + @memcpy(std.mem.sliceAsBytes(L.scales.items), hs.bytes[a * kg * 2 ..][0 .. n * kg * 2]); + @memcpy(std.mem.sliceAsBytes(L.biases.items), hb.bytes[a * kg * 2 ..][0 .. n * kg * 2]); + w.head_tail = try L.tile(L.words.items, L.scales.items, L.biases.items, n, hidden); + return w; +} + +test "quantize4 rounds as torch does" { + // one group: values 0..63 / 4 -> lo 0, scale bf16(63/4/15 = 1.05), each q round-half-even of v / 1.046875 + var src: [64 * 2]u8 = undefined; + for (0..64) |j| std.mem.writeInt(u16, src[2 * j ..][0..2], toBf16(@as(f32, @floatFromInt(j)) / 4.0), .little); + var words: [8]u32 = undefined; + var scales: [1]u16 = undefined; + var biases: [1]u16 = undefined; + quantize4(&src, 1, 64, &words, &scales, &biases); + try std.testing.expectEqual(toBf16(63.0 / 4.0 / 15.0), scales[0]); + try std.testing.expectEqual(@as(u16, 0), biases[0]); + try std.testing.expectEqual(@as(u32, 15), words[7] >> 28); + try std.testing.expectEqual(roundEven(2.5), 2.0); + try std.testing.expectEqual(roundEven(3.5), 4.0); +} diff --git a/zig/src/families/qwen27/cuda/draft_policy.zig b/zig/src/families/qwen27/cuda/draft_policy.zig new file mode 100644 index 0000000000..83888d435a --- /dev/null +++ b/zig/src/families/qwen27/cuda/draft_policy.zig @@ -0,0 +1,122 @@ +//! draft_tree.best_first on the host: which of DFlash2's candidates a round verifies, and where each hangs. + +const std = @import("std"); +const lanes = @import("lanes"); + +pub const branch = 4; +const edge_weight = 0.6; +const noise_weight = 0.7; +const scale = 1.5; +pub const rank = 256; // the selector's codebook width +pub const top = 16; // candidates a depth + +/// A drafted block's candidates: each depth's 16 token ids, their logits (unary) and the selector's projection. +pub const Candidates = struct { ids: []const u32, unary: []const f64, projected: []const f64, depths: usize }; + +/// The tree: nodes in pop order (parents first), each node's parent (-1: hangs from the anchor), path scores. +pub const Tree = struct { tokens: std.ArrayList(u32) = .empty, parents: std.ArrayList(i32) = .empty, scores: std.ArrayList(f64) = .empty }; + +const Item = struct { score: f64, parent: i32, token: u32, depth: usize }; + +fn before(_: void, a: Item, b: Item) std.math.Order { + // heapq's tuple order: score, then parent, then token, then depth + if (a.score != b.score) return std.math.order(a.score, b.score); + if (a.parent != b.parent) return std.math.order(a.parent, b.parent); + if (a.token != b.token) return std.math.order(a.token, b.token); + return std.math.order(a.depth, b.depth); +} + +/// best_first: expand the anchor's candidates, then pop the best path score until `max_nodes` are placed. +pub fn bestFirst(gpa: std.mem.Allocator, c: Candidates, pred: []const f32, succ: []const f32, anchor: u32, max_nodes: usize, sampling: ?lanes.Sampling, first_position: u64, out: *Tree) !void { + out.tokens.clearRetainingCapacity(); + out.parents.clearRetainingCapacity(); + out.scores.clearRetainingCapacity(); + const temp: f64 = if (sampling) |s| @max(s.temperature, 1e-6) else 1.0; + var heap: std.PriorityQueue(Item, void, before) = .empty; + defer heap.deinit(gpa); + const Ctx = struct { + gpa: std.mem.Allocator, + c: Candidates, + pred: []const f32, + succ: []const f32, + temp: f64, + sampling: ?lanes.Sampling, + first_position: u64, + heap: *std.PriorityQueue(Item, void, before), + + fn expand(x: @This(), token: u32, depth: usize, parent: i32, path: f64) !void { + var values: [top]f64 = undefined; + const p = x.pred[@as(usize, token) * rank ..][0..rank]; + const proj = x.c.projected[depth * rank ..][0..rank]; + var weighted: [rank]f64 = undefined; + for (&weighted, p, proj) |*wgt, a, b| wgt.* = @as(f64, a) * b; + for (&values, 0..) |*v, i| { + const cand = x.c.ids[depth * top + i]; + const s = x.succ[@as(usize, cand) * rank ..][0..rank]; + var edge: f64 = 0; + for (s, weighted) |a, b| edge += @as(f64, a) * b; + v.* = (x.c.unary[depth * top + i] + edge_weight * edge) / x.temp; + if (x.sampling) |smp| v.* += noise_weight * -@log(-@log(lanes.sampling.uniform(smp.seed, x.first_position + depth, cand))); + v.* /= scale; + } + var most = values[0]; + for (values[1..]) |v| most = @max(most, v); + var total: f64 = 0; + for (&values) |*v| { + v.* -= most; + total += @exp(v.*); + } + const log_total = @log(total); + var order: [top]usize = undefined; + for (&order, 0..) |*o, i| o.* = i; + std.mem.sort(usize, &order, &values, struct { + fn more(vals: *const [top]f64, a: usize, b: usize) bool { + return vals[a] > vals[b] or (vals[a] == vals[b] and a < b); + } + }.more); + for (order[0..branch]) |i| { + const logp = values[i] - log_total; + if (!std.math.isFinite(logp)) break; + try x.heap.push(x.gpa, .{ .score = path - logp, .parent = parent, .token = x.c.ids[depth * top + i], .depth = depth }); + } + } + }; + const ctx: Ctx = .{ .gpa = gpa, .c = c, .pred = pred, .succ = succ, .temp = temp, .sampling = sampling, .first_position = first_position, .heap = &heap }; + try ctx.expand(anchor, 0, -1, 0.0); + while (heap.count() > 0 and out.tokens.items.len < max_nodes) { + const it = heap.pop().?; + const me: i32 = @intCast(out.tokens.items.len); + try out.tokens.append(gpa, it.token); + try out.parents.append(gpa, it.parent); + try out.scores.append(gpa, it.score); + if (it.depth + 1 < c.depths) try ctx.expand(it.token, it.depth + 1, me, it.score); + } +} + +test "best_first pops by path score, parents before children, ties by parent" { + const gpa = std.testing.allocator; + const vocab = 32; + const pred = try gpa.alloc(f32, vocab * rank); + defer gpa.free(pred); + const succ = try gpa.alloc(f32, vocab * rank); + defer gpa.free(succ); + @memset(pred, 0); + @memset(succ, 0); + var ids: [2 * top]u32 = undefined; + var unary: [2 * top]f64 = undefined; + for (0..2) |d| for (0..top) |i| { + ids[d * top + i] = @intCast(i); + unary[d * top + i] = -@as(f64, @floatFromInt(i)); + }; + const projected: [2 * rank]f64 = @splat(0); + var tree: Tree = .{}; + defer { + tree.tokens.deinit(gpa); + tree.parents.deinit(gpa); + tree.scores.deinit(gpa); + } + try bestFirst(gpa, .{ .ids = &ids, .unary = &unary, .projected = &projected, .depths = 2 }, pred, succ, 3, 5, null, 100, &tree); + // logp_i = -i / 1.5 - ln(sum): the anchor's 0 and 1 (score 0.72, 1.39) come before 0's child 0 (1.44) + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 0, 2, 1 }, tree.tokens.items); + try std.testing.expectEqualSlices(i32, &.{ -1, -1, 0, -1, 0 }, tree.parents.items); +} diff --git a/zig/src/families/qwen27/cuda/drafts.zig b/zig/src/families/qwen27/cuda/drafts.zig new file mode 100644 index 0000000000..02e3659524 --- /dev/null +++ b/zig/src/families/qwen27/cuda/drafts.zig @@ -0,0 +1,103 @@ +//! DFlash2 for a shared round's streams (multi.py's drafter halves): copies first, else every block in one batch. + +const std = @import("std"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const kern = @import("kernels.zig"); +const dr = @import("draft.zig"); +const dl = @import("draft_load.zig"); +const lone = @import("lone.zig"); + +const bf = 2; +pub const taps_width = dl.taps.len * dl.hidden; +/// A shared window's drafts at most (MultiDecoder's max_rows - 1). +pub const max_nodes = st.max_rows - 1; + +pub const Kind = enum { none, copy, tree }; + +/// One stream's drafting: its drafter context, its copy index, and the drafts it holds for its next window. +pub const Stream = struct { + gpa: std.mem.Allocator, + ctx: dr.Context, + copies: lone.CopyIndex, + kind: Kind = .none, + tokens: std.ArrayList(u32) = .empty, + parents: std.ArrayList(i32) = .empty, // each draft's parent draft (-1: under the pending row) + scores: std.ArrayList(f64) = .empty, // each draft's path score (best_first's; 0 for a copy) + + pub fn init(gpa: std.mem.Allocator, ctx: dr.Context) Stream { + return .{ .gpa = gpa, .ctx = ctx, .copies = .{ .gpa = gpa } }; + } + + pub fn deinit(x: *Stream) void { + x.ctx.deinit(); + x.copies.deinit(); + x.tokens.deinit(x.gpa); + x.parents.deinit(x.gpa); + x.scores.deinit(x.gpa); + } + + fn clear(x: *Stream) void { + x.kind = .none; + x.tokens.clearRetainingCapacity(); + x.parents.clearRetainingCapacity(); + x.scores.clearRetainingCapacity(); + } +}; + +/// A stream asking for its next drafts: its context through the pending token, and its sampling. +pub const Ask = struct { x: *Stream, context: []const u32, sampling: ?lanes.Sampling }; + +/// _mode, launch_blocks and finish_tree: a copied continuation where the context repeats, else a DFlash2 tree. +pub fn propose(d: *dr.DFlash2, asks: []const Ask) !void { + var blocks: [st.max_streams]dr.Block = undefined; + var which: [st.max_streams]usize = undefined; + var n: usize = 0; + for (asks, 0..) |a, k| { + const x = a.x; + x.clear(); + const copied = try x.copies.propose(a.context, max_nodes); + if (copied.len > 0) { + x.kind = .copy; + try x.tokens.appendSlice(x.gpa, copied); + for (0..copied.len) |r| { + try x.parents.append(x.gpa, @as(i32, @intCast(r)) - 1); + try x.scores.append(x.gpa, 0); + } + } else if (x.ctx.len > 0) { + blocks[n] = .{ .ctx = &x.ctx, .pending = a.context[a.context.len - 1] }; + which[n] = k; + n += 1; + } + } + if (n == 0) return; + try d.launchMany(blocks[0..n], @min(dr.block, max_nodes + 1)); + for (blocks[0..n], which[0..n], 0..) |b, k, j| { + const a = asks[k]; + try d.finish(j, b.pending, a.context.len, max_nodes, a.sampling, &d.tree); + a.x.kind = .tree; + try a.x.tokens.appendSlice(a.x.gpa, d.tree.tokens.items); + try a.x.parents.appendSlice(a.x.gpa, d.tree.parents.items); + try a.x.scores.appendSlice(a.x.gpa, d.tree.scores.items); + } +} + +/// A stream's kept rows of the last round (rows of the round's taps, in path order). +pub const Kept = struct { x: *Stream, rows: []const u32 }; + +/// add_taps_streams: every stream's kept rows' taps gathered after the round's rows, then absorbed in one batch. +pub fn absorb(d: *dr.DFlash2, ops: kern.Ops, taps: u64, copy_items: u64, kept: []const Kept) !void { + var items: std.ArrayList(kern.Copy) = .empty; + defer items.deinit(d.gpa); + var absorbs: [st.max_streams]dr.Absorb = undefined; + const row = taps_width * bf; + const gathered = taps + st.round_rows * row; + for (kept, 0..) |k, j| { + for (k.rows) |r| try items.append(d.gpa, .{ .dst = gathered + items.items.len * row, .src = taps + r * row, .bytes = row }); + absorbs[j] = .{ .ctx = &k.x.ctx, .rows = k.rows.len }; + } + if (items.items.len == 0) return; + try ops.upload(copy_items, std.mem.sliceAsBytes(items.items)); + try ops.copies(copy_items, items.items.len); + try d.absorbMany(absorbs[0..kept.len], gathered); +} diff --git a/zig/src/families/qwen27/cuda/engine.zig b/zig/src/families/qwen27/cuda/engine.zig new file mode 100644 index 0000000000..91b8103d2c --- /dev/null +++ b/zig/src/families/qwen27/cuda/engine.zig @@ -0,0 +1,192 @@ +//! The 27B's CUDA engine for one stream: the weights, kernels and scratch, prefill and greedy serial decode. + +const std = @import("std"); +const cuda = @import("cuda"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const vision = @import("vision.zig"); +const wts = @import("weights.zig"); +const Forward = @import("forward.zig").Forward; +const Part = @import("forward.zig").Part; + +/// prefill.CHUNK: a prompt chunk's rows (prompt_rows on a GPU of 80 GB or more). +pub const prompt_rows = 4096; + +/// prefill.chunks: even chunks of at most `size` rows of [start, end); any bounds give the same bits. +pub fn chunkBounds(start: usize, end: usize, size: usize, j: usize) [2]usize { + const n = (end - start + size - 1) / size; + return .{ start + (end - start) * j / n, start + (end - start) * (j + 1) / n }; +} + +/// Chunks from `from`: even splits, or with a prompt cache the zero-anchored grid so resumed passes cut alike. +pub const Chunks = struct { + len: usize, + grid: bool, + at: usize, + j: usize = 0, + + pub fn init(len: usize, from: usize, grid: bool) Chunks { + return .{ .len = len, .grid = grid, .at = from }; + } + + pub fn next(x: *Chunks) ?[2]usize { + if (x.at >= x.len) return null; + const b: [2]usize = if (x.grid) .{ x.at, @min(x.len, x.at - x.at % prompt_rows + prompt_rows) } else chunkBounds(0, x.len, prompt_rows, x.j); + x.at = b[1]; + x.j += 1; + return b; + } +}; + +/// A state the cache may resume: a grid point inside the prompt. +pub fn resumable(from: usize, len: usize) bool { + return from > 0 and from < len and from % prompt_rows == 0; +} + +/// Where a prompt pass stops to let the cache copy its state (ascending grid points), and who copies it. +pub const Keep = struct { + at: []const u32, + ctx: *anyopaque, + call: *const fn (ctx: *anyopaque, at: u32) void, + + /// Call the keep for a chunk that ended at `end`. + pub fn after(k: ?Keep, end: usize) void { + const x = k orelse return; + for (x.at) |m| if (m == end) x.call(x.ctx, m); + } +}; + +pub const Options = struct { context: usize, kv8: bool = false }; + +pub const Engine = struct { + gpa: std.mem.Allocator, + ctx: *const cuda.Context, + s: cuda.Stream, + k: kern.Kernels, + w: wts.Weights, + scratch: st.Scratch, + context: usize, + kv8: bool, // --kv-cache fp8: every stream's attention caches e4m3 with a scale a row + grid: bool = false, // a prompt cache: prompts in zero-anchored chunks (Chunks), not even splits + + pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: []const u8, o: Options) !*Engine { + const cfg = try c.Config.read(gpa, io, dir); + const g = cfg.g; + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + e.gpa = gpa; + e.ctx = ctx; + e.context = o.context; + e.kv8 = o.kv8; + e.s = try cuda.Stream.init(ctx.d, true); + errdefer e.s.deinit(); + e.k = try kern.Kernels.load(gpa, io, ctx, kernels, g.linear_v_heads); + errdefer e.k.deinit(); + e.w = try wts.load(gpa, io, e.ops(), dir, cfg); + errdefer e.w.deinit(); + e.scratch = try st.Scratch.init(gpa, ctx.d, g, prompt_rows, o.context); + errdefer e.scratch.deinit(); + try e.s.synchronize(); + return e; + } + + pub fn deinit(e: *Engine) void { + e.scratch.deinit(); + e.w.deinit(); + e.k.deinit(); + e.s.deinit(); + e.gpa.destroy(e); + } + + pub fn ops(e: *Engine) kern.Ops { + return .{ .k = &e.k, .s = e.s }; + } + + pub fn forward(e: *Engine) Forward { + return .{ .gpa = e.gpa, .w = &e.w, .ops = e.ops(), .t = .{ .set = &e.k.triton, .s = e.s }, .s = &e.scratch }; + } + + /// A stream's state for `capacity` positions (its caches, recurrences and conv windows), empty. + pub fn sequence(e: *Engine, capacity: usize) !st.Seq { + return st.Seq.init(e.gpa, e.ops(), e.w.g, capacity, e.kv8); + } + + /// Attention's partials for `streams` streams of the engine's context in one round. + pub fn fit(e: *Engine, streams: usize) !void { + try e.s.synchronize(); + try e.scratch.fitPartials(e.ctx.d, e.w.g, streams * st.Scratch.streamPartRows(e.context)); + } + + /// prefill_state from an empty state: the prompt in even chunks of at most `prompt_rows`, its last row normed. + pub fn prefill(e: *Engine, seq: *st.Seq, prompt: []const u32) !void { + return e.prefillMedia(seq, prompt, null); + } + + /// prefill with an image prompt's rows and positions (null: text); its decode offset stays on the stream. + pub fn prefillMedia(e: *Engine, seq: *st.Seq, prompt: []const u32, media: ?*const vision.Media) !void { + return e.prefillFrom(seq, prompt, 0, media, null); + } + + /// The prompt from `from` (0, or a grid point its state was restored at), keeping states at `keep`'s marks. + pub fn prefillFrom(e: *Engine, seq: *st.Seq, prompt: []const u32, from: usize, media: ?*const vision.Media, keep: ?Keep) !void { + if (prompt.len == 0) return error.EmptyPrompt; + if (prompt.len >= seq.capacity) return error.PromptTooLong; + if (from == 0) try seq.reset(e.ops(), e.w.g) else if (from != seq.pos or !resumable(from, prompt.len)) return error.BadReuse; + seq.media = media; + defer seq.media = null; + var f = e.forward(); + var it = Chunks.init(prompt.len, from, e.grid); + while (it.next()) |b| { + try f.chunk(prompt[b[0]..b[1]], seq, b[1] == prompt.len); + Keep.after(keep, b[1]); + } + if (media) |m| seq.rope_delta = m.delta; + } + + pub fn decode(e: *Engine, seq: *st.Seq, pending: u32, count: usize, out: *std.ArrayList(u32)) !void { + var f = e.forward(); + try out.append(e.gpa, pending); + var pick: [1]u32 = undefined; + while (out.items.len < count and !e.w.isEos(out.items[out.items.len - 1])) { + const last = out.items[out.items.len - 1]; + const part = [_]Part{.{ .seq = seq, .tokens = &.{last} }}; + try f.round(&part); + try f.picks(1, &pick); + try f.commit(&part, &.{&.{0}}); + try out.append(e.gpa, pick[0]); + } + } + + /// The prompt, then up to `max_tokens` greedy tokens (the first included), as generate(draft=False) gives them. + pub fn generate(e: *Engine, seq: *st.Seq, prompt: []const u32, max_tokens: usize, out: *std.ArrayList(u32)) !void { + const room = @min(max_tokens, seq.capacity - prompt.len); + try e.prefill(seq, prompt); + var f = e.forward(); + try f.head(seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + try e.decode(seq, pick[0], @max(1, room), out); + } +}; + +test "a cached prompt cuts the zero-anchored grid, resumed or not" { + var it = Chunks.init(9000, 0, true); + try std.testing.expectEqual([2]usize{ 0, 4096 }, it.next().?); + try std.testing.expectEqual([2]usize{ 4096, 8192 }, it.next().?); + try std.testing.expectEqual([2]usize{ 8192, 9000 }, it.next().?); + try std.testing.expectEqual(@as(?[2]usize, null), it.next()); + var resumed = Chunks.init(9000, 4096, true); + try std.testing.expectEqual([2]usize{ 4096, 8192 }, resumed.next().?); + var even = Chunks.init(5078, 0, false); + try std.testing.expectEqual([2]usize{ 0, 2539 }, even.next().?); + try std.testing.expectEqual([2]usize{ 2539, 5078 }, even.next().?); + try std.testing.expect(resumable(4096, 5000) and !resumable(4096, 4096) and !resumable(3000, 5000) and !resumable(0, 5000)); +} + +test "prefill.chunks splits evenly" { + try std.testing.expectEqual([2]usize{ 0, 2539 }, chunkBounds(0, 5078, 4096, 0)); + try std.testing.expectEqual([2]usize{ 2539, 5078 }, chunkBounds(0, 5078, 4096, 1)); + try std.testing.expectEqual([2]usize{ 0, 40 }, chunkBounds(0, 40, 4096, 0)); +} diff --git a/zig/src/families/qwen27/cuda/forward.zig b/zig/src/families/qwen27/cuda/forward.zig new file mode 100644 index 0000000000..e188647925 --- /dev/null +++ b/zig/src/families/qwen27/cuda/forward.zig @@ -0,0 +1,500 @@ +//! The 27B's forward on CUDA: verify rounds (tree_forward, multi_tree_forward), their commit, and prompt chunks. + +const std = @import("std"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const wts = @import("weights.zig"); +const rnd = @import("round.zig"); +const vision = @import("vision.zig"); + +const bf = 2; +pub const Part = rnd.Part; +/// The target layers DFlash2 reads (dflash_config.target_layer_ids). +pub const tap_layers = [_]usize{ 5, 19, 33, 47, 61 }; + +pub const Forward = struct { + gpa: std.mem.Allocator, + w: *const wts.Weights, + ops: kern.Ops, + t: tri.Tri, + s: *st.Scratch, + dump: ?Dump = null, // a debugging copy of every norm's (h, y) rows, as capture.py's hook writes them + taps: ?u64 = null, // rows of the drafter's five layer taps (5 x hidden bf16), written by round and chunk + + pub const Dump = struct { io: std.Io, dir: []const u8, n: usize = 0, rows: usize = 0 }; + + fn g(f: *const Forward) c.Geometry { + return f.w.g; + } + + fn gdnShape(f: *const Forward) tri.Gdn { + const g_ = f.g(); + return .{ .c = g_.convDim(), .kh = g_.linear_k_heads, .vh = g_.linear_v_heads, .dk = c.linear_dim, .keep = c.conv_taps - 1 }; + } + + fn heads(f: *const Forward) kern.Heads { + return .{ .hk = f.g().linear_k_heads, .hv = f.g().linear_v_heads, .dv = c.linear_dim }; + } + + fn attnShape(f: *const Forward) tri.Attn { + return .{ .heads = f.g().query_heads, .kv_heads = f.g().kv_heads, .dim = c.head_dim, .half = c.rotary_dim / 2 }; + } + + fn gpu(f: *const Forward) vision.Gpu { + return .{ .d = f.ops.k.d, .s = f.ops.s, .discrete = f.ops.k.discrete }; + } + + fn upload32(f: *Forward, dst: u64, values: []const i32) !void { + try f.ops.upload(dst, std.mem.sliceAsBytes(values)); + try f.ops.s.synchronize(); // the host copy must outlive the async upload + } + + /// add_rmsnorm into the scratch's other residual buffer; returns the residual stream's new home. + fn norm(f: *Forward, x: u64, r: ?u64, weight: u64, rows: usize) !u64 { + const out = if (r == null) x else if (x == f.s.x) f.s.h else f.s.x; + try f.t.addRmsnorm(x, r, weight, out, f.s.y, f.s.xs, rows, f.g().hidden, c.eps); + if (f.dump) |*d| try f.saveRows(d, out, f.s.y, rows); + return out; + } + + /// Layer `i`'s tap, when the drafter reads it: (x + pending) of the call's rows into the taps buffer. + fn tapLayer(f: *Forward, i: usize, x: u64, rows: usize) !void { + const out = f.taps orelse return; + const j = std.mem.indexOfScalar(usize, &tap_layers, i) orelse return; + const h = f.g().hidden; + try f.ops.tap(x, f.s.pending, out, rows, h, tap_layers.len * h, j * h); + } + + fn saveRows(f: *Forward, d: *Dump, h: u64, y: u64, rows: usize) !void { + const bytes = try f.gpa.alloc(u8, rows * f.g().hidden * bf); + defer f.gpa.free(bytes); + for ([_]u64{ h, y }, [_][]const u8{ "h", "y" }) |src, name| { + try f.ops.download(bytes, src); + try f.ops.s.synchronize(); + var buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, "{s}/{d:0>3}_{s}.bin", .{ d.dir, d.n, name }); + try std.Io.Dir.cwd().writeFile(d.io, .{ .sub_path = path, .data = bytes }); + } + d.n += 1; + } + + /// The window of one stream at its position (tree_forward): logits (rows, vocab) bf16 in the scratch, records kept. + pub fn window(f: *Forward, tokens: []const u32, seq: *st.Seq) !void { + return f.round(&.{.{ .seq = seq, .tokens = tokens }}); + } + + /// Several streams' chain windows in one forward (multi_tree_forward; one stream: tree_forward), rows in order. + pub fn round(f: *Forward, parts: []const Part) !void { + const s = f.s; + const g_ = f.g(); + const w = f.w; + const r = try rnd.stage(f.gpa, f.ops, f.t, s, g_, parts); + const W = r.rows; + try f.t.embed(r.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); + var x = s.x; + var pending: ?u64 = null; + var lin: usize = 0; + var att: usize = 0; + for (w.layers, 0..) |layer, i| { + x = try f.norm(x, pending, layer.input_norm, W); + switch (layer.mixer) { + .delta => |d| { + const rec = s.records[i]; + try f.ops.dense(s.y, s.xs, d.qkv, rec.qkv, W); + try f.ops.dense(s.y, s.xs, d.z, s.z, W); + try f.ops.dense(s.y, s.xs, d.b, s.b, W); + try f.ops.dense(s.y, s.xs, d.a, s.a, W); + const sid: ?u64 = if (r.multi) r.sids else null; + try f.t.gdnPre(rec.qkv, r.conv(parts, s, g_, i, lin), d.conv, r.windows, sid, s.a, s.b, d.a_log, d.dt_bias, rec.q, rec.k, rec.v, rec.g, rec.beta, W, f.gdnShape()); + const state = if (r.multi) 0 else parts[0].seq.rec[i]; + const table = if (r.multi) r.table(lin) else 0; + try f.ops.gdnTree(rec.q, rec.k, rec.v, rec.g, rec.beta, state, table, if (r.multi) r.starts else 0, r.plan, s.yr, W, r.streams, r.slots, r.most, f.heads()); + try f.t.gatedNorm(s.yr, s.z, d.norm, s.gated, s.gated_xs, W, g_.linear_v_heads, c.linear_dim, c.eps); + try f.ops.dense(s.gated, s.gated_xs, d.out, s.r, W); + lin += 1; + }, + .attention => |a| { + const rec = s.attn_records[i]; + try f.ops.dense(s.y, s.xs, a.q, s.qg, W); + try f.ops.dense(s.y, s.xs, a.k, s.key, W); + try f.ops.dense(s.y, s.xs, a.v, rec.v, W); + try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, r.pos, w.inv_freq, s.q_rot, rec.k, W, f.attnShape(), c.eps); + const part: tri.Tri.Partials = .{ .o = s.part_o, .m = s.part_m, .l = s.part_l }; + if (r.kv8) try f.t.attention8(s.q_rot, rec.k, rec.v, s.origin, r.offsets(i, att), r.attn, part, s.attn, f.attnShape()) else try f.t.attention(s.q_rot, rec.k, rec.v, s.origin, r.offsets(i, att), r.attn, part, s.attn, f.attnShape()); + try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); + try f.ops.dense(s.gated, s.gated_xs, a.o, s.r, W); + att += 1; + }, + } + x = try f.norm(x, s.r, layer.post_norm, W); + try f.ops.dense(s.y, s.xs, layer.gate, s.gate, W); + try f.ops.dense(s.y, s.xs, layer.up, s.up, W); + try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); + try f.ops.dense(s.act, s.act_xs, layer.down, s.pending, W); + pending = s.pending; + try f.tapLayer(i, x, W); + } + const spare = if (x == s.x) s.h else s.x; + try f.t.addRmsnorm(x, pending, w.norm, spare, s.last_h, s.last_xs, W, g_.hidden, c.eps); + if (f.dump) |*d| try f.saveRows(d, spare, s.last_h, W); + try f.ops.dense(s.last_h, s.last_xs, w.head, s.logits, W); + } + + /// commit_streams after a round over `parts`: each stream keeps the window rows of its accepted path. + pub fn commit(f: *Forward, parts: []const Part, paths: []const []const u32) !void { + const s = f.s; + const g_ = f.g(); + const S = parts.len; + var width: usize = 0; + for (parts, paths) |p, path| { + if (path.len < 1 or path.len > p.tokens.len) return error.InvalidQwenCommit; + for (path) |row| if (row >= p.tokens.len) return error.InvalidQwenCommit; + width += p.tokens.len; + } + // gdn.replay_table: each DeltaNet layer's k, v, g, beta, then each stream's state of each layer + var table: std.ArrayList(u64) = .empty; + defer table.deinit(f.gpa); + var layers: usize = 0; + for (0..g_.layers) |i| if (c.linear(i)) { + const rc = s.records[i]; + try table.appendSlice(f.gpa, &.{ rc.k, rc.v, rc.g, rc.beta }); + layers += 1; + }; + for (parts) |p| for (0..g_.layers) |i| if (c.linear(i)) try table.append(f.gpa, p.seq.rec[i]); + try f.ops.upload(s.replay_table, std.mem.sliceAsBytes(table.items)); + // path_indices: each stream's accepted rows (round rows) padded to the round's width, then its count + var rows: std.ArrayList(i32) = .empty; + defer rows.deinit(f.gpa); + var base: usize = 0; + for (parts, paths) |p, path| { + for (0..width) |j| try rows.append(f.gpa, if (j < path.len) @intCast(base + path[j]) else 0); + try rows.append(f.gpa, @intCast(path.len)); + base += p.tokens.len; + } + try f.ops.upload(s.replay_rows, std.mem.sliceAsBytes(rows.items)); + try f.ops.s.synchronize(); + try f.ops.gdnReplay(s.replay_table, layers, S, s.replay_rows, width + 1, s.replay_rows + width * 4, width + 1, f.heads()); + const row = g_.convDim() * bf; + const keep = c.conv_taps - 1; + const kv = g_.kvInner() * bf; + // conv rows: the last three of [committed | accepted rows]; old ones saved first, then written with the rest + var save: std.ArrayList(kern.Copy) = .empty; + defer save.deinit(f.gpa); + var write: std.ArrayList(kern.Copy) = .empty; + defer write.deinit(f.gpa); + var quant: std.ArrayList(kern.Quant) = .empty; // kv8: the accepted keys and values, quantized into the caches + defer quant.deinit(f.gpa); + const hk = g_.kv_heads; + base = 0; + for (parts, paths, 0..) |p, path, k| { + const n = path.len; + var lin: usize = 0; + for (0..g_.layers) |i| { + if (c.linear(i)) { + const old = s.conv_old + (k * g_.layers + lin) * keep * row; + const stay = keep -| n; // committed rows that stay: old[n..3) go to new[0..3-n) + if (stay > 0) { + try save.append(f.gpa, .{ .dst = old, .src = p.seq.conv[i] + n * row, .bytes = stay * row }); + try write.append(f.gpa, .{ .dst = p.seq.conv[i], .src = old, .bytes = stay * row }); + } + for (path[n - (keep - stay) ..], stay..) |acc, j| try write.append(f.gpa, .{ .dst = p.seq.conv[i] + j * row, .src = s.records[i].qkv + (base + acc) * row, .bytes = row }); + lin += 1; + } else { + for (path, 0..) |acc, j| { + const pos = p.seq.pos + j; + if (p.seq.kv8) { + try quant.append(f.gpa, .{ .src = s.attn_records[i].k + (base + acc) * kv, .dst = p.seq.keys[i] + pos * kv / bf, .scale = p.seq.kscale[i] + pos * hk * 4, .rows = hk }); + try quant.append(f.gpa, .{ .src = s.attn_records[i].v + (base + acc) * kv, .dst = p.seq.values[i] + pos * kv / bf, .scale = p.seq.vscale[i] + pos * hk * 4, .rows = hk }); + continue; + } + const at = pos * kv; + try write.append(f.gpa, .{ .dst = p.seq.keys[i] + at, .src = s.attn_records[i].k + (base + acc) * kv, .bytes = kv }); + try write.append(f.gpa, .{ .dst = p.seq.values[i] + at, .src = s.attn_records[i].v + (base + acc) * kv, .bytes = kv }); + } + } + } + base += p.tokens.len; + p.seq.pos += n; + } + const second = s.copy_items + st.copy_items * @sizeOf(kern.Copy); + try f.ops.upload(s.copy_items, std.mem.sliceAsBytes(save.items)); + try f.ops.upload(second, std.mem.sliceAsBytes(write.items)); + try f.ops.copies(s.copy_items, save.items.len); + try f.ops.copies(second, write.items.len); + if (quant.items.len > st.copy_items) return error.InvalidQwenCommit; + try f.ops.upload(s.quant_items, std.mem.sliceAsBytes(quant.items)); + try f.ops.quant(s.quant_items, quant.items.len, hk); + try f.ops.s.synchronize(); // the tables' host copies go when this returns + } + + /// prefill_chunk: `ids` committed at the stream's position; `last` leaves the last row normed, with group_sums. + pub fn chunk(f: *Forward, ids: []const u32, seq: *st.Seq, last: bool) !void { + const W = ids.len; + const s = f.s; + const g_ = f.g(); + const w = f.w; + if (W < 1 or W > s.rows) return error.ChunkTooLong; + if (seq.pos + W > seq.capacity) return error.PromptTooLong; + const p0 = seq.pos; + { + const host = try f.gpa.alloc(i32, W * (2 + c.conv_taps)); + defer f.gpa.free(host); + for (ids, 0..) |tok, r| { + host[r] = @intCast(tok); + // an image prompt's text rows: their three positions are equal, so one row of them is theirs + host[W + r] = if (seq.media) |m| m.pos[p0 + r] else @intCast(p0 + r); + for (0..c.conv_taps) |j| host[2 * W + r * c.conv_taps + j] = @intCast(r + j); + } + try f.upload32(s.ids, host[0..W]); + try f.upload32(s.pos, host[W .. 2 * W]); + try f.upload32(s.windows, host[2 * W ..]); + } + try f.t.embed(s.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); + // rows of an image take the tower's rows, and the chunk's attention their three positions + const media: ?*const vision.Media = if (seq.media) |m| (if (m.hasImage(p0, W)) m else null) else null; + if (media) |m| { + const n = m.src.len; + const host = try f.gpa.alloc(i32, 4 * W); + defer f.gpa.free(host); + @memcpy(host[0..W], m.src[p0..][0..W]); + for (0..3) |a| @memcpy(host[W + a * W ..][0..W], m.pos[a * n + p0 ..][0..W]); + try f.upload32(m.dev.ptr, host); + try m.tower.splice(f.gpu(), s.x, m.features.ptr, m.dev.ptr, W); + } + var x = s.x; + var pending: ?u64 = null; + const kv = g_.kvInner() * bf; + const row = g_.convDim() * bf; + const keep = c.conv_taps - 1; + for (w.layers, 0..) |layer, i| { + x = try f.norm(x, pending, layer.input_norm, W); + switch (layer.mixer) { + .delta => |d| { + try f.ops.prefillDense(s.y, d.qkv, s.qkv, W); + try f.ops.prefillDense(s.y, d.z, s.z, W); + try f.ops.prefillDense(s.y, d.b, s.b, W); + try f.ops.prefillDense(s.y, d.a, s.a, W); + try f.t.gdnPre(s.qkv, seq.conv[i], d.conv, s.windows, null, s.a, s.b, d.a_log, d.dt_bias, s.gq, s.gk, s.gv, s.gg, s.gbeta, W, f.gdnShape()); + // each thread reads its state rows before it writes them: the chain may end in place + try f.ops.gdnPrompt(s.gq, s.gk, s.gv, s.gg, s.gbeta, seq.rec[i], seq.rec[i], s.yr, W, f.heads()); + if (W >= keep) { + try f.ops.copy(seq.conv[i], s.qkv + (W - keep) * row, keep * row); + } else { + try f.ops.copy(s.conv_tmp, seq.conv[i], keep * row); + try f.ops.copy(s.conv_tmp + keep * row, s.qkv, W * row); + try f.ops.copy(seq.conv[i], s.conv_tmp + W * row, keep * row); + } + try f.t.gatedNorm(s.yr, s.z, d.norm, s.gated, s.gated_xs, W, g_.linear_v_heads, c.linear_dim, c.eps); + try f.ops.prefillDense(s.gated, d.out, s.r, W); + }, + .attention => |a| { + try f.ops.prefillDense(s.y, a.q, s.qg, W); + try f.ops.prefillDense(s.y, a.k, s.key, W); + // kv8: the chunk's rotated keys and values go through the prompt buffers, quantized into the caches + const kdst = if (seq.kv8) s.prompt_keys else seq.keys[i] + p0 * kv; + const vdst = if (seq.kv8) s.prompt_values else seq.values[i] + p0 * kv; + try f.ops.prefillDense(s.y, a.v, vdst, W); + if (media) |m| { + const sh = f.attnShape(); + try m.tower.attnPrep(f.gpu(), s.qg, s.key, a.q_norm, a.k_norm, m.dev.ptr + W * 4, w.inv_freq, s.q_rot, kdst, W, .{ .heads = sh.heads, .kv_heads = sh.kv_heads, .dim = sh.dim, .half = sh.half }, c.eps); + } else try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, kdst, W, f.attnShape(), c.eps); + const scale: f32 = @floatCast(std.math.pow(f64, c.head_dim, -0.5)); + if (seq.kv8) { + const hk = g_.kv_heads; + const q = [_]kern.Quant{ + .{ .src = s.prompt_keys, .dst = seq.keys[i] + p0 * kv / bf, .scale = seq.kscale[i] + p0 * hk * 4, .rows = W * hk }, + .{ .src = s.prompt_values, .dst = seq.values[i] + p0 * kv / bf, .scale = seq.vscale[i] + p0 * hk * 4, .rows = W * hk }, + }; + try f.ops.upload(s.quant_items, std.mem.sliceAsBytes(&q)); + try f.ops.quant(s.quant_items, q.len, W * hk); + try f.ops.prefillAttention8(s.q_rot, seq.keys[i], seq.values[i], seq.kscale[i], seq.vscale[i], s.attn, p0, W, g_.query_heads, g_.kv_heads, scale); + } else try f.ops.prefillAttention(s.q_rot, seq.keys[i], seq.values[i], s.attn, p0, W, g_.query_heads, g_.kv_heads, scale); + try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); + try f.ops.prefillDense(s.gated, a.o, s.r, W); + }, + } + x = try f.norm(x, s.r, layer.post_norm, W); + try f.ops.prefillDense(s.y, layer.gate, s.gate, W); + try f.ops.prefillDense(s.y, layer.up, s.up, W); + try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); + try f.ops.prefillDense(s.act, layer.down, s.pending, W); + pending = s.pending; + try f.tapLayer(i, x, W); + } + seq.pos = p0 + W; + if (!last) return; + const at = (W - 1) * g_.hidden * bf; + const spare = if (x == s.x) s.h else s.x; + try f.t.addRmsnorm(x + at, pending.? + at, w.norm, spare, seq.head_in, s.last_xs, 1, g_.hidden, c.eps); + try f.t.groupSums(seq.head_in, seq.head_xs, g_.hidden, 1, g_.hidden); + } + + /// One stream's share of a batched prompt pass: its ids, committed at its position; `last` normalizes its last row. + pub const Piece = struct { ids: []const u32, seq: *st.Seq, last: bool }; + + /// prefill_rows: several streams' prompt chunks in one pass (each stream's conv, DeltaNet and attention its own). + pub fn chunks(f: *Forward, pieces: []const Piece) !void { + const s = f.s; + const g_ = f.g(); + const w = f.w; + const S = pieces.len; + if (S == 0 or S > st.max_streams) return error.InvalidQwenWindows; + var starts: [st.max_streams + 1]usize = undefined; + starts[0] = 0; + for (pieces, 0..) |p, k| { + if (p.ids.len == 0) return error.ChunkTooLong; + if (p.seq.pos + p.ids.len > p.seq.capacity) return error.PromptTooLong; + starts[k + 1] = starts[k] + p.ids.len; + } + const W = starts[S]; + if (W > s.rows) return error.ChunkTooLong; + const keep = c.conv_taps - 1; + const kv = g_.kvInner() * bf; + const row = g_.convDim() * bf; + { + // ids, positions, each row's stream and its conv window: [the streams' kept rows; every prompt row] + const host = try f.gpa.alloc(i32, W * (3 + c.conv_taps)); + defer f.gpa.free(host); + for (pieces, 0..) |p, k| for (p.ids, 0..) |tok, r| { + const at = starts[k] + r; + host[at] = @intCast(tok); + host[W + at] = @intCast(p.seq.pos + r); + host[2 * W + at] = @intCast(k); + for (0..c.conv_taps) |j| host[3 * W + at * c.conv_taps + j] = @intCast(if (r + j < keep) r + j else r + j + starts[k]); + }; + try f.upload32(s.ids, host[0..W]); + try f.upload32(s.pos, host[W .. 2 * W]); + try f.upload32(s.sids, host[2 * W .. 3 * W]); + try f.upload32(s.windows, host[3 * W ..]); + } + // copies the pass needs: every stream's conv rows stacked by DeltaNet layer, then each layer's writes + var items: std.ArrayList(kern.Copy) = .empty; + defer items.deinit(f.gpa); + var lin_n: usize = 0; + for (0..g_.layers) |i| if (c.linear(i)) { + const cat = s.conv_cat + lin_n * st.max_streams * keep * row; + for (pieces, 0..) |p, k| try items.append(f.gpa, .{ .dst = cat + k * keep * row, .src = p.seq.conv[i], .bytes = keep * row }); + lin_n += 1; + }; + const staged = items.items.len; + var at_layer: [256]usize = undefined; // each layer's first write, then the end + var quant: std.ArrayList(kern.Quant) = .empty; // kv8: each attention layer's prompt rows to quantize + defer quant.deinit(f.gpa); + var quant_at: [256]usize = @splat(0); + var quant_rows: usize = 0; + lin_n = 0; + for (0..g_.layers) |i| { + at_layer[i] = items.items.len; + if (c.linear(i)) { + // the last `keep` rows of [kept rows; the stream's prompt rows] + const cat = s.conv_cat + lin_n * st.max_streams * keep * row; + for (pieces, 0..) |p, k| { + const n = p.ids.len; + const o = starts[k]; + if (n >= keep) { + try items.append(f.gpa, .{ .dst = p.seq.conv[i], .src = s.qkv + (o + n - keep) * row, .bytes = keep * row }); + } else { + try items.append(f.gpa, .{ .dst = p.seq.conv[i], .src = cat + (k * keep + n) * row, .bytes = (keep - n) * row }); + try items.append(f.gpa, .{ .dst = p.seq.conv[i] + (keep - n) * row, .src = s.qkv + o * row, .bytes = n * row }); + } + } + lin_n += 1; + } else { + quant_at[i] = quant.items.len; + for (pieces, 0..) |p, k| { + const o = starts[k]; + const n = p.ids.len; + if (p.seq.kv8) { + const hk = g_.kv_heads; + try quant.append(f.gpa, .{ .src = s.prompt_keys + o * kv, .dst = p.seq.keys[i] + p.seq.pos * kv / bf, .scale = p.seq.kscale[i] + p.seq.pos * hk * 4, .rows = n * hk }); + try quant.append(f.gpa, .{ .src = s.prompt_values + o * kv, .dst = p.seq.values[i] + p.seq.pos * kv / bf, .scale = p.seq.vscale[i] + p.seq.pos * hk * 4, .rows = n * hk }); + quant_rows = @max(quant_rows, n * hk); + continue; + } + try items.append(f.gpa, .{ .dst = p.seq.keys[i] + p.seq.pos * kv, .src = s.prompt_keys + o * kv, .bytes = n * kv }); + try items.append(f.gpa, .{ .dst = p.seq.values[i] + p.seq.pos * kv, .src = s.prompt_values + o * kv, .bytes = n * kv }); + } + } + } + quant_at[g_.layers] = quant.items.len; + at_layer[g_.layers] = items.items.len; + if (quant.items.len > st.copy_items) return error.InvalidQwenWindows; + try f.ops.upload(s.quant_items, std.mem.sliceAsBytes(quant.items)); + if (items.items.len > 2 * st.copy_items) return error.InvalidQwenWindows; + try f.ops.upload(s.copy_items, std.mem.sliceAsBytes(items.items)); + try f.ops.copies(s.copy_items, staged); + const item = @sizeOf(kern.Copy); + try f.t.embed(s.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); + var x = s.x; + var pending: ?u64 = null; + lin_n = 0; + for (w.layers, 0..) |layer, i| { + x = try f.norm(x, pending, layer.input_norm, W); + switch (layer.mixer) { + .delta => |d| { + try f.ops.prefillDense(s.y, d.qkv, s.qkv, W); + try f.ops.prefillDense(s.y, d.z, s.z, W); + try f.ops.prefillDense(s.y, d.b, s.b, W); + try f.ops.prefillDense(s.y, d.a, s.a, W); + const cat = s.conv_cat + lin_n * st.max_streams * keep * row; + try f.t.gdnPre(s.qkv, cat, d.conv, s.windows, s.sids, s.a, s.b, d.a_log, d.dt_bias, s.gq, s.gk, s.gv, s.gg, s.gbeta, W, f.gdnShape()); + for (pieces, 0..) |p, k| { + const o = starts[k]; + // each thread reads its state rows before it writes them: the chain may end in place + try f.ops.gdnPrompt(s.gq + o * g_.kInner() * bf, s.gk + o * g_.kInner() * bf, s.gv + o * g_.vInner() * bf, s.gg + o * g_.linear_v_heads * 4, s.gbeta + o * g_.linear_v_heads * 4, p.seq.rec[i], p.seq.rec[i], s.yr + o * g_.vInner() * bf, p.ids.len, f.heads()); + } + try f.ops.copies(s.copy_items + at_layer[i] * item, at_layer[i + 1] - at_layer[i]); + try f.t.gatedNorm(s.yr, s.z, d.norm, s.gated, s.gated_xs, W, g_.linear_v_heads, c.linear_dim, c.eps); + try f.ops.prefillDense(s.gated, d.out, s.r, W); + lin_n += 1; + }, + .attention => |a| { + try f.ops.prefillDense(s.y, a.q, s.qg, W); + try f.ops.prefillDense(s.y, a.k, s.key, W); + try f.ops.prefillDense(s.y, a.v, s.prompt_values, W); + try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, s.prompt_keys, W, f.attnShape(), c.eps); + try f.ops.copies(s.copy_items + at_layer[i] * item, at_layer[i + 1] - at_layer[i]); + try f.ops.quant(s.quant_items + quant_at[i] * @sizeOf(kern.Quant), quant_at[i + 1] - quant_at[i], quant_rows); + const scale: f32 = @floatCast(std.math.pow(f64, c.head_dim, -0.5)); + const qrow = g_.query_heads * c.head_dim * bf; + for (pieces, 0..) |p, k| if (p.seq.kv8) + try f.ops.prefillAttention8(s.q_rot + starts[k] * qrow, p.seq.keys[i], p.seq.values[i], p.seq.kscale[i], p.seq.vscale[i], s.attn + starts[k] * qrow, p.seq.pos, p.ids.len, g_.query_heads, g_.kv_heads, scale) + else + try f.ops.prefillAttention(s.q_rot + starts[k] * qrow, p.seq.keys[i], p.seq.values[i], s.attn + starts[k] * qrow, p.seq.pos, p.ids.len, g_.query_heads, g_.kv_heads, scale); + try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); + try f.ops.prefillDense(s.gated, a.o, s.r, W); + }, + } + x = try f.norm(x, s.r, layer.post_norm, W); + try f.ops.prefillDense(s.y, layer.gate, s.gate, W); + try f.ops.prefillDense(s.y, layer.up, s.up, W); + try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); + try f.ops.prefillDense(s.act, layer.down, s.pending, W); + pending = s.pending; + try f.tapLayer(i, x, W); + } + const spare = if (x == s.x) s.h else s.x; + for (pieces, 0..) |p, k| { + p.seq.pos += p.ids.len; + if (!p.last) continue; + const at = (starts[k + 1] - 1) * g_.hidden * bf; + try f.t.addRmsnorm(x + at, pending.? + at, w.norm, spare, p.seq.head_in, s.last_xs, 1, g_.hidden, c.eps); + try f.t.groupSums(p.seq.head_in, p.seq.head_xs, g_.hidden, 1, g_.hidden); + } + try f.ops.s.synchronize(); // the copy table's host list goes when this returns + } + + /// The head over the stream's last prompt row: logits (1, vocab) in the scratch. + pub fn head(f: *Forward, seq: *const st.Seq) !void { + try f.ops.dense(seq.head_in, seq.head_xs, f.w.head, f.s.logits, 1); + } + + /// Greedy picks of the scratch's first `rows` logits rows (torch.argmax, the first maximum). + pub fn picks(f: *Forward, rows: usize, out: []u32) !void { + try f.ops.argmax(f.s.logits, c.vocab, c.vocab, f.s.picks, rows); + try f.ops.download(std.mem.sliceAsBytes(out[0..rows]), f.s.picks); + try f.ops.s.synchronize(); + } +}; diff --git a/zig/src/families/qwen27/cuda/image.zig b/zig/src/families/qwen27/cuda/image.zig new file mode 100644 index 0000000000..8dddeb9e25 --- /dev/null +++ b/zig/src/families/qwen27/cuda/image.zig @@ -0,0 +1,406 @@ +//! An image's bytes to Qwen3.5 vision patches as 0.6.6's --vision makes them: PIL's decode, smart_resize and bicubic. +const std = @import("std"); +const vision = @import("vision.zig"); + +extern fn stbi_load_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int, req_comp: c_int) ?[*]u8; +extern fn stbi_load_16_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int, req_comp: c_int) ?[*]u16; +extern fn stbi_is_16_bit_from_memory(buffer: [*]const u8, len: c_int) c_int; +extern fn stbi_info_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int) c_int; +extern fn stbi_image_free(p: ?*anyopaque) void; + +pub const Rgb = struct { + w: u32, + h: u32, + px: []u8, // row-major RGB, 3 bytes a pixel + + pub fn deinit(r: Rgb, gpa: std.mem.Allocator) void { + gpa.free(r.px); + } +}; + +/// One image ready for the tower: its patches [gh * gw, 1536] in merge order, its grid and its tokens (gh * gw / 4). +pub const Prepared = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + +pub const Error = error{ BadImage, ImageTooLarge, Animated, ImageTooSmall, OutOfMemory }; + +/// images.py's ImageLimits: sides and decoded pixels (the server bounds the encoded bytes). +pub const max_side = 8192; +pub const max_pixels = 16 << 20; +const factor = vision.patch * vision.merge; // 32 + +/// Bytes to patches for at most `max_tokens` tokens (0.6.6's per-image cap: the request's budget shared, 4096 at most). +pub fn prepare(gpa: std.mem.Allocator, bytes: []const u8, max_tokens: u32) Error!Prepared { + const img = try decode(gpa, bytes); + defer img.deinit(gpa); + return prepareRgb(gpa, img, std.hash.Wyhash.hash(0x51e7, bytes), max_tokens); +} + +pub fn prepareRgb(gpa: std.mem.Allocator, img: Rgb, hash: u64, max_tokens: u32) Error!Prepared { + const tokens = @min(max_tokens, vision.max_patches / (vision.merge * vision.merge)); + if (tokens == 0) return error.ImageTooSmall; + const size = try smartResize(img.h, img.w, factor * factor, @as(u64, tokens) * factor * factor); + const resized = try resize(gpa, img, size.w, size.h); + defer resized.deinit(gpa); + const gh = size.h / vision.patch; + const gw = size.w / vision.patch; + return .{ .pixels = try patchify(gpa, resized), .gh = gh, .gw = gw, .tokens = gh * gw / (vision.merge * vision.merge), .hash = hash }; +} + +pub const Size = struct { h: u32, w: u32 }; + +/// transformers' smart_resize: sides multiples of `factor` (half-to-even), pixels within [min_pixels, max_pixels]. +pub fn smartResize(height: u32, width: u32, min_pixels: u64, max_pixels_: u64) Error!Size { + const h: f64 = @floatFromInt(height); + const w: f64 = @floatFromInt(width); + if (@max(h, w) / @min(h, w) > 200) return error.BadImage; + const f: f64 = factor; + var hb: f64 = roundEven(h / f) * f; + var wb: f64 = roundEven(w / f) * f; + if (hb * wb > @as(f64, @floatFromInt(max_pixels_))) { + const beta = @sqrt(h * w / @as(f64, @floatFromInt(max_pixels_))); + hb = @max(f, @floor(h / beta / f) * f); + wb = @max(f, @floor(w / beta / f) * f); + } else if (hb * wb < @as(f64, @floatFromInt(min_pixels))) { + const beta = @sqrt(@as(f64, @floatFromInt(min_pixels)) / (h * w)); + hb = @ceil(h * beta / f) * f; + wb = @ceil(w * beta / f) * f; + } + return .{ .h = @intFromFloat(hb), .w = @intFromFloat(wb) }; +} + +fn roundEven(x: f64) f64 { + const r = @round(x); + return if (@abs(x - @trunc(x)) == 0.5 and @mod(r, 2) != 0) r - std.math.sign(x) else r; +} + +/// The resized image as x / 255 (float64 to float32), normalized by 0.5 and 0.5, in 16x16 patches of 2x2 merge order. +pub fn patchify(gpa: std.mem.Allocator, img: Rgb) Error![]f32 { + const P = vision.patch; + const M = vision.merge; + const T = vision.temporal; + const gh = img.h / P; + const gw = img.w / P; + const out = try gpa.alloc(f32, @as(usize, gh) * gw * vision.patch_width); + var lut: [256]f32 = undefined; + for (&lut, 0..) |*v, i| { + const scaled: f32 = @floatCast(@as(f64, @floatFromInt(i)) * (1.0 / 255.0)); + v.* = (scaled - 0.5) / 0.5; + } + var row: usize = 0; + for (0..gh / M) |by| for (0..gw / M) |bx| for (0..M) |my| for (0..M) |mx| { + const y0 = (by * M + my) * P; + const x0 = (bx * M + mx) * P; + const dst = out[row * vision.patch_width ..][0..vision.patch_width]; + for (0..3) |ch| for (0..T) |t| for (0..P) |dy| for (0..P) |dx| { + dst[((ch * T + t) * P + dy) * P + dx] = lut[img.px[((y0 + dy) * img.w + x0 + dx) * 3 + ch]]; + }; + row += 1; + }; + return out; +} + +// ---- decoding (stb_image), EXIF orientation and alpha, as PIL gives images.py its RGB ---- + +/// TurboJPEG's decompression API (libturbojpeg.so.0), opened on first use; null when the library is absent. +const Turbo = struct { + init: *const fn () callconv(.c) ?*anyopaque, + header: *const fn (?*anyopaque, [*]const u8, c_ulong, *c_int, *c_int, *c_int, *c_int) callconv(.c) c_int, + decompress: *const fn (?*anyopaque, [*]const u8, c_ulong, [*]u8, c_int, c_int, c_int, c_int, c_int) callconv(.c) c_int, + destroy: *const fn (?*anyopaque) callconv(.c) c_int, + + var state = std.atomic.Value(u8).init(0); // 0: not opened, 1: opening, 2: done (api set or not) + var api: ?Turbo = null; + var lib: ?std.DynLib = null; + + fn load() void { + var l = std.DynLib.open("libturbojpeg.so.0") catch return; + api = .{ + .init = l.lookup(@FieldType(Turbo, "init"), "tjInitDecompress") orelse return l.close(), + .header = l.lookup(@FieldType(Turbo, "header"), "tjDecompressHeader3") orelse return l.close(), + .decompress = l.lookup(@FieldType(Turbo, "decompress"), "tjDecompress2") orelse return l.close(), + .destroy = l.lookup(@FieldType(Turbo, "destroy"), "tjDestroy") orelse return l.close(), + }; + lib = l; + } + + fn get() ?Turbo { + if (state.cmpxchgStrong(0, 1, .acquire, .acquire) == null) { + load(); + state.store(2, .release); + } + while (state.load(.acquire) != 2) std.atomic.spinLoopHint(); + return api; + } +}; + +const tjpf_rgb = 0; +const tjcs_cmyk = 3; +const tjcs_ycck = 4; + +/// A JPEG through libjpeg-turbo as PIL decodes it to RGB rows; null without TurboJPEG or for CMYK (PIL converts those). +fn turboJpeg(gpa: std.mem.Allocator, bytes: []const u8) Error!?Rgb { + const t = Turbo.get() orelse return null; + const h = t.init() orelse return null; + defer _ = t.destroy(h); + var w: c_int = 0; + var ht: c_int = 0; + var sub: c_int = 0; + var cs: c_int = 0; + if (t.header(h, bytes.ptr, bytes.len, &w, &ht, &sub, &cs) != 0) return error.BadImage; + if (cs == tjcs_cmyk or cs == tjcs_ycck) return null; + if (w <= 0 or ht <= 0) return error.BadImage; + if (w > max_side or ht > max_side or @as(u64, @intCast(w)) * @as(u64, @intCast(ht)) > max_pixels) return error.ImageTooLarge; + const W: usize = @intCast(w); + const H: usize = @intCast(ht); + const out = try gpa.alloc(u8, W * H * 3); + errdefer gpa.free(out); + if (t.decompress(h, bytes.ptr, bytes.len, out.ptr, w, w * 3, ht, tjpf_rgb, 0) != 0) return error.BadImage; + return .{ .w = @intCast(W), .h = @intCast(H), .px = out }; +} + +/// A single-frame PNG or JPEG as 8-bit RGB: upright by EXIF, alpha over white, as PIL's convert("RGB") gives. +pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { + if (bytes.len < 8 or bytes.len > std.math.maxInt(c_int)) return error.BadImage; + const n: c_int = @intCast(bytes.len); + if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") and pngAnimated(bytes)) return error.Animated; + if (std.mem.startsWith(u8, bytes, "\xff\xd8\xff")) if (try turboJpeg(gpa, bytes)) |img| return upright(gpa, img, bytes); + var w: c_int = 0; + var h: c_int = 0; + var comp: c_int = 0; + if (stbi_info_from_memory(bytes.ptr, n, &w, &h, &comp) == 0) return error.BadImage; + if (w <= 0 or h <= 0) return error.BadImage; + if (w > max_side or h > max_side or @as(u64, @intCast(w)) * @as(u64, @intCast(h)) > max_pixels) return error.ImageTooLarge; + const W: usize = @intCast(w); + const H: usize = @intCast(h); + const out = try gpa.alloc(u8, W * H * 3); + errdefer gpa.free(out); + if (stbi_is_16_bit_from_memory(bytes.ptr, n) != 0 and comp == 1) { + const p = stbi_load_16_from_memory(bytes.ptr, n, &w, &h, &comp, 0) orelse return error.BadImage; + defer stbi_image_free(p); + for (0..W * H) |i| @memset(out[i * 3 ..][0..3], @intCast(@min(p[i], 255))); + } else { + const p = stbi_load_from_memory(bytes.ptr, n, &w, &h, &comp, 0) orelse return error.BadImage; + defer stbi_image_free(p); + const c: usize = @intCast(comp); + for (0..W * H) |i| { + const s = p[i * c ..][0..c]; + const px = out[i * 3 ..][0..3]; + switch (c) { + 1 => @memset(px, s[0]), + 2 => @memset(px, overWhite(s[0], s[1])), + 3 => @memcpy(px, s[0..3]), + 4 => for (0..3) |k| { + px[k] = overWhite(s[k], s[3]); + }, + else => return error.BadImage, + } + } + } + return upright(gpa, .{ .w = @intCast(W), .h = @intCast(H), .px = out }, bytes); +} + +/// The decoded image turned upright by the EXIF orientation its bytes carry (it takes `img`). +fn upright(gpa: std.mem.Allocator, img: Rgb, bytes: []const u8) Error!Rgb { + const o = orientation(bytes); + if (o < 2 or o > 8) return img; + defer img.deinit(gpa); + return orient(gpa, img, o); +} + +/// An APNG (an acTL chunk before the image data) has more than one frame: images.py refuses it. +fn pngAnimated(bytes: []const u8) bool { + var at: usize = 8; + while (at + 8 <= bytes.len) { + const len = std.mem.readInt(u32, bytes[at..][0..4], .big); + const kind = bytes[at + 4 ..][0..4]; + if (std.mem.eql(u8, kind, "acTL")) return true; + if (std.mem.eql(u8, kind, "IDAT")) return false; + at += 12 + @as(usize, len); + } + return false; +} + +/// The EXIF orientation (tag 0x0112 of IFD0) a JPEG's APP1 or a PNG's eXIf chunk carries; 1 when none. +pub fn orientation(bytes: []const u8) u32 { + if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n")) { + var at: usize = 8; + while (at + 12 <= bytes.len) { + const len: usize = std.mem.readInt(u32, bytes[at..][0..4], .big); + if (at + 12 + len > bytes.len) break; + if (std.mem.eql(u8, bytes[at + 4 ..][0..4], "eXIf")) return tiffOrientation(bytes[at + 8 ..][0..len]); + at += 12 + len; + } + return 1; + } + var at: usize = 2; + while (at + 4 <= bytes.len and bytes[at] == 0xff) { + const marker = bytes[at + 1]; + if (marker == 0xd9 or marker == 0xda) break; // end of image, start of scan + const len: usize = std.mem.readInt(u16, bytes[at + 2 ..][0..2], .big); + if (len < 2 or at + 2 + len > bytes.len) break; + const seg = bytes[at + 4 .. at + 2 + len]; + if (marker == 0xe1 and std.mem.startsWith(u8, seg, "Exif\x00\x00")) return tiffOrientation(seg[6..]); + at += 2 + len; + } + return 1; +} + +fn tiffOrientation(t: []const u8) u32 { + if (t.len < 8) return 1; + const endian: std.builtin.Endian = if (std.mem.eql(u8, t[0..2], "II")) .little else if (std.mem.eql(u8, t[0..2], "MM")) .big else return 1; + if (std.mem.readInt(u16, t[2..4], endian) != 42) return 1; + const ifd: usize = std.mem.readInt(u32, t[4..8], endian); + if (ifd + 2 > t.len) return 1; + const count: usize = std.mem.readInt(u16, t[ifd..][0..2], endian); + for (0..count) |i| { + const e = ifd + 2 + i * 12; + if (e + 12 > t.len) return 1; + if (std.mem.readInt(u16, t[e..][0..2], endian) != 0x0112) continue; + if (std.mem.readInt(u16, t[e + 2 ..][0..2], endian) != 3) return 1; // SHORT + return std.mem.readInt(u16, t[e + 8 ..][0..2], endian); + } + return 1; +} + +// Below: GLM's image.zig (families/glm) PIL arithmetic, copied since the CUDA module cannot import that family's files. + +/// PIL's exif_transpose for orientations 2-8; each output pixel read from its source pixel. +pub fn orient(gpa: std.mem.Allocator, src: Rgb, o: u32) Error!Rgb { + const w: usize = src.w; + const h: usize = src.h; + const swap = o >= 5; + const ow = if (swap) h else w; + const oh = if (swap) w else h; + const out = try gpa.alloc(u8, ow * oh * 3); + for (0..oh) |y| for (0..ow) |x| { + const s: [2]usize = switch (o) { + 2 => .{ w - 1 - x, y }, + 3 => .{ w - 1 - x, h - 1 - y }, + 4 => .{ x, h - 1 - y }, + 5 => .{ y, x }, + 6 => .{ y, h - 1 - x }, + 7 => .{ w - 1 - y, h - 1 - x }, + else => .{ w - 1 - y, x }, + }; + @memcpy(out[(y * ow + x) * 3 ..][0..3], src.px[(s[1] * w + s[0]) * 3 ..][0..3]); + }; + return .{ .w = @intCast(ow), .h = @intCast(oh), .px = out }; +} + +/// PIL's paste of a pixel with alpha `a` onto white: DIV255(255 * (255 - a) + c * a). +fn overWhite(c: u8, a: u8) u8 { + const t: u32 = 255 * (255 - @as(u32, a)) + @as(u32, c) * a + 128; + return @intCast(((t >> 8) + t) >> 8); +} + +// ---- PIL's ImagingResample for 8-bit images (Resample.c), bicubic (a = -0.5) ---- + +const precision_bits = 32 - 8 - 2; + +fn bicubic(x0: f64) f64 { + const a = -0.5; + const x = @abs(x0); + if (x < 1.0) return ((a + 2.0) * x - (a + 3.0)) * x * x + 1; + if (x < 2.0) return (((x - 5) * x + 8) * x - 4) * a; + return 0; +} + +const Coeffs = struct { bounds: []u32, kk: []i32, ksize: usize }; + +/// precompute_coeffs and normalize_coeffs_8bpc: each output pixel's first input pixel, count and fixed-point weights. +fn coeffs(gpa: std.mem.Allocator, in_size: u32, out_size: u32) Error!Coeffs { + const scale = @as(f64, @floatFromInt(in_size)) / @as(f64, @floatFromInt(out_size)); + const filterscale = @max(scale, 1.0); + const support = 2.0 * filterscale; + const ksize: usize = @as(usize, @intFromFloat(@ceil(support))) * 2 + 1; + const bounds = try gpa.alloc(u32, @as(usize, out_size) * 2); + errdefer gpa.free(bounds); + const kk = try gpa.alloc(i32, @as(usize, out_size) * ksize); + errdefer gpa.free(kk); + var pre = try gpa.alloc(f64, ksize); + defer gpa.free(pre); + const ss = 1.0 / filterscale; + for (0..out_size) |xx| { + const center = (@as(f64, @floatFromInt(xx)) + 0.5) * scale; + var xmin_i: i64 = @intFromFloat(center - support + 0.5); // (int) truncates toward zero, as C does + if (xmin_i < 0) xmin_i = 0; + var xmax_i: i64 = @intFromFloat(center + support + 0.5); + if (xmax_i > in_size) xmax_i = in_size; + xmax_i -= xmin_i; + const xmin: usize = @intCast(xmin_i); + const xmax: usize = @intCast(xmax_i); + var ww: f64 = 0; + for (0..xmax) |x| { + const w = bicubic((@as(f64, @floatFromInt(x + xmin)) - center + 0.5) * ss); + pre[x] = w; + ww += w; + } + for (0..ksize) |x| { + const k = if (x < xmax) (if (ww != 0) pre[x] / ww else pre[x]) else 0; + const v = k * @as(f64, @floatFromInt(@as(i64, 1) << precision_bits)); + kk[xx * ksize + x] = @intFromFloat(if (v < 0) v - 0.5 else v + 0.5); // C's (int) of the rounded value + } + bounds[xx * 2] = @intCast(xmin); + bounds[xx * 2 + 1] = @intCast(xmax); + } + return .{ .bounds = bounds, .kk = kk, .ksize = ksize }; +} + +fn clip8(v: i64) u8 { + const s = v >> precision_bits; + return if (s < 0) 0 else if (s > 255) 255 else @intCast(s); +} + +/// Image.resize((w, h), BICUBIC) on an 8-bit RGB image: horizontal pass, then vertical, each rounded to 8 bits. +pub fn resize(gpa: std.mem.Allocator, src: Rgb, w: u32, h: u32) Error!Rgb { + var cur = src; + var owned = false; + errdefer if (owned) cur.deinit(gpa); + if (w != src.w) { + const c = try coeffs(gpa, src.w, w); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, w) * cur.h * 3); + for (0..cur.h) |y| for (0..w) |xx| { + const xmin = c.bounds[xx * 2]; + const xmax = c.bounds[xx * 2 + 1]; + const k = c.kk[xx * c.ksize ..]; + for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..xmax) |x| ss += @as(i64, cur.px[(y * cur.w + x + xmin) * 3 + ch]) * k[x]; + out[(y * w + xx) * 3 + ch] = clip8(ss); + } + }; + if (owned) cur.deinit(gpa); + cur = .{ .w = w, .h = cur.h, .px = out }; + owned = true; + } + if (h != src.h) { + const c = try coeffs(gpa, src.h, h); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, cur.w) * h * 3); + for (0..h) |yy| { + const ymin = c.bounds[yy * 2]; + const ymax = c.bounds[yy * 2 + 1]; + const k = c.kk[yy * c.ksize ..]; + for (0..cur.w) |x| for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..ymax) |y| ss += @as(i64, cur.px[((y + ymin) * cur.w + x) * 3 + ch]) * k[y]; + out[(yy * cur.w + x) * 3 + ch] = clip8(ss); + }; + } + if (owned) cur.deinit(gpa); + cur = .{ .w = cur.w, .h = h, .px = out }; + owned = true; + } + if (!owned) cur = .{ .w = src.w, .h = src.h, .px = try gpa.dupe(u8, src.px) }; + return cur; +} + +test "smart_resize rounds half to even and respects the pixel bounds" { + try std.testing.expectEqual(Size{ .h = 32, .w = 64 }, try smartResize(15, 20, 1024, 4096 * 1024)); + try std.testing.expectEqual(Size{ .h = 384, .w = 512 }, try smartResize(389, 517, 1024, 4096 * 1024)); + try std.testing.expectEqual(@as(f64, 2), roundEven(2.5)); + try std.testing.expectEqual(@as(f64, 2), roundEven(1.5)); +} diff --git a/zig/src/families/qwen27/cuda/kernels.zig b/zig/src/families/qwen27/cuda/kernels.zig new file mode 100644 index 0000000000..c43f19aacb --- /dev/null +++ b/zig/src/families/qwen27/cuda/kernels.zig @@ -0,0 +1,394 @@ +//! The 27B's CUDA kernels: our .cu fatbins with the Python wrappers' launch logic, and the captured Triton set. + +const std = @import("std"); +const cuda = @import("cuda"); +pub const torch_ops = @import("nemotron").torch_ops; + +/// Mangled names of the instantiations the copies in zig/kernels/cuda export (cuobjdump -symbols of each fatbin). +const sym = struct { + const group = "_ZN12tf_qmm_group12group_kernelILi64ELi16ELi64ELi1ELi4ELi8ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii"; + const wide = [_][:0]const u8{ + "_ZN12tf_qmm_group12group_kernelILi64ELi32ELi64ELi1ELi4ELi4ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii", + "_ZN12tf_qmm_group12group_kernelILi64ELi64ELi64ELi1ELi4ELi4ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii", + "_ZN12tf_qmm_group12group_kernelILi64ELi64ELi128ELi2ELi4ELi3ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii", + }; + const gemv = "_ZN12tf_lane_gemv11gemv_kernelILi64ELi64ELi8EEEvPK13__nv_bfloat16PKfNS_4PartEiii"; + const prefill_mm = "_ZN14tf_qmm_prefill14prefill_kernelILi64ELi128ELi128ELi2ELi2ELi2ELb0EEEvPK13__nv_bfloat16PKjS3_S3_Pviiiiii"; + const pattn = "_ZN20tf_prefill_attention12pattn_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiif"; + const pattn8 = "_ZN20tf_prefill_attention13pattn8_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16PKhS5_PKfS7_PS1_iiiiif"; + const chain128 = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16Li128ELi32EEEvPKT_S4_PKS1_PKfS8_S8_PfPS1_iii"; + const chain64 = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16Li64ELi32EEEvPKT_S4_PKS1_PKfS8_S8_PfPS1_iii"; + const argmax = "tf_argmax_rows_i32_kernel"; +}; + +/// qmm_group.cu's Part and Parts, passed by value: four projections at most, one used here. +pub const Part = extern struct { w: u64, scales: u64, biases: u64, out: u64, n: c_int, npad: c_int, sk: c_int, tiles: c_int, first: c_int }; +pub const Parts = extern struct { p: [4]Part, count: c_int }; + +/// lane_gemv.cu's Part: one projection whose column tiles the CTAs share out. +pub const GemvPart = extern struct { w: u64, scales: u64, biases: u64, out: u64, n: c_int, npad: c_int, sk: c_int, tiles: c_int }; + +/// gdn.cu's Pending (the tree kernel's rows still to fold): all null here, commits replay instead. +pub const Pending = extern struct { k: u64 = 0, v: u64 = 0, g: u64 = 0, beta: u64 = 0, rows: u64 = 0, row_stride: c_int = 0, counts: u64 = 0, count_stride: c_int = 0 }; + +comptime { + std.debug.assert(@sizeOf(Part) == 56 and @sizeOf(Parts) == 232 and @sizeOf(GemvPart) == 48 and @sizeOf(Pending) == 64); +} + +pub const group_smem: u32 = 35328; // LaneTile<64, 16, 64, 1, 4, 8>::SMEM +/// qmm_group's GB10 tiles 3-5 for wider rounds: rows a tile, columns a tile, threads, LaneTile::SMEM. +pub const Wide = struct { bm: usize, bn: usize, threads: u32, smem: u32 }; +pub const wide = [_]Wide{ .{ .bm = 32, .bn = 64, .threads = 128, .smem = 26112 }, .{ .bm = 64, .bn = 64, .threads = 128, .smem = 43008 }, .{ .bm = 64, .bn = 128, .threads = 256, .smem = 39168 } }; +pub const prefill_mm_smem: u32 = 41984; // Tile<64, 128, 128, 2, 2, 2>::SMEM: prompt_tile 9, two stages +pub const pattn_smem: u32 = 98304; // two 32-key slots of 256 dims beside eight warps' staged queries + +/// One item of a batched copy: 16-byte aligned pointers, a multiple of 16 bytes. +pub const Copy = extern struct { dst: u64, src: u64, bytes: u64 }; + +/// One item of qwen_ops.cu's kv_quant (--kv-cache fp8): `rows` bf16 rows of 256 to e4m3 rows plus an fp32 scale each. +pub const Quant = extern struct { src: u64, dst: u64, scale: u64, rows: u64 }; + +/// A tiled 4-bit projection: packed words, (kg, npad) scales and biases, n outputs from k inputs. +pub const QLinear = struct { w: u64, s: u64, b: u64, n: usize, k: usize, npad: usize }; + +pub const Kernels = struct { + d: *const cuda.Driver, + mods: [15]cuda.Module, + triton: cuda.aot.Set, + group: cuda.Function, + wide: [wide.len]cuda.Function, // tiles 3-5: rows <= 32, <= 64, more + gemv: cuda.Function, + prefill_mm: cuda.Function, + pattn: cuda.Function, + pattn8: cuda.Function, + kv_quant: cuda.Function, + trees: [cuda.kernels.gdn_variants.len]cuda.Function, // tree_kernel by gdn_variants: [0] the chain one + chip: [3]c_int, // major, minor, SMs: what dispatch_tree reads + replay: cuda.Function, + prompt_chain: cuda.Function, + prompt_rows: usize, // the prompt chain's value rows a block: 64 when heads < SMs + pack_dense: cuda.Function, + transpose16: cuda.Function, + argmax: cuda.Function, + torch: torch_ops.Functions, + copy_batch: cuda.Function, + tap: cuda.Function, + rms_norm: cuda.Function, + inv_freq: cuda.Function, + torch_rms: cuda.Function, // F.rms_norm's bits on bf16 rows of 5120 (torch_ops/norm_rotary.cu) + rotary: cuda.Function, + gemv_blocks: usize, // resident lane_gemv CTAs: per SM times SMs + gemv_rows: usize, // windows of at most this many rows take lane_gemv (none; TF_QWEN27_GEMV_ROWS) + gb10: bool, + discrete: bool, // the card has its own memory: checkpoint bytes reach it through page-locked slots + + /// Loads every module; `triton_dir` holds the captured aot.json and cubins for this GPU. + pub fn load(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, triton_dir: []const u8, heads: usize) !Kernels { + const d = ctx.d; + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var k: Kernels = undefined; + k.d = d; + const kk = cuda.kernels; + const images = [_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.prefill_attention, kk.gdn, kk.gdn_prefill, kk.affine4_pack, kk.torch_argmax, kk.torch_topk, kk.torch_pointwise, kk.torch_indexing, kk.torch_movement, kk.torch_nemotron_constants, kk.qwen_ops, kk.torch_norm_rotary }; + var loaded: usize = 0; + errdefer for (k.mods[0..loaded]) |*m| m.unload(); + for (images, 0..) |img, i| { + k.mods[i] = try cuda.Module.load(d, img); + loaded += 1; + } + k.group = try k.mods[0].function(sym.group); + for (&k.wide, sym.wide) |*f, name| f.* = try k.mods[0].function(name); + k.prefill_mm = try k.mods[1].function(sym.prefill_mm); + k.gemv = try k.mods[2].function(sym.gemv); + k.pattn = try k.mods[3].function(sym.pattn); + k.pattn8 = try k.mods[3].function(sym.pattn8); + for (&k.trees, cuda.kernels.gdn_variants) |*f, v| f.* = try k.mods[4].function(v.symbol); + k.replay = try k.mods[4].function(cuda.kernels.gdn_symbols.replay_bf16); + k.pack_dense = try k.mods[6].function(cuda.qlinear.symbols.pack_words); + k.transpose16 = try k.mods[6].function(cuda.qlinear.symbols.pack_scales); + k.argmax = try k.mods[7].function(sym.argmax); + k.torch = try torch_ops.Functions.resolve(k.mods[7..13]); + k.copy_batch = try k.mods[13].function("tf_copy_batch"); + k.kv_quant = try k.mods[13].function("tf_kv_quant"); + k.tap = try k.mods[13].function("tf_tap"); + k.rms_norm = try k.mods[13].function("tf_rms_norm"); + k.inv_freq = try k.mods[13].function("tf_inv_freq"); + k.rotary = try k.mods[13].function("tf_rotary"); + k.torch_rms = try k.mods[14].function("tf_dflash_rms5120_bf16_fma_kernel"); + const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); + // gdn_prefill_cuda: a block takes 128 value rows, or 64 when there are fewer heads than SMs + k.prompt_rows = if (heads >= sms) 128 else 64; + k.prompt_chain = try k.mods[5].function(if (k.prompt_rows == 128) sym.chain128 else sym.chain64); + k.triton = try cuda.aot.Set.load(gpa, io, d, ctx.device, triton_dir); + errdefer k.triton.deinit(); + try k.group.allowDynamicShared(group_smem); + for (k.wide, wide) |f, t| try f.allowDynamicShared(t.smem); + try k.gemv.allowDynamicShared(group_smem); + try k.prefill_mm.allowDynamicShared(prefill_mm_smem); + try k.pattn.allowDynamicShared(pattn_smem); + try k.pattn8.allowDynamicShared(pattn_smem); + k.gemv_blocks = @max(1, try k.gemv.occupancy(128, group_smem)) * sms; + const major = try ctx.attribute(.compute_capability_major); + const minor = try ctx.attribute(.compute_capability_minor); + k.gb10 = major == 12 and minor == 1; + k.discrete = try ctx.attribute(.integrated) == 0; + k.gemv_rows = 0; // a GB10 runs the 27B's projections faster in Python's clusters, 1 to 16 rows alike + if (std.c.getenv("TF_QWEN27_GEMV_ROWS")) |v| k.gemv_rows = std.fmt.parseInt(usize, std.mem.span(v), 10) catch k.gemv_rows; + k.chip = .{ major, minor, @intCast(sms) }; + return k; + } + + pub fn deinit(k: *Kernels) void { + k.triton.deinit(); + for (&k.mods) |*m| m.unload(); + } +}; + +/// qmm.split_k: K slices fixed by the weight's shape, never by the row count. +pub fn splitK(n: usize, k: usize) usize { + const tiles = (n + 63) / 64; + const groups = k / 64; + var sk: usize = 1; + while (sk < 8 and tiles * sk < 192 and groups % (sk * 2) == 0 and groups / (sk * 2) >= 8) sk *= 2; + return sk; +} + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn u(x: usize) u32 { + return @intCast(x); +} + +/// The GDN shapes every launch takes: key heads, value heads, value rows a head. +pub const Heads = struct { hk: usize, hv: usize, dv: usize }; + +/// Launch helpers on one stream; each mirrors the Python wrapper it replaces. +pub const Ops = struct { + k: *const Kernels, + s: cuda.Stream, + + fn go(o: Ops, f: cuda.Function, grid: [3]usize, block: u32, shared: u32, args: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = .{ .x = u(grid[0]), .y = u(grid[1]), .z = u(grid[2]) }, .block = .{ .x = block }, .shared = shared }, o.s, args); + } + + /// qmm.matmul on sm_12x: x (rows, k) bf16 with group sums xs -> out (rows, n) bf16, qmm_group's bits. + pub fn dense(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize) !void { + const sk = splitK(q.n, q.k); + if (rows > 16) return o.wideTile(x, xs, q, out, rows, sk); + // Python's clusters, a CTA a K slice; lane_gemv (byte-equal) when TF_QWEN27_GEMV_ROWS asks for it + return if (sk > 1 and rows <= o.k.gemv_rows) o.gemv(x, xs, q, out, rows, sk) else o.cluster(x, xs, q, out, rows, sk); + } + + /// qmm.matmul at a K split the caller names (matmul_rows takes the stacked weight's for each part). + pub fn denseSplit(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + if (rows > 16) return o.wideTile(x, xs, q, out, rows, sk); + return if (sk > 1 and rows <= o.k.gemv_rows) o.gemv(x, xs, q, out, rows, sk) else o.cluster(x, xs, q, out, rows, sk); + } + + /// tree_forward's taps: bf16(x + pending) of `rows` rows into columns [col, col + d) of rows `stride` wide. + pub fn tap(o: Ops, x: u64, pending: u64, out: u64, rows: usize, d: usize, stride: usize, col: usize) !void { + var a: cuda.Args = .{}; + for ([_]u64{ x, pending, out }) |v| a.add(v); + for ([_]usize{ d, stride, col }) |v| a.add(int(v)); + try o.go(o.k.tap, .{ rows, 4, 1 }, 256, 0, &a); + } + + /// lane_gemv: every K slice of a column tile in one CTA, summed in slice order, CTAs looping over the tiles. + fn gemv(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + const tiles = (q.n + 63) / 64; + var a: cuda.Args = .{}; + a.add(x); + a.add(xs); + a.add(GemvPart{ .w = q.w, .scales = q.s, .biases = q.b, .out = out, .n = int(q.n), .npad = int(q.npad), .sk = int(sk), .tiles = int(tiles) }); + for ([_]usize{ rows, q.k, q.k }) |v| a.add(int(v)); + const cfg: cuda.Config = .{ .grid = .{ .x = u(@min(tiles, o.k.gemv_blocks)) }, .block = .{ .x = 128 }, .shared = group_smem, .pdl = o.k.gb10 }; + try cuda.launch.launch(o.k.gemv, cfg, o.s, &a); + } + + /// qmm_group's tile 2 with one K slice: a CTA a column tile. + fn cluster(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + const tiles = (q.n + 63) / 64; + var parts: Parts = std.mem.zeroes(Parts); + parts.count = 1; + parts.p[0] = .{ .w = q.w, .scales = q.s, .biases = q.b, .out = out, .n = int(q.n), .npad = int(q.npad), .sk = int(sk), .tiles = int(tiles), .first = 0 }; + const rows_t = (rows + 15) / 16; + var a: cuda.Args = .{}; + a.add(x); + a.add(xs); + a.add(parts); + for ([_]usize{ rows, q.k, q.k, rows_t, sk }) |v| a.add(int(v)); + const cfg: cuda.Config = .{ + .grid = .{ .x = u(rows_t * tiles * sk) }, + .block = .{ .x = 128 }, + .shared = group_smem, + .cluster = if (sk > 1) .{ .x = u(sk) } else null, + .pdl = o.k.gb10, + }; + try cuda.launch.launch(o.k.group, cfg, o.s, &a); + } + + /// qmm_group's dispatch on a GB10 past 16 rows: tile 3, 4 or 5, a cluster of `sk` CTAs a column tile. + fn wideTile(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + const i: usize = if (rows <= 32) 0 else if (rows <= 64) 1 else 2; + const t = wide[i]; + const tiles = (q.n + t.bn - 1) / t.bn; + const rows_t = (rows + t.bm - 1) / t.bm; + var parts: Parts = std.mem.zeroes(Parts); + parts.count = 1; + parts.p[0] = .{ .w = q.w, .scales = q.s, .biases = q.b, .out = out, .n = int(q.n), .npad = int(q.npad), .sk = int(sk), .tiles = int(tiles), .first = 0 }; + var a: cuda.Args = .{}; + a.add(x); + a.add(xs); + a.add(parts); + for ([_]usize{ rows, q.k, q.k, rows_t, sk }) |v| a.add(int(v)); + const cfg: cuda.Config = .{ + .grid = .{ .x = u(rows_t * tiles * sk) }, + .block = .{ .x = t.threads }, + .shared = t.smem, + .cluster = if (sk > 1) .{ .x = u(sk) } else null, + .pdl = o.k.gb10, + }; + try cuda.launch.launch(o.k.wide[i], cfg, o.s, &a); + } + + /// qmm.prefill_matmul at prompt_tile 9: weights rounded once to bf16, one fp32 chain over K; bf16 out. + pub fn prefillDense(o: Ops, x: u64, q: QLinear, out: u64, rows: usize) !void { + const rows_t = (rows + 127) / 128; + const band = (12 << 20) / (128 * q.k * 2); + const group = @max(1, @min(rows_t, band)); + var a: cuda.Args = .{}; + for ([_]u64{ x, q.w, q.s, q.b, out }) |v| a.add(v); + for ([_]usize{ rows, q.n, q.k, q.npad, q.k, group }) |v| a.add(int(v)); + try o.go(o.k.prefill_mm, .{ rows_t * ((q.n + 127) / 128), 1, 1 }, 128, prefill_mm_smem, &a); + } + + /// gdn.tree (dispatch_tree): y from one `state`, or each stream's own by `table` and `starts`; `slots` 0: chains. + pub fn gdnTree(o: Ops, q: u64, k: u64, v: u64, g: u64, beta: u64, state: u64, table: u64, starts: u64, plan: u64, y: u64, rows: usize, streams: usize, slots: usize, most: usize, h: Heads) !void { + const variant = cuda.kernels.treeVariant(@intCast(slots), @intCast(streams), o.k.chip[0], o.k.chip[1], o.k.chip[2]); + const index = for (cuda.kernels.gdn_variants, 0..) |x, n| { + if (std.mem.eql(u8, x.symbol, variant.symbol)) break n; + } else unreachable; + var a: cuda.Args = .{}; + for ([_]u64{ q, k, v, g, beta, state, table, starts, plan }) |x| a.add(x); + a.add(int(rows)); + a.add(y); + for ([_]usize{ h.hk, h.hv, h.dv }) |x| a.add(int(x)); + a.add(Pending{}); + a.add(@as(u64, 0)); + a.add(@as(u64, 0)); + a.add(h.dv % variant.r == 0 and v % (2 * @as(u64, @min(variant.r, 8))) == 0); + const shared = 16 * @as(usize, variant.warps) * variant.slots * variant.r * 32 + (if (variant.chain) 0 else 4 * 3 * most); + try o.go(o.k.trees[index], .{ (h.dv + variant.r * variant.warps - 1) / (variant.r * variant.warps), h.hv, streams }, 32 * variant.warps, @intCast(shared), &a); + } + + /// gdn.replay in place: each stream's accepted rows stepped into the states the table names. + pub fn gdnReplay(o: Ops, table: u64, layers: usize, streams: usize, rows: u64, row_stride: usize, counts: u64, count_stride: usize, h: Heads) !void { + var a: cuda.Args = .{}; + a.add(table); + a.add(int(layers)); + a.add(rows); + a.add(int(row_stride)); + a.add(counts); + a.add(int(count_stride)); + a.add(@as(u64, 0)); + for ([_]usize{ h.hk, h.hv, h.dv }) |x| a.add(int(x)); + try o.go(o.k.replay, .{ (h.dv + 31) / 32, h.hv, layers * streams }, 128, 0, &a); + } + + /// gdn.chain: a prompt chunk's rows from `state` (read only) to `last`, chunk-invariant bits. + pub fn gdnPrompt(o: Ops, q: u64, k: u64, v: u64, g: u64, beta: u64, state: u64, last: u64, y: u64, rows: usize, h: Heads) !void { + var a: cuda.Args = .{}; + for ([_]u64{ q, k, v, g, beta, state, last, y }) |x| a.add(x); + for ([_]usize{ rows, h.hk, h.hv }) |x| a.add(int(x)); + const r = o.k.prompt_rows; + try o.go(o.k.prompt_chain, .{ h.hv, 128 / r, 1 }, u(2 * r), 0, &a); + } + + /// prefill_attention (head dim 256, two query heads a block): q (rows, heads, 256) at positions p0.. + pub fn prefillAttention(o: Ops, q: u64, kc: u64, vc: u64, out: u64, p0: usize, rows: usize, heads: usize, kv_heads: usize, scale: f32) !void { + const g = heads / kv_heads; + const hpc = 2; + var a: cuda.Args = .{}; + for ([_]u64{ q, kc, vc, out }) |v| a.add(v); + for ([_]usize{ p0, rows, heads, kv_heads, g }) |v| a.add(int(v)); + a.add(scale); + const block_rows = 16 * (8 / hpc); + try o.go(o.k.pattn, .{ (rows + block_rows - 1) / block_rows, kv_heads * (g / hpc), 1 }, 256, pattn_smem, &a); + } + + /// prefill_attention over an fp8 cache: e4m3 keys and values with a scale a (position, key head) row. + pub fn prefillAttention8(o: Ops, q: u64, kc: u64, vc: u64, ks: u64, vs: u64, out: u64, p0: usize, rows: usize, heads: usize, kv_heads: usize, scale: f32) !void { + const g = heads / kv_heads; + const hpc = 2; + var a: cuda.Args = .{}; + for ([_]u64{ q, kc, vc, ks, vs, out }) |v| a.add(v); + for ([_]usize{ p0, rows, heads, kv_heads, g }) |v| a.add(int(v)); + a.add(scale); + const block_rows = 16 * (8 / hpc); + try o.go(o.k.pattn8, .{ (rows + block_rows - 1) / block_rows, kv_heads * (g / hpc), 1 }, 256, pattn_smem, &a); + } + + /// qwen_ops.cu's tf_kv_quant: `count` items from the device table `items`, none over `most` rows. + pub fn quant(o: Ops, items: u64, count: usize, most: usize) !void { + if (count == 0) return; + var a: cuda.Args = .{}; + a.add(items); + try o.go(o.k.kv_quant, .{ (most + 7) / 8, count, 1 }, 256, 0, &a); + } + + /// torch.argmax(rows of bf16 logits) as int32: the first maximum, a NaN first. + pub fn argmax(o: Ops, logits: u64, vocab: usize, ld: usize, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(out); + for ([_]usize{ rows, vocab, ld }) |v| a.add(@as(i64, @intCast(v))); + a.add(@as(i32, 0)); // dtype 0: bf16 + try o.go(o.k.argmax, .{ rows, 1, 1 }, 1024, 0, &a); + } + + /// The torch-op replacements on this stream (topk and casts for sampled draws). + pub fn torch(o: Ops) torch_ops.Torch { + return .{ .f = &o.k.torch, .s = o.s }; + } + + /// qwen_ops.cu's tf_copy_batch: `count` (dst, src, bytes) items from the device table `items`, one launch. + pub fn copies(o: Ops, items: u64, count: usize) !void { + if (count == 0) return; + var a: cuda.Args = .{}; + a.add(items); + try o.go(o.k.copy_batch, .{ count, 4, 1 }, 256, 0, &a); + } + + pub fn copy(o: Ops, dst: u64, src: u64, bytes: usize) !void { + if (bytes == 0) return; + try o.k.d.check(o.k.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, o.s.handle), "cuMemcpyDtoDAsync"); + } + + pub fn fill32(o: Ops, dst: u64, value: u32, words: usize) !void { + try o.k.d.check(o.k.d.api.cuMemsetD32Async(dst, value, words, o.s.handle), "cuMemsetD32Async"); + } + + pub fn upload(o: Ops, dst: u64, bytes: []const u8) !void { + if (bytes.len == 0) return; + try o.k.d.check(o.k.d.api.cuMemcpyHtoDAsync_v2(dst, bytes.ptr, bytes.len, o.s.handle), "cuMemcpyHtoDAsync"); + } + + pub fn download(o: Ops, dst: []u8, src: u64) !void { + if (dst.len == 0) return; + try o.k.d.check(o.k.d.api.cuMemcpyDtoHAsync_v2(dst.ptr, src, dst.len, o.s.handle), "cuMemcpyDtoHAsync"); + } +}; + +test "split_k follows the 27B's shapes" { + try std.testing.expectEqual(@as(usize, 2), splitK(10240, 5120)); // qkv + try std.testing.expectEqual(@as(usize, 2), splitK(6144, 5120)); // z + try std.testing.expectEqual(@as(usize, 8), splitK(48, 5120)); // b, a + try std.testing.expectEqual(@as(usize, 1), splitK(17408, 5120)); // gate, up + try std.testing.expectEqual(@as(usize, 4), splitK(5120, 17408)); // down + try std.testing.expectEqual(@as(usize, 4), splitK(5120, 6144)); // out_proj, o_proj + try std.testing.expectEqual(@as(usize, 1), splitK(12288, 5120)); // q with its gate + try std.testing.expectEqual(@as(usize, 8), splitK(1024, 5120)); // k, v + try std.testing.expectEqual(@as(usize, 1), splitK(248320, 5120)); // head +} diff --git a/zig/src/families/qwen27/cuda/lanes.zig b/zig/src/families/qwen27/cuda/lanes.zig new file mode 100644 index 0000000000..acbd27a1c1 --- /dev/null +++ b/zig/src/families/qwen27/cuda/lanes.zig @@ -0,0 +1,585 @@ +//! The 27B's CUDA engine behind the lane core: every stream's window in one verify, DFlash2 drafts in one batch. + +const std = @import("std"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const Engine = @import("engine.zig").Engine; +const Part = @import("forward.zig").Part; +const Forward = @import("forward.zig").Forward; +const eng = @import("engine.zig"); +const prompt_rows = eng.prompt_rows; +const reuse = @import("reuse.zig"); +const dl = @import("draft_load.zig"); +const dr = @import("draft.zig"); +const drafts = @import("drafts.zig"); +const lone = @import("lone.zig"); +const trees = @import("tree.zig"); +const vision = @import("vision.zig"); +const be = lanes.backend; + +/// The row counts calibrate times (calibration_rows without the tile steps a GB10 skips), to 16 a stream. +const calibration = [_]usize{ 1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256 }; + +/// The last verified round, committed when the next call needs the streams' states (keep may cut it first). +const Pending = struct { + streams: [st.max_streams]*lanes.Stream = undefined, + parts: [st.max_streams]Part = undefined, + paths: [st.max_streams][]const u32 = undefined, + path_rows: [st.round_rows]u32 = undefined, // the round's kept rows, each stream's path in its own slice + tokens: [st.round_rows]u32 = undefined, + parents: [st.round_rows]i32 = undefined, + starts: [st.max_streams]usize = undefined, // each window's first row in the round + n: usize = 0, +}; + +pub const Cuda = struct { + gpa: std.mem.Allocator, + e: *Engine, + streams: u32, + seqs: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Seq) = .empty, + logits: []u16 = &.{}, // a whole row on the host, for a draw with top_k off + cand_values: []f32 = &.{}, // the rows' top candidates on the host + cand_ids: []i64 = &.{}, + values: []f64 = &.{}, + pending: Pending = .{}, + drafter: ?*dr.DFlash2 = null, // DFlash2, when its checkpoint is pulled and drafts are on + tower: ?*vision.Tower = null, // the image tower, with --vision + drafting: std.AutoHashMapUnmanaged(*lanes.Stream, *drafts.Stream) = .empty, + costs: [calibration.len + 1]lanes.config.Cost = undefined, // the forward's ms by a round's rows (calibrate) + cost_count: usize = 0, + + pub fn init(gpa: std.mem.Allocator, e: *Engine, streams: u32) !Cuda { + return .{ + .gpa = gpa, + .e = e, + .streams = streams, + .logits = try gpa.alloc(u16, c.vocab), + .cand_values = try gpa.alloc(f32, st.round_rows * st.max_candidates), + .cand_ids = try gpa.alloc(i64, st.round_rows * st.max_candidates), + .values = try gpa.alloc(f64, st.max_candidates), + }; + } + + pub fn deinit(x: *Cuda) void { + var it = x.seqs.valueIterator(); + while (it.next()) |seq| { + seq.*.deinit(); + x.gpa.destroy(seq.*); + } + x.seqs.deinit(x.gpa); + var dit = x.drafting.valueIterator(); + while (dit.next()) |ds| { + ds.*.deinit(); + x.gpa.destroy(ds.*); + } + x.drafting.deinit(x.gpa); + x.gpa.free(x.logits); + x.gpa.free(x.cand_values); + x.gpa.free(x.cand_ids); + x.gpa.free(x.values); + } + + /// The facts the round loop reads: 16-row windows in one forward; with DFlash2, host trees with node chances. + pub fn facts(x: *const Cuda) lanes.Model { + var m: lanes.Model = .{ .exact_width = st.max_rows, .hidden_rows = true, .batch_rows = st.round_rows, .max_streams = @min(x.streams, st.max_streams), .streams_exact = true }; + if (x.drafter != null) { + m.mtp = true; + m.speculate = true; + m.speculate_early = false; + m.drafts = drafts.max_nodes; + m.draft_probabilities = true; + m.draft_streams = true; + } + const timed = x.costs[0..x.cost_count]; + var narrow: usize = 0; + while (narrow < timed.len and timed[narrow].width <= st.max_rows) narrow += 1; + m.window_costs = timed[0..narrow]; + m.shared_costs = timed; + return m; + } + + /// multi.calibrate: the forward's ms (median of three) by the rows `streams` windows bring, on a fresh state. + pub fn calibrate(x: *Cuda, io: std.Io, streams: usize) !void { + var seq = x.e.sequence(st.max_rows + 2) catch |err| return if (err == error.OutOfMemory) err else error.OutOfDeviceMemory; + defer seq.deinit(); + const zeros: [st.max_rows]u32 = @splat(0); + const most: usize = st.max_rows * @as(usize, @min(streams, st.max_streams)); + var rows: [calibration.len + 1]usize = undefined; + var n: usize = 0; + for (calibration) |r| if (r < most) { + rows[n] = r; + n += 1; + }; + rows[n] = most; + n += 1; + var f = x.e.forward(); + const clock = std.Io.Clock.awake; + for (rows[0..n], x.costs[0..n]) |r, *cost| { + const parts_n = (r + st.max_rows - 1) / st.max_rows; + var parts: [st.max_streams]Part = undefined; + for (parts[0..parts_n], 0..) |*part, i| part.* = .{ .seq = &seq, .tokens = zeros[0 .. r / parts_n + @intFromBool(i < r % parts_n)] }; + var times: [3]f64 = undefined; + for (0..4) |rep| { + try f.ops.s.synchronize(); + const t0 = clock.now(io).toNanoseconds(); + try f.round(parts[0..parts_n]); + try f.ops.s.synchronize(); + if (rep > 0) times[rep - 1] = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; + } + std.mem.sort(f64, ×, {}, std.sort.asc(f64)); + cost.* = .{ .width = @intCast(r), .ms = times[1] }; + } + x.cost_count = n; + } + + pub fn backend(x: *Cuda) be.Backend { + return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .probabilities = probabilities, .tree = tree, .release = release, .prefill_many = prefillMany } }; + } + + /// The stream's drafting (its DFlash2 context and copy index), made on first use. + pub fn draftingOf(x: *Cuda, s: *lanes.Stream) !*drafts.Stream { + if (x.drafting.get(s)) |ds| return ds; + const ds = try x.gpa.create(drafts.Stream); + errdefer x.gpa.destroy(ds); + const ctx = dr.Context.init(x.e.ctx.d) catch |err| return if (err == error.OutOfMemory) err else error.OutOfDeviceMemory; + ds.* = drafts.Stream.init(x.gpa, ctx); + errdefer ds.deinit(); + try x.drafting.put(x.gpa, s, ds); + return ds; + } + + fn cast(p: *anyopaque) *Cuda { + return @ptrCast(@alignCast(p)); + } + + fn seqOf(x: *Cuda, s: *lanes.Stream) !*st.Seq { + return x.seqs.get(s) orelse error.UnknownQwenStream; + } + + /// Commits the last verified round: every stream its kept rows (its whole window unless keep cut it). + fn settle(x: *Cuda) !void { + const p = &x.pending; + if (p.n == 0) return; + const n = p.n; + p.n = 0; + var f = x.e.forward(); + try f.commit(p.parts[0..n], p.paths[0..n]); + } + + /// The stream's state, the last round committed first. + fn settled(x: *Cuda, s: *lanes.Stream) !*st.Seq { + try x.settle(); + return x.seqOf(s); + } + + /// The round's logits rows drawn: greedy by one argmax, sampled from top (top_k + 8) GPU candidates or whole rows. + pub fn drawRows(x: *Cuda, rules: []const ?lanes.Sampling, positions: []const u64, out: []u32) !void { + const rows = positions.len; + var f = x.e.forward(); + const s = f.s; + try f.picks(rows, out[0..rows]); + var want: usize = 0; + for (rules) |r| if (r) |rule| if (rule.temperature > 0 and rule.top_k != 0) { + want = @max(want, @min(c.vocab, @as(usize, rule.top_k) + 8)); + }; + if (want > st.max_candidates) want = 0; // past the GPU's candidates: whole rows below + if (want > 0) { + const t = f.ops.torch(); + try t.toF32(s.logits, s.logits32, rows * c.vocab); + try t.topk(s.logits32, c.vocab, rows, want, s.cand_values, s.cand_ids, s.topk_scratch); + try f.ops.download(std.mem.sliceAsBytes(x.cand_values[0 .. rows * want]), s.cand_values); + try f.ops.download(std.mem.sliceAsBytes(x.cand_ids[0 .. rows * want]), s.cand_ids); + try f.ops.s.synchronize(); + } + for (rules, positions, out[0..rows], 0..) |rule_, pos, *o, r| { + const rule = rule_ orelse continue; + if (rule.temperature <= 0) continue; + if (rule.top_k != 0 and want > 0) { + const vals = x.values[0..want]; + for (vals, x.cand_values[r * want ..][0..want]) |*v, w| v.* = w; + const ids = x.cand_ids[r * want ..][0..want]; + o.* = @intCast(try lanes.sampling.choose(x.gpa, vals, @ptrCast(ids), pos, rule)); + continue; + } + try f.ops.download(std.mem.sliceAsBytes(x.logits), s.logits + r * c.vocab * 2); + try f.ops.s.synchronize(); + o.* = try draw(x.gpa, x.logits, rule, pos); + } + } + + /// A new stream's state, sized for its prompt and reply. + pub fn open(x: *Cuda, s: *lanes.Stream) !*st.Seq { + try x.settle(); + const ids = s.prompt(); + if (ids.len == 0 or x.seqs.contains(s)) return error.InvalidQwenPrompt; + const capacity = @min(x.e.context, ids.len + s.max_new + st.max_rows); + if (ids.len >= capacity) return error.PromptTooLong; + const seq = try x.gpa.create(st.Seq); + errdefer x.gpa.destroy(seq); + seq.* = x.e.sequence(capacity) catch |err| return if (err == error.OutOfMemory) err else error.OutOfDeviceMemory; + errdefer seq.deinit(); + try x.seqs.put(x.gpa, s, seq); + return seq; + } + + fn prefill(p: *anyopaque, s: *lanes.Stream) !void { + const x = cast(p); + const seq = try x.open(s); + errdefer x.dropSeq(s); + try x.prefillOpened(s, seq); + } + + /// prefill_state into an opened stream: a found kept state restored, then the prompt in chunks to the cache marks. + fn prefillOpened(x: *Cuda, s: *lanes.Stream, seq: *st.Seq) !void { + // an image prompt: the tower's rows and the prompt's three positions for its pass (EncodedVision) + const media: ?*vision.Media = if (s.images.len == 0) null else blk: { + const tower = x.tower orelse return error.VisionDisabled; + const gpu: vision.Gpu = .{ .d = x.e.ops().k.d, .s = x.e.ops().s, .discrete = x.e.ops().k.discrete }; + break :blk try vision.Media.init(x.gpa, tower, gpu, s.prompt(), s.images, prompt_rows); + }; + defer if (media) |m| m.deinit(); + const from = x.restoreKept(s, seq, media != null); + // an image prompt keeps nothing: its rows' positions are the tower's, not the tokens' + const marks: ?eng.Keep = if (s.reuse.marks.len == 0 or media != null) null else .{ .at = s.reuse.marks, .ctx = s, .call = keptAt }; + if (x.drafter) |d| if (s.drafts) { + const ds = try x.draftingOf(s); + return lone.prefillFrom(x.e, seq, &ds.ctx, d, s.prompt(), from, media, marks); + }; + try x.e.prefillFrom(seq, s.prompt(), from, media, marks); + } + + /// The stream's kept state restored on its sequence: where its prompt pass starts (0: none, off the grid, failed). + fn restoreKept(x: *Cuda, s: *lanes.Stream, seq: *st.Seq, image: bool) usize { + s.cached = 0; + const saved = s.reuse.saved orelse return 0; + if (image or !x.e.grid or !eng.resumable(s.reuse.at, s.prompt().len)) { + s.reuse_failed = true; + return 0; + } + reuse.restoreSeq(x.e, seq, saved) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = s.reuse.at; + return s.reuse.at; + } + + /// The prompt pass stands at a mark: the lane host copies the stream's state there. + fn keptAt(ctx: *anyopaque, at: u32) void { + const s: *lanes.Stream = @ptrCast(@alignCast(ctx)); + if (s.reuse.hook) |k| k.at(k.ptr, s, at); + } + + /// prefill_batch: prompts in shared passes of at most a chunk's rows (a longer one alone, in its chunks). + fn prefillMany(p: *anyopaque, streams: []const *lanes.Stream, errs: []?anyerror) !void { + const x = cast(p); + var pieces: [st.max_streams]Forward.Piece = undefined; + var which: [st.max_streams]usize = undefined; + var n: usize = 0; + var rows: usize = 0; + for (streams, errs, 0..) |s, *err, i| { + const seq = x.open(s) catch |e| { + err.* = e; + continue; + }; + const ids = s.prompt(); + if (ids.len > prompt_rows) { + x.prefillOpened(s, seq) catch |e| { + x.dropSeq(s); + err.* = e; + }; + continue; + } + if (n == st.max_streams or rows + ids.len > prompt_rows) { + x.pass(streams, errs, pieces[0..n], which[0..n]); + n = 0; + rows = 0; + } + pieces[n] = .{ .ids = ids, .seq = seq, .last = true }; + which[n] = i; + n += 1; + rows += ids.len; + } + if (n > 0) x.pass(streams, errs, pieces[0..n], which[0..n]); + } + + /// One shared prompt pass; on a failure every stream in it fails. + fn pass(x: *Cuda, streams: []const *lanes.Stream, errs: []?anyerror, pieces: []const Forward.Piece, which: []const usize) void { + x.passPieces(streams, pieces, which) catch |e| for (which) |i| { + x.dropSeq(streams[i]); + errs[i] = e; + }; + } + + fn passPieces(x: *Cuda, streams: []const *lanes.Stream, pieces: []const Forward.Piece, which: []const usize) !void { + var f = x.e.forward(); + const d = x.drafter orelse return f.chunks(pieces); + f.taps = x.e.scratch.taps; + try f.chunks(pieces); + // each drafting stream's last window of taps, consecutive whole prompts absorbed together + const row = drafts.taps_width * 2; + var group: [st.max_streams]dr.Absorb = undefined; + var g: usize = 0; + var g_rows: usize = 0; + var g_from: usize = 0; // the group's first tap row + var at: usize = 0; // this piece's first row in the pass + for (pieces, which) |pc, i| { + defer at += pc.ids.len; + const s = streams[i]; + if (!s.drafts) continue; + const ds = try x.draftingOf(s); + ds.ctx.len = 0; + ds.ctx.end = 0; + const tap_from = pc.ids.len -| dl.window; + ds.ctx.skip(tap_from); + const taken = pc.ids.len - tap_from; + if (g > 0 and (tap_from > 0 or g_from + g_rows != at or g_rows + taken > dl.window + 1)) { + try d.absorbMany(group[0..g], x.e.scratch.taps + g_from * row); + g = 0; + } + if (g == 0) { + g_from = at + tap_from; + g_rows = 0; + } + group[g] = .{ .ctx = &ds.ctx, .rows = taken }; + g += 1; + g_rows += taken; + } + if (g > 0) try d.absorbMany(group[0..g], x.e.scratch.taps + g_from * row); + } + + fn dropSeq(x: *Cuda, s: *lanes.Stream) void { + if (x.seqs.fetchRemove(s)) |entry| { + entry.value.deinit(); + x.gpa.destroy(entry.value); + } + } + + fn first(p: *anyopaque, s: *lanes.Stream, position: u64) !u64 { + const x = cast(p); + const seq = try x.settled(s); + if (position != seq.pos) return error.InvalidQwenPosition; + var f = x.e.forward(); + try f.head(seq); + var out: [1]u32 = undefined; + try x.drawRows(&.{s.sampling}, &.{position}, &out); + return out[0]; + } + + fn queue(p: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) !u64 { + const x = cast(p); + const seq = try x.settled(s); + if (position != seq.pos + 1) return error.InvalidQwenPosition; + const token: u32 = switch (feed) { + .value => |v| v, + .handle => |h| @intCast(h), + }; + var f = x.e.forward(); + const part = [_]Part{.{ .seq = seq, .tokens = &.{token} }}; + try f.round(&part); + var out: [1]u32 = undefined; + try x.drawRows(&.{s.sampling}, &.{position}, &out); + try f.commit(&part, &.{&.{0}}); + return out[0]; + } + + fn read(_: *anyopaque, handle: u64) !u32 { + if (handle >= c.vocab) return error.InvalidQwenToken; + return @intCast(handle); + } + + /// One forward over every window (one stream: tree_forward's, several: multi_tree_forward's), each row drawn. + fn verify(p: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const x = cast(p); + if (windows.len != out.len or windows.len == 0 or windows.len > st.max_streams) return error.InvalidQwenWindows; + try x.settle(); + const pend = &x.pending; + var total: usize = 0; + for (windows, out, 0..) |w, o, k| { + const rows = w.rows(); + if (w.held != 0 or w.positions.len != rows or rows > st.max_rows or total + rows > st.round_rows) return error.UnsupportedQwenWindow; + if (o.sampled.len != rows or o.drafts.len != w.tokens.len) return error.InvalidQwenOutputs; + const seq = try x.seqOf(w.stream); + pend.tokens[total] = w.pending; + @memcpy(pend.tokens[total + 1 ..][0..w.tokens.len], w.tokens); + const parents: ?[]const i32 = if (w.parents) |given| blk: { + if (given.len != rows) return error.InvalidQwenWindows; + @memcpy(pend.parents[total..][0..rows], given); + break :blk pend.parents[total..][0..rows]; + } else null; + // each row's draw is keyed at its depth past the committed position + var depth: [st.max_rows]usize = undefined; + if (parents) |ps| { + try trees.depths(ps, depth[0..rows]); + } else for (depth[0..rows], 0..) |*d, r| { + d.* = r; + } + for (w.positions, depth[0..rows]) |pos, d| if (pos != seq.pos + d + 1) return error.InvalidQwenPosition; + pend.parts[k] = .{ .seq = seq, .tokens = pend.tokens[total..][0..rows], .parents = parents }; + pend.starts[k] = total; + pend.streams[k] = w.stream; + // a window kept whole: its rows in order (keep replaces them with its path) + for (pend.path_rows[total..][0..rows], 0..) |*row, r| row.* = @intCast(r); + pend.paths[k] = pend.path_rows[total..][0..rows]; + total += rows; + } + var f = x.e.forward(); + if (x.drafter != null) f.taps = x.e.scratch.taps; + try f.round(pend.parts[0..windows.len]); + pend.n = windows.len; + var rules: [st.round_rows]?lanes.Sampling = undefined; + var positions: [st.round_rows]u64 = undefined; + var drawn: [st.round_rows]u32 = undefined; + var row: usize = 0; + for (windows) |w| for (w.positions) |pos| { + rules[row] = w.stream.sampling; + positions[row] = pos; + row += 1; + }; + try x.drawRows(rules[0..total], positions[0..total], &drawn); + row = 0; + for (windows, out) |w, o| { + @memcpy(o.sampled, drawn[row..][0..o.sampled.len]); + row += o.sampled.len; + @memcpy(o.drafts, w.tokens); + } + } + + /// A window keeps its accepted path (a chain's prefix, or a tree's root-to-node rows); verify keeps all of it. + fn keep(p: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + const x = cast(p); + const pend = &x.pending; + for (windows, paths) |w, path| { + const k = for (pend.streams[0..pend.n], 0..) |s, k| { + if (s == w.stream) break k; + } else return error.UnknownQwenStream; + const rows = pend.parts[k].tokens.len; + if (path.len == 0 or path.len > rows) return error.InvalidQwenCommit; + const slot: [*]u32 = @constCast(pend.paths[k].ptr); + for (path, 0..) |r, i| { + if (r >= rows) return error.InvalidQwenCommit; + slot[i] = r; + } + pend.paths[k] = slot[0..path.len]; + } + } + + /// The kept rows' taps into each stream's drafter context, then each stream's next drafts. + fn draft(p: *anyopaque, requests: []const be.DraftRequest) !void { + const x = cast(p); + const d = x.drafter orelse { + for (requests) |r| if (r.depth != 0) return error.QwenCheckpointHasNoDraftHead; + return; + }; + const pend = &x.pending; + var kept: [st.max_streams]drafts.Kept = undefined; + var rows: [st.round_rows]u32 = undefined; + var asks: [st.max_streams]drafts.Ask = undefined; + var firsts: [st.max_streams]std.ArrayList(u32) = @splat(.empty); + defer for (&firsts) |*l| l.deinit(x.gpa); + var nk: usize = 0; + var nr: usize = 0; + var na: usize = 0; + for (requests) |r| { + if (na == st.max_streams) return error.InvalidQwenWindows; + const ds = x.drafting.get(r.stream) orelse continue; + var context = r.stream.context.items; + if (r.rows) |path| { + const k = for (pend.streams[0..pend.n], 0..) |s, k| { + if (s == r.stream) break k; + } else return error.UnknownQwenStream; + for (path, rows[nr..][0..path.len]) |row, *g| g.* = @intCast(pend.starts[k] + row); + kept[nk] = .{ .x = ds, .rows = rows[nr..][0..path.len] }; + nk += 1; + nr += path.len; + } else if (r.first) |feed| { + // the prompt's taps went in with its prefill; the first token ends the context the copies read + const token: u32 = switch (feed) { + .value => |v| v, + .handle => |h| try read(p, h), + }; + try firsts[na].appendSlice(x.gpa, context); + try firsts[na].append(x.gpa, token); + context = firsts[na].items; + } + asks[na] = .{ .x = ds, .context = context, .sampling = r.stream.sampling }; + na += 1; + } + const f = x.e.forward(); + try drafts.absorb(d, f.ops, x.e.scratch.taps, x.e.scratch.copy_items, kept[0..nk]); + try drafts.propose(d, asks[0..na]); + } + + /// The drafts a stream holds as host tokens and parents (a copy's as a chain). + fn tree(p: *anyopaque, s: *lanes.Stream, gpa: std.mem.Allocator) !?lanes.stream.Held { + const x = cast(p); + const ds = x.drafting.get(s) orelse return null; + const tokens = try gpa.dupe(u32, ds.tokens.items); + errdefer gpa.free(tokens); + const parents: ?[]i32 = if (ds.kind == .tree) try gpa.dupe(i32, ds.parents.items) else null; + return .{ .count = @intCast(tokens.len), .tokens = tokens, .parents = parents }; + } + + /// Each held draft's chance of landing: a tree node's exp(-path score) (allocate's), a copied token's 1. + fn probabilities(p: *anyopaque, s: *lanes.Stream, out: []f64) !bool { + const x = cast(p); + const ds = x.drafting.get(s) orelse return false; + if (out.len > ds.scores.items.len) return false; + for (out, ds.scores.items[0..out.len]) |*o, score| o.* = @exp(-score); + return true; + } + + fn release(p: *anyopaque, s: *lanes.Stream) void { + const x = cast(p); + x.settle() catch |err| std.log.err("committing the last round before a release: {s}", .{@errorName(err)}); + if (x.seqs.fetchRemove(s)) |entry| { + entry.value.deinit(); + x.gpa.destroy(entry.value); + } + if (x.drafting.fetchRemove(s)) |entry| { + entry.value.deinit(); + x.gpa.destroy(entry.value); + } + } +}; + +fn value(word: u16) f64 { + return @as(f32, @bitCast(@as(u32, word) << 16)); +} + +/// The Metal backend's draw: the top-k candidates by value then id, then the shared fp64 keyed sampler. +pub fn draw(gpa: std.mem.Allocator, logits: []const u16, settings: ?lanes.Sampling, position: u64) !u32 { + var best: usize = 0; + for (logits, 0..) |word, id| { + const x = value(word); + if (!std.math.isFinite(x)) return error.NonfiniteQwenLogits; + if (x > value(logits[best])) best = id; + } + const sampling = settings orelse return @intCast(best); + if (sampling.temperature <= 0) return @intCast(best); + const k = if (sampling.top_k == 0) logits.len else @min(logits.len, sampling.top_k); + const values = try gpa.alloc(f64, k); + defer gpa.free(values); + const ids = try gpa.alloc(u64, k); + defer gpa.free(ids); + var filled: usize = 0; + for (logits, 0..) |word, id| { + const x = value(word); + if (k == logits.len) { + values[id] = x; + ids[id] = id; + continue; + } + if (filled == k and x <= values[k - 1]) continue; + var at = @min(filled, k - 1); + while (at > 0 and x > values[at - 1]) : (at -= 1) { + values[at] = values[at - 1]; + ids[at] = ids[at - 1]; + } + values[at] = x; + ids[at] = id; + filled = @min(filled + 1, k); + } + return @intCast(try lanes.sampling.choose(gpa, values, ids, position, sampling)); +} diff --git a/zig/src/families/qwen27/cuda/lone.zig b/zig/src/families/qwen27/cuda/lone.zig new file mode 100644 index 0000000000..9f55fe1fca --- /dev/null +++ b/zig/src/families/qwen27/cuda/lone.zig @@ -0,0 +1,197 @@ +//! decode.draft_decode for one stream: copies from the context, else a DFlash2 tree; verify, walk, commit, absorb. + +const std = @import("std"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const tree = @import("tree.zig"); +const kern = @import("kernels.zig"); +const dr = @import("draft.zig"); +const dl = @import("draft_load.zig"); +const eng = @import("engine.zig"); +const Engine = eng.Engine; +const Forward = @import("forward.zig").Forward; +const Part = @import("forward.zig").Part; +const Lanes = @import("lanes.zig").Cuda; + +const bf = 2; +const taps_width = dl.taps.len * dl.hidden; + +/// decode.CopyIndex: earlier 8-token matches of the context's suffix, the longest continuation proposed. +pub const CopyIndex = struct { + pub const n = 8; + const Key = [n]u32; + gpa: std.mem.Allocator, + positions: std.AutoHashMapUnmanaged(Key, std.ArrayList(usize)) = .empty, + indexed: usize = 0, + + pub fn deinit(x: *CopyIndex) void { + var it = x.positions.valueIterator(); + while (it.next()) |l| l.deinit(x.gpa); + x.positions.deinit(x.gpa); + } + + fn update(x: *CopyIndex, context: []const u32) !void { + if (context.len < n) return; + const last = context.len - n; // the trailing query itself stays out of the index + var start = x.indexed; + while (start < last) : (start += 1) { + const gop = try x.positions.getOrPut(x.gpa, context[start..][0..n].*); + if (!gop.found_existing) gop.value_ptr.* = .empty; + try gop.value_ptr.append(x.gpa, start); + } + x.indexed = @max(x.indexed, last); + } + + /// The longest continuation after an earlier occurrence of the last 8 tokens (latest first), at least 8 long. + pub fn propose(x: *CopyIndex, context: []const u32, max_nodes: usize) ![]const u32 { + if (context.len < 2 * n) return &.{}; + try x.update(context); + const starts = x.positions.get(context[context.len - n ..][0..n].*) orelse return &.{}; + var best: []const u32 = &.{}; + var i = starts.items.len; + while (i > 0) { + i -= 1; + const from = starts.items[i] + n; + const cont = context[from..@min(context.len, from + max_nodes)]; + if (cont.len > best.len) { + best = cont; + if (best.len == max_nodes) break; + } + } + return if (best.len >= n) best else &.{}; + } +}; + +/// decode.next_copy_rows: a copy's next window, twice as wide after a whole copy, half after a broken one. +pub fn nextCopyRows(rows: usize, whole: bool, tree_rows: usize, max_rows: usize) usize { + const first = @min(max_rows, @max(tree_rows, 16)); + return if (whole) @min(max_rows, @max(rows, first) * 2) else @max(first, @min(rows, max_rows) / 2); +} + +pub const Stats = struct { rounds: usize = 0, drafted: usize = 0, accepted: usize = 0 }; + +/// prefill_state with a drafter: the prompt in even chunks, its last `window` rows' taps into the context. +pub fn prefill(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32) !void { + return prefillMedia(e, seq, ctx, d, prompt, null); +} + +/// prefill with an image prompt's rows and positions (null: text); its decode offset stays on the stream. +pub fn prefillMedia(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, media: ?*const @import("vision.zig").Media) !void { + return prefillFrom(e, seq, ctx, d, prompt, 0, media, null); +} + +/// prefillMedia from `from` (0, or a restored grid point), keeping states at `keep`'s marks; drafts change no token. +pub fn prefillFrom(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, from: usize, media: ?*const @import("vision.zig").Media, keep: ?eng.Keep) !void { + if (prompt.len >= seq.capacity) return error.PromptTooLong; + if (from == 0) try seq.reset(e.ops(), e.w.g) else if (from != seq.pos or !eng.resumable(from, prompt.len)) return error.BadReuse; + seq.media = media; + defer seq.media = null; + defer if (media) |m| { + seq.rope_delta = m.delta; + }; + ctx.len = 0; + ctx.end = 0; + const tap_from = @max(from, prompt.len -| dl.window); + ctx.skip(tap_from); + var f = e.forward(); + f.taps = e.scratch.taps; + var it = eng.Chunks.init(prompt.len, from, e.grid); + while (it.next()) |b| { + try f.chunk(prompt[b[0]..b[1]], seq, b[1] == prompt.len); + eng.Keep.after(keep, b[1]); + if (b[1] <= tap_from) continue; + const skip = tap_from -| b[0]; + try d.absorb(ctx, e.scratch.taps + skip * taps_width * bf, b[1] - b[0] - skip); + } +} + +/// draft_decode, greedy: rounds until `count` tokens or an end token; the first token is `pending`. +pub fn decode(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, pending: u32, count: usize, max_rows: usize, out: *std.ArrayList(u32), stats: *Stats) !void { + const gpa = e.gpa; + var context: std.ArrayList(u32) = .empty; + defer context.deinit(gpa); + try context.appendSlice(gpa, prompt); + try out.append(gpa, pending); + try context.append(gpa, pending); + var copies: CopyIndex = .{ .gpa = gpa }; + defer copies.deinit(); + const tree_rows = max_rows; + var copy_rows = nextCopyRows(tree_rows, false, tree_rows, max_rows); + var tokens: [st.max_rows]u32 = undefined; + var parents: [st.max_rows]i32 = undefined; + var sampled: [st.max_rows]u32 = undefined; + var path: [st.max_rows]u32 = undefined; + var f = e.forward(); + f.taps = e.scratch.taps; + while (out.items.len < count and !e.w.isEos(out.items[out.items.len - 1])) { + const last = out.items[out.items.len - 1]; + tokens[0] = last; + parents[0] = -1; + var rows: usize = 1; + const copied = try copies.propose(context.items, copy_rows - 1); + if (copied.len > 0) { + for (copied, 1..) |t, r| { + tokens[r] = t; + parents[r] = @as(i32, @intCast(r)) - 1; + } + rows += copied.len; + } else if (ctx.len > 0) { + const p = try d.propose(ctx, last, context.items.len, tree_rows - 1, null); + for (p.tokens, p.parents, 1..) |t, pr, r| { + tokens[r] = t; + parents[r] = if (pr < 0) 0 else pr + 1; + } + rows += p.tokens.len; + } + const part = [_]Part{.{ .seq = seq, .tokens = tokens[0..rows], .parents = parents[0..rows] }}; + try f.round(&part); + try f.picks(rows, &sampled); + // the path: from the root, each next token the child whose token the target drew + var n: usize = 1; + path[0] = 0; + var terminal = sampled[0]; + while (out.items.len + n < count and !e.w.isEos(terminal)) { + const child = for (1..rows) |r| { + if (parents[r] == @as(i32, @intCast(path[n - 1])) and tokens[r] == terminal) break r; + } else break; + path[n] = @intCast(child); + n += 1; + terminal = sampled[child]; + } + try f.commit(&part, &.{path[0..n]}); + // the drafter reads the kept rows' taps, gathered in path order + var items: [st.max_rows]kern.Copy = undefined; + const gathered = e.scratch.taps + st.max_rows * taps_width * bf; + for (path[0..n], 0..) |row, j| items[j] = .{ .dst = gathered + j * taps_width * bf, .src = e.scratch.taps + row * taps_width * bf, .bytes = taps_width * bf }; + try f.ops.upload(e.scratch.copy_items, std.mem.sliceAsBytes(items[0..n])); + try f.ops.copies(e.scratch.copy_items, n); + try d.absorb(ctx, gathered, n); + for (path[1..n]) |row| { + try out.append(gpa, tokens[row]); + try context.append(gpa, tokens[row]); + } + try out.append(gpa, terminal); + try context.append(gpa, terminal); + if (copied.len > 0) copy_rows = nextCopyRows(copy_rows, n == rows, tree_rows, max_rows); + stats.rounds += 1; + stats.drafted += rows - 1; + stats.accepted += n - 1; + } +} + +test "copy windows grow after whole copies and shrink after broken ones" { + try std.testing.expectEqual(@as(usize, 12), nextCopyRows(12, false, 12, 12)); + try std.testing.expectEqual(@as(usize, 12), nextCopyRows(12, true, 12, 12)); + try std.testing.expectEqual(@as(usize, 16), nextCopyRows(16, false, 12, 64)); + try std.testing.expectEqual(@as(usize, 32), nextCopyRows(16, true, 12, 64)); +} + +test "copies propose the latest earlier continuation of the last 8 tokens" { + const gpa = std.testing.allocator; + var x: CopyIndex = .{ .gpa = gpa }; + defer x.deinit(); + const ctx = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1, 2, 3, 4, 5, 6, 7, 8 }; + try std.testing.expectEqualSlices(u32, &.{ 9, 10, 11, 12, 13, 14, 15, 16 }, try x.propose(&ctx, 8)); + try std.testing.expectEqual(@as(usize, 0), (try x.propose(ctx[0..15], 8)).len); +} diff --git a/zig/src/families/qwen27/cuda/native.zig b/zig/src/families/qwen27/cuda/native.zig new file mode 100644 index 0000000000..cbe9817214 --- /dev/null +++ b/zig/src/families/qwen27/cuda/native.zig @@ -0,0 +1,166 @@ +//! Qwen3.5-family dense models on CUDA behind the native family interface (native/cuda.zig's registry). + +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const engine = @import("engine.zig"); +const Lanes = @import("lanes.zig").Cuda; +const dr = @import("draft.zig"); +const vision = @import("vision.zig"); +const image = @import("image.zig"); +const reuse = @import("reuse.zig"); + +pub const model_type = "qwen3_5"; +pub const formats: []const []const u8 = &.{"mlx-q4g64"}; +pub const default_context: i64 = 32768; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = engine.prompt_rows; +/// --drafter: the DFlash2 checkpoint the 27B drafts with (it has no MTP head of its own). +pub const takes_drafter = true; + +/// Prompt-cache copies (reuse.zig), kept in pinned host memory; a state ends where its prompt pass stands. +pub const snap_bytes = reuse.bytes; +pub const snap_save = reuse.save; +pub const snap_restore = reuse.restore; +pub const snap_drop = reuse.drop; +pub const snap_host = true; +pub const snap_lookahead: u32 = 0; + +/// The server keeps prompt states: prompts cut the zero-anchored grid, where kept states resume. +pub fn useCache(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + own.e.grid = true; +} + +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, vision: ?Vision = null, kv8: bool = false }; + +/// --vision's limits: the visual tokens a request's images share, and its images. +pub const Vision = struct { image_tokens: u32, max_images: u32 }; + +/// The image placeholder the chat template writes once an image, and the tokens it wraps it in. +pub const image_token = vision.image_token; +pub const image_markers = [_]u32{ vision.vision_start, vision.image_token, vision.vision_end }; + +/// Info.vision's prepare: an image's bytes to the tower's patches (image.zig), on the HTTP thread. +pub fn prepareImage(a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !image.Prepared { + return image.prepare(a, bytes, max_tokens); +} + +/// A lone drafted stream's own driver (none here: one stream decodes in the lane core too, as under --parallel). +pub const LoneRun = *const fn (ctx: *anyopaque, s: *lanes.Stream, hooks: *anyopaque, committed: *const fn (*anyopaque) void, yield: *const fn (*anyopaque) bool, resumed: bool) anyerror!bool; + +/// What the native server drives: the lane backend, the facts its round loop reads, and how to free it. +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + /// Device bytes each admitted stream allocates for its own state and caches. + stream_bytes: usize, + /// Streams that allocate nothing (none here: every stream's state is its own). + free_streams: u32 = 0, + /// What a --slide trainer keeps out of the streams' room (none: the 27B does not learn on CUDA yet). + learn_bytes: usize = 0, + /// What the image tower keeps out of the streams' room (--vision): one call's scratch and a request's rows. + vision_bytes: usize = 0, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + lone: ?LoneRun = null, + target: *reuse.Target, // what the prompt cache copies (reuse.zig) +}; + +const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, target: reuse.Target = undefined, draft: ?*dr.DFlash2 = null, tower: ?*vision.Tower = null }; + +/// The drafter the Python engine pairs with the 27B once pulled (z-lab/Qwen3.8-27B-DFlash2). +const drafter_repo = "models--z-lab--Qwen3.8-27B-DFlash2"; + +fn getenv(name: [:0]const u8) ?[]const u8 { + return std.mem.span(std.c.getenv(name) orelse return null); +} + +/// --drafter, else the pulled drafter's snapshot in the Hugging Face cache; null when neither holds one. +fn drafterDir(a: std.mem.Allocator, io: std.Io, given: ?[]const u8) !?[]const u8 { + if (given) |d| return try a.dupe(u8, d); + const hub = if (getenv("HF_HUB_CACHE")) |h| try a.dupe(u8, h) else if (getenv("HF_HOME")) |h| try std.fs.path.join(a, &.{ h, "hub" }) else blk: { + const home = getenv("HOME") orelse return null; + break :blk try std.fs.path.join(a, &.{ home, ".cache", "huggingface", "hub" }); + }; + defer a.free(hub); + const snaps = try std.fs.path.join(a, &.{ hub, drafter_repo, "snapshots" }); + defer a.free(snaps); + var dir = std.Io.Dir.cwd().openDir(io, snaps, .{ .iterate = true }) catch return null; + defer dir.close(io); + var it = dir.iterate(); + while (try it.next(io)) |entry| if (entry.kind == .directory) return try std.fs.path.join(a, &.{ snaps, entry.name }); + return null; +} + +/// The streams the lane core may admit at most; the server's memory admission picks how many fit. +const most_streams = 32; + +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + // the 27B's glue runs the Python engine's Triton kernels, captured on this chip (no own glue kernels yet) + const e = try engine.Engine.init(gpa, io, ctx, dir, kernels orelse return error.QwenNeedsCapturedKernels, .{ .context = o.context, .kv8 = o.kv8 }); + errdefer e.deinit(); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + own.* = .{ .gpa = gpa, .e = e, .lanes = try Lanes.init(gpa, e, most_streams) }; + errdefer own.lanes.deinit(); + own.target = .{ .e = e, .seqs = &own.lanes.seqs }; + if (o.drafts) if (try drafterDir(gpa, io, o.drafter)) |draft_dir| { + defer gpa.free(draft_dir); + const f = e.forward(); + own.draft = try dr.DFlash2.init(gpa, io, f.ops, f.t, &e.w, draft_dir, dir); + own.lanes.drafter = own.draft; + std.log.info("DFlash2 drafts every stream: {s}", .{draft_dir}); + // the forward's ms by rows: a shared round's tree widths follow the curve + try own.lanes.calibrate(io, most_streams); + }; + var vision_bytes: usize = 0; + if (o.vision) |v| { + const ops = e.ops(); + own.tower = try vision.Tower.load(gpa, io, .{ .d = ops.k.d, .s = ops.s, .discrete = ops.k.discrete }, dir); + own.lanes.tower = own.tower; + vision_bytes = vision.Tower.scratchBytes(vision.max_patches) + @as(usize, v.image_tokens) * vision.out_hidden * 2 + engine.prompt_rows * 16; + std.log.info("image tower loaded: {d:.2} GiB, {d:.2} GiB kept for one image call", .{ @as(f64, @floatFromInt(own.tower.?.weight_bytes)) / (1 << 30), @as(f64, @floatFromInt(vision_bytes)) / (1 << 30) }); + } + return .{ + .backend = own.lanes.backend(), + .facts = own.lanes.facts(), + .rows = st.max_rows, + // each stream's caches, its drafter context, and its share of a round's attention partials (`fit`) + .stream_bytes = st.Seq.bytes(e.w.g, o.context, o.kv8) + st.Scratch.partialBytes(e.w.g, st.Scratch.streamPartRows(o.context)) + if (own.draft != null) dr.Context.bytes() else 0, + .vision_bytes = vision_bytes, + .ctx = own, + .deinit = release, + .target = &own.target, + }; +} + +/// After admission: attention's partials sized for the `streams` the budget admitted. +pub fn fit(p: *anyopaque, streams: u32) !void { + const own: *Owned = @ptrCast(@alignCast(p)); + try own.e.fit(@min(streams, st.max_streams)); +} + +/// A request this engine refuses, in words; null: none of its own. +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.PromptTooLong => "the prompt and its reply exceed this server's context window: shorten it or lower max_tokens", + error.OutOfDeviceMemory => "the GPU had no memory left for this request's caches: retry once another request ends", + error.QwenCheckpointHasNoDraftHead => "this checkpoint has no draft head on CUDA yet: serve with --no-drafts", + error.VisionDisabled => "image input needs this server started with --vision", + error.BadImagePlaceholders => "the image placeholders do not match the prepared images", + else => null, + }; +} + +fn release(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + own.lanes.deinit(); + if (own.draft) |d| d.deinit(); + if (own.tower) |t| t.deinit(); + own.e.deinit(); + own.gpa.destroy(own); +} diff --git a/zig/src/families/qwen27/cuda/reuse.zig b/zig/src/families/qwen27/cuda/reuse.zig new file mode 100644 index 0000000000..c8e36ded25 --- /dev/null +++ b/zig/src/families/qwen27/cuda/reuse.zig @@ -0,0 +1,124 @@ +//! Qwen3.8-27B CUDA prompt states for the shared cache: DeltaNet recurrences, conv windows and attention rows on host. + +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const Engine = @import("engine.zig").Engine; + +/// One kept state: the copy and the position it holds. +pub const Copy = struct { + host: cuda.HostBuffer, + at: usize, +}; + +/// The engine and the streams' states a save copies. The native host keeps one of these for the loaded model. +pub const Target = struct { + e: *Engine, + seqs: *std.AutoHashMapUnmanaged(*lanes.Stream, *st.Seq), +}; + +/// One piece of a stream's state: its device address and length. +const Piece = struct { dev: u64, len: usize }; + +/// A state at `at`'s pieces in copy order (DeltaNet state, conv windows, `at` K/V rows, kv8 scales); seq null: lengths. +fn pieces(g: c.Geometry, kv8: bool, seq: ?*const st.Seq, at: usize, out: []Piece) []Piece { + var n: usize = 0; + const row: usize = g.kvInner() * @as(usize, if (kv8) 1 else 2); + for (0..g.layers) |i| { + if (c.linear(i)) { + out[n] = .{ .dev = if (seq) |s| s.rec[i] else 0, .len = g.deltaBytes() }; + out[n + 1] = .{ .dev = if (seq) |s| s.conv[i] else 0, .len = g.convBytes() }; + n += 2; + continue; + } + out[n] = .{ .dev = if (seq) |s| s.keys[i] else 0, .len = at * row }; + out[n + 1] = .{ .dev = if (seq) |s| s.values[i] else 0, .len = at * row }; + n += 2; + if (kv8) { + out[n] = .{ .dev = if (seq) |s| s.kscale[i] else 0, .len = at * g.kv_heads * 4 }; + out[n + 1] = .{ .dev = if (seq) |s| s.vscale[i] else 0, .len = at * g.kv_heads * 4 }; + n += 2; + } + } + return out[0..n]; +} + +const max_pieces = 4 * 128; + +fn total(g: c.Geometry, kv8: bool, at: usize) u64 { + var buf: [max_pieces]Piece = undefined; + var n: u64 = 0; + for (pieces(g, kv8, null, at, &buf)) |p| n += p.len; + return n; +} + +/// Host bytes a save at `at` takes. +pub fn bytes(ptr: *anyopaque, at: u32) u64 { + const t: *Target = @ptrCast(@alignCast(ptr)); + return total(t.e.w.g, t.e.kv8, at); +} + +/// Copy the stream's state after `at` prompt tokens. Its pass stands there. +pub fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + const t: *Target = @ptrCast(@alignCast(ptr)); + const s: *lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoStream)); + const seq = t.seqs.get(s) orelse return error.UnknownStream; + if (seq.pos != at or seq.rope_delta != 0) return error.NotAtMark; + const e = t.e; + const copy = try e.gpa.create(Copy); + errdefer e.gpa.destroy(copy); + copy.* = .{ .host = try cuda.HostBuffer.alloc(e.ctx.d, total(e.w.g, e.kv8, at)), .at = at }; + errdefer copy.host.free(); + var buf: [max_pieces]Piece = undefined; + var off: usize = 0; + for (pieces(e.w.g, e.kv8, seq, at, &buf)) |p| { + try e.ops().download(copy.host.bytes[off..][0..p.len], p.dev); + off += p.len; + } + try e.s.synchronize(); + return copy; +} + +/// Make `seq` the kept state's: the next prompt chunk starts at its position. +pub fn restoreSeq(e: *Engine, seq: *st.Seq, saved: *anyopaque) !void { + const copy: *Copy = @ptrCast(@alignCast(saved)); + if (copy.at >= seq.capacity) return error.BadReuse; + var buf: [max_pieces]Piece = undefined; + var off: usize = 0; + for (pieces(e.w.g, e.kv8, seq, copy.at, &buf)) |p| { + try e.ops().upload(p.dev, copy.host.bytes[off..][0..p.len]); + off += p.len; + } + try e.s.synchronize(); // the host copy may be dropped once this returns + seq.pos = copy.at; + seq.rope_delta = 0; + seq.media = null; +} + +/// The store's restore: the owner's state made the kept one's. +pub fn restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + const t: *Target = @ptrCast(@alignCast(ptr)); + const s: *lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoStream)); + return restoreSeq(t.e, t.seqs.get(s) orelse return error.UnknownStream, saved); +} + +/// Free a kept state's host copy. +pub fn drop(ptr: *anyopaque, saved: *anyopaque) void { + const t: *Target = @ptrCast(@alignCast(ptr)); + const copy: *Copy = @ptrCast(@alignCast(saved)); + copy.host.free(); + t.e.gpa.destroy(copy); +} + +test "a kept state holds the recurrences whole and the attention rows it read" { + const g = c.the_27b; + var buf: [max_pieces]Piece = undefined; + try std.testing.expectEqual(@as(usize, 48 * 2 + 16 * 2), pieces(g, false, null, 1, &buf).len); + try std.testing.expectEqual(@as(usize, 48 * 2 + 16 * 4), pieces(g, true, null, 1, &buf).len); + const fixed = total(g, false, 0); + try std.testing.expectEqual(fixed, 48 * (g.deltaBytes() + g.convBytes())); + try std.testing.expectEqual(fixed + 16 * 2 * 1000 * g.kvInner() * 2, total(g, false, 1000)); + try std.testing.expectEqual(fixed + 16 * 2 * 1000 * (g.kvInner() + g.kv_heads * 4), total(g, true, 1000)); +} diff --git a/zig/src/families/qwen27/cuda/round.zig b/zig/src/families/qwen27/cuda/round.zig new file mode 100644 index 0000000000..0d355ce181 --- /dev/null +++ b/zig/src/families/qwen27/cuda/round.zig @@ -0,0 +1,265 @@ +//! A verify round's inputs laid out as tree_forward or multi_tree_forward lays them (Triton variants follow alignment). + +const std = @import("std"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const tree = @import("tree.zig"); + +const bf = 2; + +/// One stream's window: its tokens from its committed position, and each row's parent (null: a chain). +pub const Part = struct { seq: *st.Seq, tokens: []const u32, parents: ?[]const i32 = null }; + +/// Where a round's inputs live on the device, and what the layer loop launches with. +pub const Round = struct { + rows: usize, + streams: usize, + multi: bool, + ids: u64, + pos: u64, + windows: u64, + sids: u64, // multi: each row's stream; else the windows again (gdn_pre passes WIN as SID) + plan: u64, // GDN schedule entries (rows, 3) + starts: u64, // stream row starts (streams + 1) + slots: usize, // the GDN schedule's live states (0: every window a chain) + most: usize, // the most rows a stream's window holds + tables: u64, // multi: (DeltaNet layers, streams) state pointers, a layer's row at its DeltaNet index + attn: tri.Tri.Plan, + offs: u64, // (attention layers, streams, 2) int64 cache offsets (4 under kv8: scales too); single: by layer + kv8: bool, // the streams' caches are e4m3 with scales (attention8) + starts_host: [st.max_streams + 1]usize, + + /// The conv rows gdn_pre reads for layer `i` (its DeltaNet index `j`): the stream's own, or the stacked copy. + pub fn conv(r: *const Round, parts: []const Part, s: *const st.Scratch, g: c.Geometry, i: usize, j: usize) u64 { + if (!r.multi) return parts[0].seq.conv[i]; + return s.conv_cat + j * st.max_streams * (c.conv_taps - 1) * g.convDim() * bf; + } + + /// Layer `i`'s attention cache offsets: tree_forward's (one stream, by layer) or the packed (layer, streams) rows. + pub fn offsets(r: *const Round, i: usize, a: usize) u64 { + const each: usize = if (r.kv8) 32 else 16; + return if (r.multi) r.offs + a * r.streams * each else r.offs + i * each; + } + + /// The DeltaNet state table of DeltaNet layer `j` (multi only). + pub fn table(r: *const Round, j: usize) u64 { + return r.tables + j * r.streams * 8; + } +}; + +/// A part's parents: its own tree's, or a chain's. +pub fn parentsOf(p: Part, buf: []i32) []const i32 { + if (p.parents) |x| return x; + for (buf[0..p.tokens.len], 0..) |*x, r| x.* = @as(i32, @intCast(r)) - 1; + return buf[0..p.tokens.len]; +} + +/// Segment offsets in ints of attnPlan's plan_host, each on a 16-byte boundary for Triton's aligned plan pointers. +const AttnAt = struct { n_items: usize, streams: usize, items: usize, parents: usize }; + +fn pad16(out: *std.ArrayList(i32), gpa: std.mem.Allocator, from: usize) !usize { + while ((out.items.len - from) % 4 != 0) try out.append(gpa, 0); + return out.items.len - from; +} + +fn attnPlan(gpa: std.mem.Allocator, out: *std.ArrayList(i32), parts: []const Part, group: usize) !AttnAt { + const from = out.items.len; + var at: AttnAt = undefined; + for (parts, 0..) |p, s| for (p.tokens) |_| try out.append(gpa, @intCast(s)); + at.streams = try pad16(out, gpa, from); + var start: usize = 0; + for (parts) |p| { + const w = p.tokens.len; + try out.appendSlice(gpa, &.{ @intCast(start), @intCast(w), @intCast(p.seq.pos), @intCast(tri.slots(p.seq.pos, w)) }); + start += w; + } + at.items = try pad16(out, gpa, from); + var n_items: usize = 0; + for (parts, 0..) |p, s| { + const w = p.tokens.len; + const folded = tri.groups(p.seq.pos, w); + const loose = p.seq.pos / tri.chunk - folded * tri.group_chunks; + for (0..folded + loose) |j| { + const code: i32 = if (j < folded) @intCast(j) else -1 - @as(i32, @intCast(j - folded)); + var first: usize = 0; + while (first < w * group) : (first += 16) { + try out.appendSlice(gpa, &.{ @intCast(s), @intCast(first), code }); + n_items += 1; + } + } + } + at.parents = try pad16(out, gpa, from); + start = 0; + var buf: [tree.max_nodes]i32 = undefined; + for (parts) |p| { + for (parentsOf(p, &buf)) |x| try out.append(gpa, if (x < 0) -1 else @intCast(start + @as(usize, @intCast(x)))); + start += p.tokens.len; + } + at.n_items = n_items; + return at; +} + +/// Each stream's key and value caches as bf16 element offsets from the scratch's origin. +fn offsetOf(s: *const st.Scratch, ptr: u64) i64 { + return @divExact(@as(i64, @bitCast(ptr -% s.origin)), bf); +} + +/// Layer `i`'s cache offsets for a stream: bf16 elements of keys and values, or under kv8 e4m3 bytes plus fp32 scales. +fn cacheOffsets(s: *const st.Scratch, seq: *const st.Seq, i: usize, out: *std.ArrayList(i64), gpa: std.mem.Allocator) !void { + if (!seq.kv8) return out.appendSlice(gpa, &.{ offsetOf(s, seq.keys[i]), offsetOf(s, seq.values[i]) }); + const d = struct { + fn at(sc: *const st.Scratch, ptr: u64, size: i64) i64 { + return @divExact(@as(i64, @bitCast(ptr -% sc.origin)), size); + } + }; + try out.appendSlice(gpa, &.{ d.at(s, seq.keys[i], 1), d.at(s, seq.values[i], 1), d.at(s, seq.kscale[i], 4), d.at(s, seq.vscale[i], 4) }); +} + +/// Every stream's host plans: positions (pos + depth), the GDN schedule (nodes offset by its start), conv windows. +const Host = struct { pos: std.ArrayList(i32) = .empty, entries: std.ArrayList(i32) = .empty, windows: std.ArrayList(i32) = .empty, slots: usize = 0, most: usize = 0 }; + +fn plans(gpa: std.mem.Allocator, parts: []const Part, starts: []const usize, multi: bool, h: *Host) !void { + const keep = c.conv_taps - 1; + var buf: [tree.max_nodes]i32 = undefined; + var dep: [tree.max_nodes]usize = undefined; + var win: [tree.max_nodes * c.conv_taps]i32 = undefined; + for (parts, 0..) |p, k| { + const parents = parentsOf(p, &buf); + const w = parents.len; + try tree.depths(parents, dep[0..w]); + for (dep[0..w]) |d| try h.pos.append(gpa, @as(i32, @intCast(p.seq.pos + d)) + p.seq.rope_delta); + const s = try tree.schedule(gpa, parents); + defer gpa.free(s.entries); + for (s.entries, 0..) |x, j| try h.entries.append(gpa, if (j % 3 == 0) x + @as(i32, @intCast(starts[k])) else x); + h.slots = @max(h.slots, s.slots); + h.most = @max(h.most, w); + // one stream's windows index [its state; its rows]; several streams' index [their states; all rows] + tree.convWindows(parents, keep, if (multi) starts[k] else 0, win[0 .. w * (keep + 1)]); + try h.windows.appendSlice(gpa, win[0 .. w * (keep + 1)]); + } +} + +/// Uploads the round's inputs and runs attention's _paths; the caller's layer loop reads the returned Round. +pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, g: c.Geometry, parts: []const Part) !Round { + if (parts.len == 0 or parts.len > st.max_streams) return error.InvalidQwenWindows; + var W: usize = 0; + var r: Round = undefined; + r.starts_host[0] = 0; + for (parts, 0..) |p, k| { + if (p.tokens.len == 0 or p.tokens.len > tree.max_nodes) return error.InvalidQwenWindows; + if (p.parents) |x| if (x.len != p.tokens.len) return error.InvalidQwenWindows; + if (p.seq.pos + p.tokens.len > p.seq.capacity) return error.PromptTooLong; + W += p.tokens.len; + r.starts_host[k + 1] = W; + } + if (W > st.round_rows) return error.WindowTooWide; + // attention's partials: the most slots any stream takes, for every row of the round + var most_slots: usize = 0; + for (parts) |p| { + most_slots = @max(most_slots, tri.slots(p.seq.pos, p.tokens.len)); + if (p.seq.kv8 != parts[0].seq.kv8) return error.InvalidQwenWindows; + } + if (most_slots * W > s.part_rows) return error.WindowTooWide; + r.kv8 = parts[0].seq.kv8; + r.rows = W; + r.streams = parts.len; + r.multi = parts.len > 1; + const S = parts.len; + const group = g.query_heads / g.kv_heads; + var h: Host = .{}; + defer { + h.pos.deinit(gpa); + h.entries.deinit(gpa); + h.windows.deinit(gpa); + } + try plans(gpa, parts, r.starts_host[0 .. S + 1], r.multi, &h); + r.slots = h.slots; + r.most = h.most; + var host: std.ArrayList(i32) = .empty; + defer host.deinit(gpa); + var offs: std.ArrayList(i64) = .empty; + defer offs.deinit(gpa); + if (!r.multi) { + // tree_forward: tokens, positions, plan (entries then starts), windows and attention's plan apart + const p = parts[0]; + for (p.tokens) |tok| try host.append(gpa, @intCast(tok)); + try ops.upload(s.ids, std.mem.sliceAsBytes(host.items)); + try ops.upload(s.pos, std.mem.sliceAsBytes(h.pos.items)); + try ops.upload(s.windows, std.mem.sliceAsBytes(h.windows.items)); + try ops.s.synchronize(); + host.clearRetainingCapacity(); + try host.appendSlice(gpa, h.entries.items); + try host.appendSlice(gpa, &.{ 0, @intCast(W) }); + try ops.upload(s.plan, std.mem.sliceAsBytes(host.items)); + try ops.s.synchronize(); + host.clearRetainingCapacity(); + const ap = try attnPlan(gpa, &host, parts, group); + try ops.upload(s.attn_plan, std.mem.sliceAsBytes(host.items)); + try ops.s.synchronize(); + for (0..g.layers) |i| if (c.linear(i)) try offs.appendNTimes(gpa, 0, if (r.kv8) 4 else 2) else try cacheOffsets(s, p.seq, i, &offs, gpa); + try ops.upload(s.offs, std.mem.sliceAsBytes(offs.items)); + try ops.s.synchronize(); + r.ids = s.ids; + r.pos = s.pos; + r.windows = s.windows; + r.sids = s.windows; + r.plan = s.plan; + r.starts = s.plan + 3 * W * 4; + r.tables = 0; + r.offs = s.offs; + r.attn = .{ .rows = s.attn_plan, .streams = s.attn_plan + ap.streams * 4, .items = s.attn_plan + ap.items * 4, .n_items = ap.n_items, .paths = s.paths, .depths = s.depths, .width = W }; + try t.paths(s.attn_plan + ap.parents * 4, s.paths, s.depths, W); + return r; + } + // multi_tree_forward: positions, stream ids, plan entries, starts, ids, windows, attention's plan in one copy + try host.appendSlice(gpa, h.pos.items); + for (parts, 0..) |p, k| for (p.tokens) |_| try host.append(gpa, @intCast(k)); + try host.appendSlice(gpa, h.entries.items); + for (r.starts_host[0 .. S + 1]) |x| try host.append(gpa, @intCast(x)); + for (parts) |p| for (p.tokens) |tok| try host.append(gpa, @intCast(tok)); + try host.appendSlice(gpa, h.windows.items); + while (host.items.len % 4 != 0) try host.append(gpa, 0); // the attention plan from a 16-byte boundary + const at_attn = host.items.len; + const ap = try attnPlan(gpa, &host, parts, group); + try ops.upload(s.round, std.mem.sliceAsBytes(host.items)); + try ops.s.synchronize(); + const base = s.round; + r.pos = base; + r.sids = base + W * 4; + r.plan = base + 2 * W * 4; + r.starts = base + 5 * W * 4; + r.ids = base + (5 * W + S + 1) * 4; + r.windows = base + (6 * W + S + 1) * 4; + const ab = base + at_attn * 4; + r.attn = .{ .rows = ab, .streams = ab + ap.streams * 4, .items = ab + ap.items * 4, .n_items = ap.n_items, .paths = s.paths, .depths = s.depths, .width = W }; + // the state pointer table and cache offsets, one copy each; every stream's conv rows stacked by layer + var ptrs: std.ArrayList(u64) = .empty; + defer ptrs.deinit(gpa); + var stack: std.ArrayList(kern.Copy) = .empty; + defer stack.deinit(gpa); + const keep = c.conv_taps - 1; + var j: usize = 0; + for (0..g.layers) |i| { + if (!c.linear(i)) { + for (parts) |p| try cacheOffsets(s, p.seq, i, &offs, gpa); + continue; + } + const cat = s.conv_cat + j * st.max_streams * keep * g.convDim() * bf; + for (parts, 0..) |p, k| { + try ptrs.append(gpa, p.seq.rec[i]); + try stack.append(gpa, .{ .dst = cat + k * keep * g.convDim() * bf, .src = p.seq.conv[i], .bytes = keep * g.convDim() * bf }); + } + j += 1; + } + try ops.upload(s.tables, std.mem.sliceAsBytes(ptrs.items)); + try ops.upload(s.offs, std.mem.sliceAsBytes(offs.items)); + try ops.upload(s.copy_items, std.mem.sliceAsBytes(stack.items)); + try ops.copies(s.copy_items, stack.items.len); + try ops.s.synchronize(); + r.tables = s.tables; + r.offs = s.offs; + try t.paths(ab + ap.parents * 4, s.paths, s.depths, W); + return r; +} diff --git a/zig/src/families/qwen27/cuda/shape.zig b/zig/src/families/qwen27/cuda/shape.zig new file mode 100644 index 0000000000..b018dc22a1 --- /dev/null +++ b/zig/src/families/qwen27/cuda/shape.zig @@ -0,0 +1,102 @@ +//! The shapes the CUDA engine is built for: the family's parsed config (config.zig), held to the 27B's. +const std = @import("std"); +const config = @import("../config.zig"); + +pub const vocab = 248320; +pub const linear_dim = 128; // a DeltaNet key or value head's width +pub const conv_taps = 4; +pub const head_dim = 256; +pub const rotary_dim = 64; +pub const eps: f32 = 1e-6; +pub const theta: f32 = 10000000; + +/// Whether layer `index` is a DeltaNet layer: every fourth is attention. +pub fn linear(index: usize) bool { + return index % 4 != 3; +} + +/// The widths a forward sizes its buffers by. +pub const Geometry = struct { + hidden: usize, + intermediate: usize, + layers: usize, + linear_k_heads: usize, // DeltaNet key (and query) heads + linear_v_heads: usize, // DeltaNet value heads, each key head serving a run of them + query_heads: usize, + kv_heads: usize, + + /// The DeltaNet input projection's row: queries, keys, then values. + pub fn convDim(g: Geometry) usize { + return (2 * g.linear_k_heads + g.linear_v_heads) * linear_dim; + } + pub fn kInner(g: Geometry) usize { + return g.linear_k_heads * linear_dim; + } + pub fn vInner(g: Geometry) usize { + return g.linear_v_heads * linear_dim; + } + pub fn qInner(g: Geometry) usize { + return g.query_heads * head_dim; + } + pub fn kvInner(g: Geometry) usize { + return g.kv_heads * head_dim; + } + /// The widest row an activation buffer holds: the recurrence's values or the attention's heads. + pub fn inner(g: Geometry) usize { + return @max(g.vInner(), g.qInner()); + } + /// One layer's recurrent state (fp32) and its conv window (bf16). + pub fn deltaBytes(g: Geometry) usize { + return g.linear_v_heads * linear_dim * linear_dim * 4; + } + pub fn convBytes(g: Geometry) usize { + return (conv_taps - 1) * g.convDim() * 2; + } +}; + +/// Qwen3.8-27B, the one checkpoint shape the CUDA engine serves. +pub const the_27b: Geometry = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .linear_k_heads = 16, .linear_v_heads = 48, .query_heads = 24, .kv_heads = 4 }; + +/// A checkpoint's config.json (and generation_config.json's end tokens), refused unless it is the 27B's. +pub const Config = struct { + g: Geometry, + eos: [config.max_eos]u32, + eos_count: usize, + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const text = try file(gpa, io, dir, "config.json") orelse return error.MissingConfig; + defer gpa.free(text); + const generation = try file(gpa, io, dir, "generation_config.json"); + defer if (generation) |x| gpa.free(x); + return check(try config.parse(gpa, text, generation)); + } + + fn file(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, name: []const u8) !?[]u8 { + const path = try std.fs.path.join(gpa, &.{ dir, name }); + defer gpa.free(path); + return std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)) catch |err| switch (err) { + error.FileNotFound => null, + else => err, + }; + } +}; + +/// The parsed config as the CUDA engine's Config, when every shape the kernels assume is the 27B's. +pub fn check(c: config.Config) !Config { + const g: Geometry = .{ .hidden = c.hidden, .intermediate = c.intermediate, .layers = c.layers, .linear_k_heads = c.k_heads, .linear_v_heads = c.v_heads, .query_heads = c.heads, .kv_heads = c.kv_heads }; + if (!std.meta.eql(g, the_27b) or c.vocab != vocab or c.head_dim != head_dim or c.dk != linear_dim or c.dv != linear_dim) return error.UnsupportedQwenGeometry; + if (c.conv_kernel != conv_taps or c.rope_dims != rotary_dim or c.eps != eps or c.rope_theta != theta) return error.UnsupportedQwenGeometry; + for (c.kinds[0..c.layers], 0..) |kind, i| if ((kind == .linear) != linear(i)) return error.UnsupportedQwenGeometry; + return .{ .g = g, .eos = c.eos, .eos_count = c.eos_count }; +} + +test "the 27B's shapes pass and another hidden size is refused" { + var c: config.Config = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .vocab = vocab, .heads = 24, .kv_heads = 4, .head_dim = head_dim, .k_heads = 16, .v_heads = 48, .dk = linear_dim, .dv = linear_dim, .conv_kernel = conv_taps, .eps = eps, .rope_dims = rotary_dim, .rope_theta = theta }; + for (c.kinds[0..64], 0..) |*k, i| k.* = if (linear(i)) .linear else .attention; + c.eos[0] = 248044; + c.eos_count = 1; + const ok = try check(c); + try std.testing.expectEqual(@as(usize, 1), ok.eos_count); + c.hidden = 2048; + try std.testing.expectError(error.UnsupportedQwenGeometry, check(c)); +} diff --git a/zig/src/families/qwen27/cuda/state.zig b/zig/src/families/qwen27/cuda/state.zig new file mode 100644 index 0000000000..433102b490 --- /dev/null +++ b/zig/src/families/qwen27/cuda/state.zig @@ -0,0 +1,354 @@ +//! A stream's committed state (DeltaNet recurrences, conv windows, attention caches) and the forward's scratch. + +const std = @import("std"); +const cuda = @import("cuda"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const vision = @import("vision.zig"); +const torch_ops = kern.torch_ops; + +/// The most rows a stream's verify window takes (the multi-stream GDN tree kernel's limit). +pub const max_rows = 16; +/// The most streams a shared round takes. +pub const max_streams = 16; +/// The most rows a verify round takes: every stream's whole window. +pub const round_rows = max_rows * max_streams; +/// The most items a batched copy takes: every stream's layers, three rows or a key and a value each. +pub const copy_items = max_streams * 64 * 3 + round_rows * 64 * 2; +/// The most candidates a sampled row reads from the GPU: top_k up to 1,024, and exact_sampling.MARGIN past it. +pub const max_candidates = 1024 + 8; + +/// A bump allocator over one device buffer, every slice 256-byte aligned. +pub const Arena = struct { + buf: ?cuda.DeviceBuffer, // null: a measuring pass, every take counted and none backed + used: usize = 0, + + pub fn init(d: *const cuda.Driver, len: usize) !Arena { + return .{ .buf = try cuda.DeviceBuffer.alloc(d, len) }; + } + + pub fn deinit(a: *Arena) void { + if (a.buf) |*b| b.free(); + } + + pub fn take(a: *Arena, len: usize) !u64 { + const at = std.mem.alignForward(usize, a.used, 256); + a.used = at + len; + const b = a.buf orelse return 0; + if (a.used > b.len) return error.ArenaFull; + return b.ptr + at; + } +}; + +/// One stream's committed state: DeltaNet recurrences and conv windows, attention keys and values for `capacity`. +pub const Seq = struct { + arena: Arena, + rec: []u64, // by layer: (hv, dv, dk) fp32, 0 for attention layers + conv: []u64, // by layer: (3, conv dim) bf16 + keys: []u64, // by layer: (capacity, kv heads, head dim) bf16, or e4m3 under kv8 + values: []u64, + kscale: []u64, // kv8: by layer, (capacity, kv heads) fp32, each key row's scale (0 for DeltaNet layers) + vscale: []u64, + kv8: bool, // --kv-cache fp8: keys and values as e4m3 rows with a scale each + head_in: u64, // the last prompt row normed, (hidden) bf16, and its group sums: the first draw's input + head_xs: u64, + capacity: usize, + pos: usize = 0, + rope_delta: i32 = 0, // an image prompt's rotary shift past its rows (decode positions are pos + rope_delta) + media: ?*const vision.Media = null, // during an image prompt's pass: its rows and positions + gpa: std.mem.Allocator, + + /// Device bytes a stream of `capacity` positions takes. + pub fn bytes(g: c.Geometry, capacity: usize, kv8: bool) usize { + var n: usize = std.mem.alignForward(usize, g.hidden * 2, 256) + std.mem.alignForward(usize, g.hidden / 64 * 4, 256); + const a = std.mem.alignForward; + for (0..g.layers) |i| n += if (c.linear(i)) a(usize, g.deltaBytes(), 256) + a(usize, g.convBytes(), 256) else if (kv8) 2 * (a(usize, capacity * g.kvInner(), 256) + a(usize, capacity * g.kv_heads * 4, 256)) else 2 * a(usize, capacity * g.kvInner() * 2, 256); + return n; + } + + /// A fresh stream: zero recurrences and conv windows, caches for `capacity` positions. + pub fn init(gpa: std.mem.Allocator, ops: kern.Ops, g: c.Geometry, capacity: usize, kv8: bool) !Seq { + var s: Seq = .{ .gpa = gpa, .arena = try Arena.init(ops.k.d, bytes(g, capacity, kv8)), .rec = &.{}, .conv = &.{}, .keys = &.{}, .values = &.{}, .kscale = &.{}, .vscale = &.{}, .kv8 = kv8, .head_in = 0, .head_xs = 0, .capacity = capacity }; + errdefer s.arena.deinit(); + s.rec = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.rec); + s.conv = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.conv); + s.keys = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.keys); + s.values = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.values); + s.kscale = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.kscale); + s.vscale = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.vscale); + const bf: usize = if (kv8) 1 else 2; + s.head_in = try s.arena.take(g.hidden * 2); + s.head_xs = try s.arena.take(g.hidden / 64 * 4); + for (0..g.layers) |i| { + s.rec[i] = 0; + s.conv[i] = 0; + s.keys[i] = 0; + s.values[i] = 0; + s.kscale[i] = 0; + s.vscale[i] = 0; + const A = &s.arena; + if (c.linear(i)) { + s.rec[i] = try A.take(g.deltaBytes()); + s.conv[i] = try A.take(g.convBytes()); + } else { + s.keys[i] = try A.take(capacity * g.kvInner() * bf); + s.values[i] = try A.take(capacity * g.kvInner() * bf); + if (kv8) { + s.kscale[i] = try A.take(capacity * g.kv_heads * 4); + s.vscale[i] = try A.take(capacity * g.kv_heads * 4); + } + } + } + try s.reset(ops, g); + return s; + } + + pub fn deinit(s: *Seq) void { + s.arena.deinit(); + s.gpa.free(s.rec); + s.gpa.free(s.conv); + s.gpa.free(s.keys); + s.gpa.free(s.values); + s.gpa.free(s.kscale); + s.gpa.free(s.vscale); + s.* = undefined; + } + + /// Back to an empty prompt: zero recurrences and conv windows (State.__init__'s zeros). + pub fn reset(s: *Seq, ops: kern.Ops, g: c.Geometry) !void { + for (0..g.layers) |i| if (c.linear(i)) { + try ops.fill32(s.rec[i], 0, g.deltaBytes() / 4); + try ops.fill32(s.conv[i], 0, g.convBytes() / 4); + }; + s.pos = 0; + s.rope_delta = 0; + s.media = null; + } +}; + +/// One DeltaNet layer's window record, kept until commit: what the replay steps and the conv window takes. +pub const GdnRecord = struct { q: u64, k: u64, v: u64, g: u64, beta: u64, qkv: u64 }; +/// One attention layer's window record: the rotated keys and the values the window's rows would add. +pub const AttnRecord = struct { k: u64, v: u64 }; + +/// The forward's device buffers, sized for `rows` rows a call (a decode window, or a prompt chunk). +pub const Scratch = struct { + arena: Arena, + rows: usize, + // the residual stream and the normed rows with their group sums + x: u64, + h: u64, + y: u64, + xs: u64, + r: u64, + pending: u64, + // DeltaNet + qkv: u64, + z: u64, + b: u64, + a: u64, + yr: u64, + gq: u64, // a prompt chunk's DeltaNet inputs (a window's live in its records) + gk: u64, + gv: u64, + gg: u64, + gbeta: u64, + gated: u64, + gated_xs: u64, + // attention + qg: u64, + key: u64, + value: u64, + q_rot: u64, + attn: u64, + // MLP + gate: u64, + up: u64, + act: u64, + act_xs: u64, + // the head's input, logits and picks + last_h: u64, + last_xs: u64, + logits: u64, + picks: u64, + logits32: u64, // the round's logits as fp32, the top-k input + cand_values: u64, // (rows, max_candidates) fp32 and int64: each row's top candidates + cand_ids: u64, + topk_scratch: u64, + // inputs a call uploads: ids, positions, conv windows, the GDN plan, the attention plan + ids: u64, + pos: u64, + sids: u64, // a batched prompt's rows' streams + prompt_keys: u64, // a batched prompt's rotated keys and values, before each stream's cache takes its rows + prompt_values: u64, + windows: u64, + plan: u64, + attn_plan: u64, + paths: u64, + depths: u64, + offs: u64, + part_o: u64, // attention's partials, (slots, rows, heads, dim) fp32 and (slots, rows, heads) m and l, in `parts` + part_m: u64, + part_l: u64, + part_rows: usize, // the slot-rows `parts` holds: a round's most slots times its rows fit under this + parts: ?cuda.DeviceBuffer = null, + quant_items: u64, // --kv-cache fp8: a commit's or a prompt's kv_quant table (kern.Quant) + origin: u64, // the bf16 origin cache offsets count from + conv_tmp: u64, + conv_old: u64, // a round's streams' conv rows that survive its commit, by stream and DeltaNet layer + copy_items: u64, // two batched-copy tables (kern.Copy), one for each phase of a commit + taps: u64, // a call's rows of the drafter's taps: (rows, 5 x hidden) bf16 + replay_table: u64, + replay_rows: u64, + round: u64, // a shared round's packed int32 inputs (multi_tree_forward's one host copy) + tables: u64, // (DeltaNet layers, streams) int64: each stream's state of each layer + conv_cat: u64, // by DeltaNet layer: every stream's conv rows, stacked + records: []GdnRecord, // by layer: the round's DeltaNet inputs, kept until commit + attn_records: []AttnRecord, // by layer: the round's rotated keys and values + gpa: std.mem.Allocator, + + /// Scratch for prompt chunks of `prompt_rows` and windows of `max_rows`, over caches of `capacity` positions. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, g: c.Geometry, prompt_rows: usize, capacity: usize) !Scratch { + var s: Scratch = undefined; + s.gpa = gpa; + s.records = try gpa.alloc(GdnRecord, g.layers); + errdefer gpa.free(s.records); + s.attn_records = try gpa.alloc(AttnRecord, g.layers); + errdefer gpa.free(s.attn_records); + s.arena = .{ .buf = null }; + try s.layout(g, prompt_rows, capacity); + s.arena = try Arena.init(d, s.arena.used); + errdefer s.arena.deinit(); + try s.layout(g, prompt_rows, capacity); + s.parts = null; + try s.fitPartials(d, g, initial_part_rows); + return s; + } + + /// Partials for calibration's short windows until `fit` sizes them for the admitted streams. + pub const initial_part_rows = 4 * round_rows; + + /// Device bytes partials of `slot_rows` take. + pub fn partialBytes(g: c.Geometry, slot_rows: usize) usize { + const a = std.mem.alignForward; + return a(usize, slot_rows * g.query_heads * c.head_dim * 4, 256) + 2 * a(usize, slot_rows * g.query_heads * 4, 256); + } + + /// The slot-rows a stream of `capacity` positions may add to a round: its most slots times its widest window. + pub fn streamPartRows(capacity: usize) usize { + return ((capacity + max_rows + tri.chunk - 1) / tri.chunk + 1) * max_rows; + } + + /// Partials of `slot_rows` (at least the initial), replacing any held. + pub fn fitPartials(s: *Scratch, d: *const cuda.Driver, g: c.Geometry, slot_rows: usize) !void { + const rows = @max(slot_rows, initial_part_rows); + if (s.parts) |*b| b.free(); + s.parts = null; + var b = try cuda.DeviceBuffer.alloc(d, partialBytes(g, rows)); + errdefer b.free(); + var A: Arena = .{ .buf = b }; + s.part_o = try A.take(rows * g.query_heads * c.head_dim * 4); + s.part_m = try A.take(rows * g.query_heads * 4); + s.part_l = try A.take(rows * g.query_heads * 4); + s.part_rows = rows; + s.parts = b; + } + + fn layout(s: *Scratch, g: c.Geometry, prompt_rows: usize, capacity: usize) !void { + const R = @max(prompt_rows, round_rows); + const W = round_rows; + const bf = 2; + // attention.plan_host: a query tile's items per committed chunk and folded group + const codes = capacity / tri.chunk + capacity / (tri.chunk * tri.group_chunks); + const items = codes * ((W * (g.query_heads / g.kv_heads) + 15) / 16); + s.rows = R; + s.arena.used = 0; + const A = &s.arena; + s.origin = try A.take(128); + s.x = try A.take(R * g.hidden * bf); + s.h = try A.take(R * g.hidden * bf); + s.y = try A.take(R * g.hidden * bf); + s.r = try A.take(R * g.hidden * bf); + s.pending = try A.take(R * g.hidden * bf); + s.xs = try A.take(R * g.hidden / 64 * 4); + s.qkv = try A.take(R * g.convDim() * bf); + s.z = try A.take(R * g.vInner() * bf); + s.b = try A.take(R * g.linear_v_heads * bf); + s.a = try A.take(R * g.linear_v_heads * bf); + s.yr = try A.take(R * g.vInner() * bf); + s.gq = try A.take(R * g.kInner() * bf); + s.gk = try A.take(R * g.kInner() * bf); + s.gv = try A.take(R * g.vInner() * bf); + s.gg = try A.take(R * g.linear_v_heads * 4); + s.gbeta = try A.take(R * g.linear_v_heads * 4); + s.gated = try A.take(R * g.inner() * bf); + s.gated_xs = try A.take(R * g.inner() / 64 * 4); + s.qg = try A.take(R * 2 * g.qInner() * bf); + s.key = try A.take(R * g.kvInner() * bf); + s.value = try A.take(R * g.kvInner() * bf); + s.q_rot = try A.take(R * g.qInner() * bf); + s.attn = try A.take(R * g.qInner() * bf); + s.gate = try A.take(R * g.intermediate * bf); + s.up = try A.take(R * g.intermediate * bf); + s.act = try A.take(R * g.intermediate * bf); + s.act_xs = try A.take(R * g.intermediate / 64 * 4); + s.last_h = try A.take(W * g.hidden * bf); + s.last_xs = try A.take(W * g.hidden / 64 * 4); + s.logits = try A.take(W * c.vocab * bf); + s.picks = try A.take(W * 4); + s.logits32 = try A.take(W * c.vocab * 4); + s.cand_values = try A.take(W * max_candidates * 4); + s.cand_ids = try A.take(W * max_candidates * 8); + s.topk_scratch = try A.take(torch_ops.topkScratchBytes(W, c.vocab)); + s.ids = try A.take(R * 4); + s.pos = try A.take(R * 4); + s.sids = try A.take(R * 4); + s.prompt_keys = try A.take(R * g.kvInner() * bf); + s.prompt_values = try A.take(R * g.kvInner() * bf); + s.windows = try A.take(R * c.conv_taps * 4); + s.plan = try A.take(R * 3 * 4); + s.attn_plan = try A.take((W + 4 + 3 * items + W + 12) * 4); // + each segment's 16-byte padding + s.paths = try A.take(W * tri.max_nodes * 4); + s.depths = try A.take(W * 4); + s.offs = try A.take(g.layers * max_streams * 4 * 8); + s.conv_tmp = try A.take((c.conv_taps - 1 + R) * g.convDim() * bf); + s.conv_old = try A.take(max_streams * g.layers * (c.conv_taps - 1) * g.convDim() * bf); + s.copy_items = try A.take(2 * copy_items * @sizeOf(kern.Copy)); + s.quant_items = try A.take(copy_items * @sizeOf(kern.Quant)); + s.taps = try A.take(R * 5 * g.hidden * bf); + s.replay_table = try A.take(g.layers * (4 + max_streams) * 8); + s.replay_rows = try A.take(max_streams * (W + 1) * 4); + s.round = try A.take((6 * W + max_streams + 1 + W * c.conv_taps + 4 + W + 4 * max_streams + 3 * items * max_streams + W + 12) * 4); + s.tables = try A.take(g.layers * max_streams * 8); + s.conv_cat = try A.take(g.layers * max_streams * (c.conv_taps - 1) * g.convDim() * bf); + for (0..g.layers) |i| { + if (c.linear(i)) { + s.records[i] = .{ + .q = try A.take(W * g.kInner() * bf), + .k = try A.take(W * g.kInner() * bf), + .v = try A.take(W * g.vInner() * bf), + .g = try A.take(W * g.linear_v_heads * 4), + .beta = try A.take(W * g.linear_v_heads * 4), + .qkv = try A.take(W * g.convDim() * bf), + }; + } else { + s.attn_records[i] = .{ .k = try A.take(W * g.kvInner() * bf), .v = try A.take(W * g.kvInner() * bf) }; + } + } + } + + pub fn deinit(s: *Scratch) void { + if (s.parts) |*b| b.free(); + s.arena.deinit(); + s.gpa.free(s.records); + s.gpa.free(s.attn_records); + s.* = undefined; + } +}; diff --git a/zig/src/families/qwen27/cuda/tree.zig b/zig/src/families/qwen27/cuda/tree.zig new file mode 100644 index 0000000000..f8cdf7187d --- /dev/null +++ b/zig/src/families/qwen27/cuda/tree.zig @@ -0,0 +1,181 @@ +//! A verify tree's host plans: gdn.schedule's slots and visiting order, and each node's conv window and depth. + +const std = @import("std"); + +/// The most nodes a stream's tree takes (forward._paths), and the most live states a schedule may hold. +pub const max_nodes = 128; +pub const max_slots = 32; + +/// gdn.schedule's result: (node, source, dest) entries in visiting order and the slots they use. +pub const Schedule = struct { entries: []i32, slots: usize }; + +/// forward._paths: each row's depth from the root (parents topologically sorted, -1 at row 0 only). +pub fn depths(parents: []const i32, out: []usize) !void { + if (parents.len == 0 or parents.len > max_nodes or parents[0] != -1) return error.InvalidQwenTree; + for (parents, 0..) |p, row| { + if (row == 0) { + out[0] = 0; + continue; + } + if (p < 0 or p >= row) return error.InvalidQwenTree; + out[row] = out[@intCast(p)] + 1; + } +} + +/// Whether every row's parent is the row before it: a chain. +pub fn chain(parents: []const i32) bool { + for (parents, 0..) |p, row| if (p != @as(i32, @intCast(row)) - 1) return false; + return true; +} + +/// gdn._order_slots: entries for one visiting order, and the slots it needs. +fn orderSlots(gpa: std.mem.Allocator, parents: []const i32, order: []const usize) !Schedule { + const n = parents.len; + const pos = try gpa.alloc(usize, n); + defer gpa.free(pos); + for (order, 0..) |node, i| pos[node] = i; + // each node's last child in this order, and whether all its children follow it directly + const last = try gpa.alloc(?usize, n); + defer gpa.free(last); + @memset(last, null); + const direct = try gpa.alloc(bool, n); + defer gpa.free(direct); + @memset(direct, true); + for (parents, 0..) |p, node| { + if (p < 0) continue; + const pu: usize = @intCast(p); + if (last[pu] == null or pos[node] > pos[last[pu].?]) last[pu] = node; + if (pos[node] != pos[pu] + 1) direct[pu] = false; + } + const slot_of = try gpa.alloc(?i32, n); + defer gpa.free(slot_of); + @memset(slot_of, null); + var free: std.ArrayList(i32) = .empty; + defer free.deinit(gpa); + var entries = try gpa.alloc(i32, 3 * n); + errdefer gpa.free(entries); + var used: i32 = 0; + for (order, 0..) |node, i| { + const parent = parents[node]; + var source: i32 = -1; + if (parent >= 0) { + const pu: usize = @intCast(parent); + source = if (i > 0 and order[i - 1] == pu) -2 else slot_of[pu] orelse return error.InvalidQwenTree; + // its last child reads it now: the slot may be reused + if (slot_of[pu] != null and pos[last[pu].?] == i) { + try free.append(gpa, slot_of[pu].?); + slot_of[pu] = null; + } + } + var dest: i32 = -1; + if (last[node] != null and !direct[node]) { + if (free.items.len > 0) { + std.mem.sort(i32, free.items, {}, std.sort.asc(i32)); + dest = free.orderedRemove(0); + } else { + dest = used; + used += 1; + } + slot_of[node] = dest; + } + entries[3 * i ..][0..3].* = .{ @intCast(node), source, dest }; + } + return .{ .entries = entries, .slots = @intCast(used) }; +} + +/// gdn.schedule: depth-first or level order, whichever needs fewer slots (depth-first on a tie). +pub fn schedule(gpa: std.mem.Allocator, parents: []const i32) !Schedule { + const n = parents.len; + const d = try gpa.alloc(usize, n); + defer gpa.free(d); + try depths(parents, d); + // depth-first: children in row order, as the Python stack pushes them reversed + const dfs = try gpa.alloc(usize, n); + defer gpa.free(dfs); + var stack: std.ArrayList(usize) = .empty; + defer stack.deinit(gpa); + try stack.append(gpa, 0); + var at: usize = 0; + while (stack.pop()) |node| { + dfs[at] = node; + at += 1; + var child = n; + while (child > node + 1) { + child -= 1; + if (parents[child] == @as(i32, @intCast(node))) try stack.append(gpa, child); + } + } + const level = try gpa.alloc(usize, n); + defer gpa.free(level); + for (level, 0..) |*l, i| l.* = i; + std.mem.sort(usize, level, d, struct { + fn less(ds: []const usize, a: usize, b: usize) bool { + return ds[a] < ds[b] or (ds[a] == ds[b] and a < b); + } + }.less); + const first = try orderSlots(gpa, parents, dfs); + const second = orderSlots(gpa, parents, level) catch |err| { + gpa.free(first.entries); + return err; + }; + const best, const other = if (second.slots < first.slots) .{ second, first } else .{ first, second }; + gpa.free(other.entries); + if (best.slots > max_slots) { + gpa.free(best.entries); + return error.QwenTreeTooWide; + } + return best; +} + +/// forward._conv_windows: each node's last `keep` inputs along its path, then its own row (`keep + base + row`). +pub fn convWindows(parents: []const i32, keep: usize, base: usize, out: []i32) void { + const w = keep + 1; + for (parents, 0..) |p, row| { + const dst = out[row * w ..][0..w]; + if (p < 0) { + for (0..keep) |j| dst[j] = @intCast(j); + } else { + const src = out[@as(usize, @intCast(p)) * w ..][0..w]; + @memcpy(dst[0..keep], src[1..w]); + } + dst[keep] = @intCast(keep + base + row); + } +} + +test "a chain's schedule keeps no slot and reads each predecessor" { + const gpa = std.testing.allocator; + const s = try schedule(gpa, &.{ -1, 0, 1, 2 }); + defer gpa.free(s.entries); + try std.testing.expectEqual(@as(usize, 0), s.slots); + try std.testing.expectEqualSlices(i32, &.{ 0, -1, -1, 1, -2, -1, 2, -2, -1, 3, -2, -1 }, s.entries); +} + +test "a fork saves the shared parent in a slot until its last child" { + const gpa = std.testing.allocator; + // root 0 with children 1 and 2, 1 with child 3: depth-first 0 1 3 2 needs the root kept for 2 + const s = try schedule(gpa, &.{ -1, 0, 0, 1 }); + defer gpa.free(s.entries); + try std.testing.expectEqual(@as(usize, 1), s.slots); + try std.testing.expectEqualSlices(i32, &.{ 0, -1, 0, 1, -2, -1, 3, -2, -1, 2, 0, -1 }, s.entries); +} + +test "schedules match gdn.schedule on random trees" { + const gpa = std.testing.allocator; + const cases = .{ + .{ &[_]i32{ -1, 0, 1, 2, 0, 3 }, &[_]i32{ 0, -1, 0, 1, -2, -1, 2, -2, -1, 3, -2, -1, 5, -2, -1, 4, 0, -1 }, 1 }, + .{ &[_]i32{ -1, 0, 0, 0, 0, 2, 3, 6, 3 }, &[_]i32{ 0, -1, 0, 1, -2, -1, 2, 0, -1, 5, -2, -1, 3, 0, 1, 6, -2, -1, 7, -2, -1, 8, 1, -1, 4, 0, -1 }, 2 }, + .{ &[_]i32{ -1, 0, 0, 2, 1, 0, 5, 1, 6, 4, 2, 6 }, &[_]i32{ 0, -1, 0, 1, -2, 1, 4, -2, -1, 9, -2, -1, 7, 1, -1, 2, 0, 1, 3, -2, -1, 10, 1, -1, 5, 0, -1, 6, -2, 0, 8, -2, -1, 11, 0, -1 }, 2 }, + }; + inline for (cases) |case| { + const s = try schedule(gpa, case[0]); + defer gpa.free(s.entries); + try std.testing.expectEqual(@as(usize, case[2]), s.slots); + try std.testing.expectEqualSlices(i32, case[1], s.entries); + } +} + +test "conv windows follow each node's path" { + var out: [4 * 4]i32 = undefined; + convWindows(&.{ -1, 0, 0, 1 }, 3, 0, &out); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 5, 2, 3, 4, 6 }, &out); +} diff --git a/zig/src/families/qwen27/cuda/triton.zig b/zig/src/families/qwen27/cuda/triton.zig new file mode 100644 index 0000000000..d52e14174b --- /dev/null +++ b/zig/src/families/qwen27/cuda/triton.zig @@ -0,0 +1,160 @@ +//! The 27B's Triton kernels from the captured cubins: each launch has the Python wrapper's grid and constexprs. + +const std = @import("std"); +const cuda = @import("cuda"); +const aot = cuda.aot; + +const p = aot.ptr; + +fn int(name: []const u8, v: usize) aot.Arg { + return aot.int(name, @intCast(v)); +} + +fn ci(name: []const u8, v: usize) aot.Const { + return aot.ci(name, @intCast(v)); +} + +fn u(x: usize) u32 { + return @intCast(x); +} + +fn cdiv(a: usize, b: usize) u32 { + return u((a + b - 1) / b); +} + +fn pow2(n: usize) usize { + return std.math.ceilPowerOfTwo(usize, n) catch unreachable; +} + +/// attention.py's layout constants: 512-key chunks, folded four to a group, up to 128 window rows. +pub const chunk = 512; +pub const group_chunks = 4; +pub const max_nodes = 128; +const merge_columns = 64; + +/// The DeltaNet shapes glue.gdn_pre takes: projection width, key and value heads, head dim, kept conv rows. +pub const Gdn = struct { c: usize, kh: usize, vh: usize, dk: usize, keep: usize }; + +/// The attention shapes: query and key heads, head dim, rotary half. +pub const Attn = struct { heads: usize, kv_heads: usize, dim: usize, half: usize }; + +pub const Tri = struct { + set: *const aot.Set, + s: cuda.Stream, + + fn run(t: Tri, name: []const u8, grid: [3]u32, args: []const aot.Arg, consts: []const aot.Const) !void { + try t.set.run(t.s, name, grid, args, consts); + } + + /// glue.embed: a 4-bit table row dequantized, one program a row and 64-group. + pub fn embed(t: Tri, ids: u64, w: u64, s: u64, b: u64, out: u64, rows: usize, d: usize) !void { + try t.run("_embed", .{ u(rows), u(d / 64), 1 }, &.{ p("IDS", "*i32", ids), p("Wt", "*i32", w), p("S", "*bf16", s), p("B", "*bf16", b), p("OUT", "*bf16", out) }, &.{ci("D", d)}); + } + + /// glue.add_rmsnorm: h = x + r (or x itself without r), y = rmsnorm(h) * w, xs = y's 64-group sums. + pub fn addRmsnorm(t: Tri, x: u64, r: ?u64, w: u64, h: u64, y: u64, xs: u64, rows: usize, d: usize, eps: f32) !void { + try t.run("_add_rmsnorm", .{ u(rows), 1, 1 }, &.{ p("X", "*bf16", x), p("R", "*bf16", r orelse x), p("W", "*bf16", w), p("H", "*bf16", if (r != null) h else x), p("Y", "*bf16", y), p("XS", "*fp32", xs), aot.float("eps", eps) }, &.{ ci("D", d), ci("BLOCK", pow2(d)), ci("HAS_R", @intFromBool(r != null)) }); + } + + /// glue.gdn_pre: conv over each row's window of [state; qkv], q/k norms, g and beta; `sid`: several streams. + pub fn gdnPre(t: Tri, qkv: u64, cs: u64, cw: u64, win: u64, sid: ?u64, a: u64, b: u64, alog: u64, dtb: u64, q: u64, k: u64, v: u64, g: u64, beta: u64, rows: usize, m: Gdn) !void { + try t.run("_gdn_pre", .{ u(rows), u(2 * m.kh + m.vh), 1 }, &.{ + p("QKV", "*bf16", qkv), p("CS", "*bf16", cs), p("CW", "*bf16", cw), p("WIN", "*i32", win), p("A", "*bf16", a), p("B", "*bf16", b), p("ALOG", "*fp32", alog), + p("DTB", "*fp32", dtb), p("Q", "*bf16", q), p("K", "*bf16", k), p("V", "*bf16", v), p("G", "*fp32", g), p("BETA", "*fp32", beta), p("SID", "*i32", sid orelse win), + }, &.{ ci("C", m.c), ci("KH", m.kh), ci("VH", m.vh), ci("DK", m.dk), ci("NKEEP", m.keep), ci("MULTI", @intFromBool(sid != null)) }); + } + + /// glue.gated_norm: silu(z) * rmsnorm(y) * w per value head, and its group sums. + pub fn gatedNorm(t: Tri, y: u64, z: u64, w: u64, out: u64, xs: u64, rows: usize, vh: usize, dv: usize, eps: f32) !void { + try t.run("_gated_norm", .{ u(rows), u(vh), 1 }, &.{ p("Yr", "*bf16", y), p("Z", "*bf16", z), p("W", "*bf16", w), p("OUT", "*bf16", out), p("XS", "*fp32", xs), aot.float("eps", eps) }, &.{ ci("VH", vh), ci("DV", dv) }); + } + + /// glue.swiglu: silu(gate) * up in 1024-column blocks, and its group sums. + pub fn swiglu(t: Tri, gate: u64, up: u64, out: u64, xs: u64, rows: usize, n: usize) !void { + try t.run("_swiglu", .{ u(rows), cdiv(n, 1024), 1 }, &.{ p("GATE", "*bf16", gate), p("UP", "*bf16", up), p("OUT", "*bf16", out), p("XS", "*fp32", xs) }, &.{ ci("N", n), ci("BLOCK", 1024) }); + } + + /// glue.attn_prep: q (from the [q | gate] rows) and k normed, then rotated at each row's position. + pub fn attnPrep(t: Tri, qg: u64, kv: u64, qn: u64, kn: u64, pos: u64, inv: u64, qout: u64, kout: u64, rows: usize, a: Attn, eps: f32) !void { + try t.run("_attn_prep", .{ u(rows), u(a.heads + a.kv_heads), 1 }, &.{ p("QG", "*bf16", qg), p("KV", "*bf16", kv), p("QN", "*bf16", qn), p("KN", "*bf16", kn), p("POS", "*i32", pos), p("INV", "*fp32", inv), p("QOUT", "*bf16", qout), p("KOUT", "*bf16", kout), aot.float("eps", eps) }, &.{ + ci("H", a.heads), ci("HKV", a.kv_heads), ci("D", a.dim), ci("HALF", a.half), ci("MROPE", 0), ci("ROWS", 0), ci("HSEC", 11), ci("WSEC", 10), + }); + } + + /// glue.gate_mul: the attention output times sigmoid(gate) from the [q | gate] rows, and its group sums. + pub fn gateMul(t: Tri, o: u64, qg: u64, out: u64, xs: u64, rows: usize, heads: usize, dim: usize) !void { + try t.run("_gate_mul", .{ u(rows), u(heads), 1 }, &.{ p("O", "*bf16", o), p("QG", "*bf16", qg), p("OUT", "*bf16", out), p("XS", "*fp32", xs) }, &.{ ci("H", heads), ci("D", dim) }); + } + + /// qmm.group_sums: each row's 64-group input sums in fp32 (rows may be strided by `ld`). + pub fn groupSums(t: Tri, x: u64, xs: u64, ld: usize, rows: usize, k: usize) !void { + try t.run("_group_sums", .{ u(rows), cdiv(k / 64, 16), 1 }, &.{ p("X", "*bf16", x), p("XS", "*fp32", xs), int("ldx", ld) }, &.{ ci("KG", k / 64), ci("GS", 64), ci("GB", 16) }); + } + + /// attention.from_packed's _paths: each row's root-to-row window rows and its depth. + pub fn paths(t: Tri, parents: u64, out: u64, depths: u64, rows: usize) !void { + try t.run("_paths", .{ u(rows), 1, 1 }, &.{ p("PARENTS", "*i32", parents), p("PATHS", "*i32", out), p("DEPTHS", "*i32", depths) }, &.{ci("MAXD", max_nodes)}); + } + + /// The layout attention.attention reads: the plan's tables and the partial buffers it writes. + pub const Plan = struct { streams: u64, items: u64, n_items: usize, rows: u64, paths: u64, depths: u64, width: usize }; + pub const Partials = struct { o: u64, m: u64, l: u64 }; + + /// attention.attention: committed keys in 512-key chunks, the row's own path in its tail, merged in order. + pub fn attention(t: Tri, q: u64, kn: u64, vn: u64, base: u64, offs: u64, plan: Plan, part: Partials, out: u64, a: Attn) !void { + const g = a.heads / a.kv_heads; + const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(a.dim), -0.5)); + const w = plan.width; + if (plan.n_items > 0) try t.run("_shared", .{ u(plan.n_items * a.kv_heads), 1, 1 }, &.{ + p("Q", "*bf16", q), p("KC", "*bf16", base), p("VC", "*bf16", base), p("OFF", "*i64", offs), p("STREAM", "*i32", plan.streams), + p("ITEMS", "*i32", plan.items), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + const tails = 1 + (max_nodes + chunk - 1) / chunk; + try t.run("_tail", .{ u(w), u(a.kv_heads), u(tails) }, &.{ + p("Q", "*bf16", q), p("KN", "*bf16", kn), p("VN", "*bf16", vn), p("KC", "*bf16", base), p("VC", "*bf16", base), p("OFF", "*i64", offs), p("STREAM", "*i32", plan.streams), + p("ROWS", "*i32", plan.rows), p("PATHS", "*i32", plan.paths), p("DEPTHS", "*i32", plan.depths), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), ci("MAXD", max_nodes), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + try t.run("_merge", .{ u(w), u(a.kv_heads), u(a.dim / merge_columns) }, &.{ + p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), p("OUT", "*bf16", out), p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), int("W", w), + }, &.{ ci("H", a.heads), ci("D", a.dim), ci("G", g), ci("DS", merge_columns), ci("CH", chunk), ci("GR", group_chunks) }); + } + + /// attention8 (attention_kv8.py): e4m3 cache attention at `base` plus each stream's `offs`; window K/V stay bf16. + pub fn attention8(t: Tri, q: u64, kn: u64, vn: u64, base: u64, offs: u64, plan: Plan, part: Partials, out: u64, a: Attn) !void { + const g = a.heads / a.kv_heads; + const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(a.dim), -0.5)); + const w = plan.width; + if (plan.n_items > 0) try t.run("_shared8", .{ u(plan.n_items * a.kv_heads), 1, 1 }, &.{ + p("Q", "*bf16", q), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), + p("STREAM", "*i32", plan.streams), p("ITEMS", "*i32", plan.items), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + const tails = 1 + (max_nodes + chunk - 1) / chunk; + try t.run("_tail8", .{ u(w), u(a.kv_heads), u(tails) }, &.{ + p("Q", "*bf16", q), p("KN", "*bf16", kn), p("VN", "*bf16", vn), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), + p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), p("PATHS", "*i32", plan.paths), p("DEPTHS", "*i32", plan.depths), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), ci("MAXD", max_nodes), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + try t.run("_merge", .{ u(w), u(a.kv_heads), u(a.dim / merge_columns) }, &.{ + p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), p("OUT", "*bf16", out), p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), int("W", w), + }, &.{ ci("H", a.heads), ci("D", a.dim), ci("G", g), ci("DS", merge_columns), ci("CH", chunk), ci("GR", group_chunks) }); + } +}; + +/// attention.groups: whole committed 2048-key groups fold in their own programs only when they fill the GPU. +pub fn groups(p_: usize, w: usize) usize { + const g = p_ / (chunk * group_chunks); + return if (g * w >= 64) g else 0; +} + +/// attention.slots: one partial slot per folded group, then one per chunk through the window's last key. +pub fn slots(p_: usize, w: usize) usize { + const g = groups(p_, w); + return g + (p_ + w + chunk - 1) / chunk - g * group_chunks; +} + +test "attention slots follow the Python plan" { + try std.testing.expectEqual(@as(usize, 1), slots(0, 1)); + try std.testing.expectEqual(@as(usize, 2), slots(512, 1)); + try std.testing.expectEqual(@as(usize, 9), slots(4096, 1)); // 8 chunks + the window's own + try std.testing.expectEqual(@as(usize, 13), slots(6144, 16)); // 3 groups x 16 rows < 64: every chunk its own + try std.testing.expectEqual(@as(usize, 4), slots(6144, 32)); // 3 folded groups, then the window's chunk +} diff --git a/zig/src/families/qwen27/cuda/vision.zig b/zig/src/families/qwen27/cuda/vision.zig new file mode 100644 index 0000000000..c455e25bbb --- /dev/null +++ b/zig/src/families/qwen27/cuda/vision.zig @@ -0,0 +1,520 @@ +//! The Qwen3.5 vision tower on CUDA as 0.6.6's --vision runs it in bf16: patch embed, 27 rotary blocks, 2x2 merger. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const nemotron = @import("nemotron"); +const source = nemotron.source; + +const lt = cuda.cublaslt; +const prefix = "vision_tower."; + +/// vision_config as the 27B's checkpoint gives it; another tower is refused. +pub const hidden = 1152; +pub const heads = 16; +pub const head_dim = hidden / heads; // 72 +pub const depth = 27; +pub const intermediate = 4304; +pub const out_hidden = 5120; +pub const patch = 16; +pub const temporal = 2; +pub const merge = 2; +pub const channels = 3; +pub const patch_width = channels * temporal * patch * patch; // 1536 +pub const grid_side = 48; // sqrt(num_position_embeddings 2304) +pub const merged = hidden * merge * merge; // 4608 +pub const eps: f32 = 1e-6; +/// The language model's rope_parameters.mrope_section (t, h, w frequencies, interleaved). +pub const mrope_section = [3]u32{ 11, 11, 10 }; +/// Tokens the template writes around an image, and the image placeholder it expands. +pub const vision_start: u32 = 248053; +pub const vision_end: u32 = 248054; +pub const image_token: u32 = 248056; +/// One tower call's patches: a 4,096-token image's (0.6.6's MAX_PATCHES). +pub const max_patches = 16384; +const workspace_bytes = 32 << 20; + +/// The device, stream and memory kind the tower runs on (the engine's, or a checker's own). +pub const Gpu = struct { + d: *const cuda.Driver, + s: cuda.Stream, + discrete: bool, + + fn upload(g: Gpu, dst: u64, bytes: []const u8) !void { + if (bytes.len == 0) return; + try g.d.check(g.d.api.cuMemcpyHtoDAsync_v2(dst, bytes.ptr, bytes.len, g.s.handle), "cuMemcpyHtoDAsync"); + } +}; + +/// One image's patch grid (rows and columns of 16x16 patches, both even). +pub const Grid = struct { h: u32, w: u32 }; + +const Block = struct { norm1_w: u64, norm1_b: u64, qkv_w: u64, qkv_b: u64, proj_w: u64, proj_b: u64, norm2_w: u64, norm2_b: u64, fc1_w: u64, fc1_b: u64, fc2_w: u64, fc2_b: u64 }; + +const Fns = struct { + embed: cuda.Function, + layernorm: cuda.Function, + qkv_rope: cuda.Function, + attention: cuda.Function, + bias_gelu: cuda.Function, + bias_residual: cuda.Function, + bias_cast: cuda.Function, + splice: cuda.Function, + attn_prep: cuda.Function, +}; + +/// The image tower's weights on the GPU and its kernels; `encode` turns patches into language-width rows. +pub const Tower = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + mod: cuda.Module, + f: Fns, + lib: lt.Library, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + patch_w: u64 = 0, + patch_b: u64 = 0, + pos: u64 = 0, + blocks: [depth]Block = undefined, + merger_norm_w: u64 = 0, + merger_norm_b: u64 = 0, + fc1_w: u64 = 0, + fc1_b: u64 = 0, + fc2_w: u64 = 0, + fc2_b: u64 = 0, + inv: u64 = 0, + weight_bytes: usize = 0, + + /// The checkpoint's vision_tower tensors (bf16); the patch convolution's weight as [channel, frame, y, x] rows. + pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: Gpu, dir: []const u8) !*Tower { + const t = try gpa.create(Tower); + errdefer gpa.destroy(t); + t.* = .{ .gpa = gpa, .d = ops.d, .mod = undefined, .f = undefined, .lib = undefined }; + t.lib = try lt.Library.open(); + errdefer t.lib.close(); + t.mod = try cuda.Module.load(ops.d, cuda.kernels.qwen_vision); + errdefer t.mod.unload(); + t.f = .{ + .embed = try t.mod.function("tf_qv_embed"), + .layernorm = try t.mod.function("tf_qv_layernorm"), + .qkv_rope = try t.mod.function("tf_qv_qkv_rope"), + .attention = try t.mod.function("tf_qv_attention72"), + .bias_gelu = try t.mod.function("tf_qv_bias_gelu"), + .bias_residual = try t.mod.function("tf_qv_bias_residual"), + .bias_cast = try t.mod.function("tf_qv_bias_cast"), + .splice = try t.mod.function("tf_qv_splice"), + .attn_prep = try t.mod.function("tf_qv_attn_prep_mrope"), + }; + errdefer t.freeBuffers(); + var src = try source.Source.init(gpa, .{ .d = ops.d, .s = ops.s, .discrete = ops.discrete }); + defer src.deinit(); + var ck = try core.Checkpoint.openModelPrefix(gpa, io, dir, prefix); + defer ck.close(); + try src.add(&ck); + const L = struct { + t: *Tower, + ck: *core.Checkpoint, + src: *source.Source, + fn get(l: @This(), name: []const u8, shape: []const usize) !u64 { + var buf: [96]u8 = undefined; + const tn = try l.ck.expect(try std.fmt.bufPrint(&buf, prefix ++ "{s}", .{name}), .bf16, shape); + const ptr = try l.t.alloc(tn.bytes.len); + try l.src.upload(ptr, tn.bytes); + return ptr; + } + }; + const l: L = .{ .t = t, .ck = &ck, .src = &src }; + { // [hidden, T, P, P, C] as stored (MLX) to [hidden, C, T, P, P] + const tn = try ck.expect(prefix ++ "patch_embed.proj.weight", .bf16, &.{ hidden, temporal, patch, patch, channels }); + const host = try gpa.alloc(u16, hidden * patch_width); + defer gpa.free(host); + const raw = try gpa.alloc(u8, tn.bytes.len); + defer gpa.free(raw); + try src.read(raw, tn.bytes); + const stored: []align(1) const u16 = std.mem.bytesAsSlice(u16, raw); + for (0..hidden) |o| for (0..channels) |ch| for (0..temporal) |tt| for (0..patch) |y| for (0..patch) |x| { + host[o * patch_width + ((ch * temporal + tt) * patch + y) * patch + x] = stored[(((o * temporal + tt) * patch + y) * patch + x) * channels + ch]; + }; + t.patch_w = try t.alloc(host.len * 2); + try src.upload(t.patch_w, std.mem.sliceAsBytes(host)); + try ops.s.synchronize(); + } + t.patch_b = try l.get("patch_embed.proj.bias", &.{hidden}); + t.pos = try l.get("pos_embed.weight", &.{ grid_side * grid_side, hidden }); + for (&t.blocks, 0..) |*b, i| { + var pb: [32]u8 = undefined; + const p = try std.fmt.bufPrint(&pb, "blocks.{d}.", .{i}); + var nb: [96]u8 = undefined; + const n = struct { + fn f(buf: []u8, a: []const u8, s: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ a, s }); + } + }.f; + b.norm1_w = try l.get(try n(&nb, p, "norm1.weight"), &.{hidden}); + b.norm1_b = try l.get(try n(&nb, p, "norm1.bias"), &.{hidden}); + b.qkv_w = try l.get(try n(&nb, p, "attn.qkv.weight"), &.{ 3 * hidden, hidden }); + b.qkv_b = try l.get(try n(&nb, p, "attn.qkv.bias"), &.{3 * hidden}); + b.proj_w = try l.get(try n(&nb, p, "attn.proj.weight"), &.{ hidden, hidden }); + b.proj_b = try l.get(try n(&nb, p, "attn.proj.bias"), &.{hidden}); + b.norm2_w = try l.get(try n(&nb, p, "norm2.weight"), &.{hidden}); + b.norm2_b = try l.get(try n(&nb, p, "norm2.bias"), &.{hidden}); + b.fc1_w = try l.get(try n(&nb, p, "mlp.linear_fc1.weight"), &.{ intermediate, hidden }); + b.fc1_b = try l.get(try n(&nb, p, "mlp.linear_fc1.bias"), &.{intermediate}); + b.fc2_w = try l.get(try n(&nb, p, "mlp.linear_fc2.weight"), &.{ hidden, intermediate }); + b.fc2_b = try l.get(try n(&nb, p, "mlp.linear_fc2.bias"), &.{hidden}); + } + t.merger_norm_w = try l.get("merger.norm.weight", &.{hidden}); + t.merger_norm_b = try l.get("merger.norm.bias", &.{hidden}); + t.fc1_w = try l.get("merger.linear_fc1.weight", &.{ merged, merged }); + t.fc1_b = try l.get("merger.linear_fc1.bias", &.{merged}); + t.fc2_w = try l.get("merger.linear_fc2.weight", &.{ out_hidden, merged }); + t.fc2_b = try l.get("merger.linear_fc2.bias", &.{out_hidden}); + if (ck.unused() != 0) return error.UnusedVisionTensors; + var inv: [head_dim / 4]f32 = undefined; + invFreq(&inv); + t.inv = try t.alloc(@sizeOf(@TypeOf(inv))); + try src.flush(); + try ops.upload(t.inv, std.mem.asBytes(&inv)); + try ops.s.synchronize(); + return t; + } + + pub fn deinit(t: *Tower) void { + t.freeBuffers(); + t.mod.unload(); + t.lib.close(); + t.gpa.destroy(t); + } + + fn freeBuffers(t: *Tower) void { + for (t.buffers.items) |*b| b.free(); + t.buffers.deinit(t.gpa); + } + + fn alloc(t: *Tower, len: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(t.d, len); + try t.buffers.append(t.gpa, b); + t.weight_bytes += len; + return b.ptr; + } + + /// The scratch one tower call of `n` patches needs, in bytes (the patches' bf16 copy included). + pub fn scratchBytes(n: usize) usize { + return n * patch_width * 2 + // patches + 2 * n * hidden * 2 + // x, h + n * @max(3 * hidden, intermediate) * 4 + // fp32 Linear out + 3 * n * hidden * 2 + // q, k, v + n * hidden * 2 + // attention out + n * @max(intermediate, hidden) * 2 + // gelu rows + n * (2 + 4) * 4 + n * 4 * 4 + // hw, idx, weights + workspace_bytes; + } + + /// Images' patches (fp32, merge order) to merged bf16 [sum(h * w) / 4, out_hidden] at `out`, each image on its own. + pub fn encode(t: *Tower, ops: Gpu, pixels: []const f32, grids: []const Grid, out: u64) !void { + var n: usize = 0; + for (grids) |g| { + if (g.h == 0 or g.w == 0 or g.h % merge != 0 or g.w % merge != 0) return error.BadImageGrid; + n += @as(usize, g.h) * g.w; + } + if (n == 0 or n > max_patches or pixels.len != n * patch_width) return error.BadImagePatches; + const gpa = t.gpa; + // host side: bf16 patches, each patch's (row, column) and its 4 position-grid taps + const px16 = try gpa.alloc(u16, n * patch_width); + defer gpa.free(px16); + for (px16, pixels) |*o, v| o.* = bf16(v); + const hw = try gpa.alloc(i32, n * 2); + defer gpa.free(hw); + const idx = try gpa.alloc(i32, n * 4); + defer gpa.free(idx); + const wts = try gpa.alloc(f32, n * 4); + defer gpa.free(wts); + var at: usize = 0; + for (grids) |g| { + positions(g, hw[at * 2 ..][0 .. @as(usize, g.h) * g.w * 2], idx[at * 4 ..][0 .. @as(usize, g.h) * g.w * 4], wts[at * 4 ..][0 .. @as(usize, g.h) * g.w * 4]); + at += @as(usize, g.h) * g.w; + } + var scratch = try cuda.DeviceBuffer.alloc(t.d, scratchBytes(n)); + defer scratch.free(); + var cur: u64 = scratch.ptr; + const take = struct { + fn f(p: *u64, len: usize) u64 { + const r = p.*; + p.* += std.mem.alignForward(usize, len, 256); + return r; + } + }.f; + const d_px = take(&cur, n * patch_width * 2); + const x = take(&cur, n * hidden * 2); + const h = take(&cur, n * hidden * 2); + const acc = take(&cur, n * @max(3 * hidden, intermediate) * 4); + const q = take(&cur, n * hidden * 2); + const k = take(&cur, n * hidden * 2); + const v = take(&cur, n * hidden * 2); + const att = take(&cur, n * hidden * 2); + const mid = take(&cur, n * @max(intermediate, hidden) * 2); + const d_hw = take(&cur, n * 2 * 4); + const d_idx = take(&cur, n * 4 * 4); + const d_wts = take(&cur, n * 4 * 4); + const ws = cur; + const ws_len = scratch.ptr + scratch.len - cur; + try ops.upload(d_px, std.mem.sliceAsBytes(px16)); + try ops.upload(d_hw, std.mem.sliceAsBytes(hw)); + try ops.upload(d_idx, std.mem.sliceAsBytes(idx)); + try ops.upload(d_wts, std.mem.sliceAsBytes(wts)); + + var mm: Gemms = .{ .lib = &t.lib }; + defer mm.deinit(); + const m4 = n / (merge * merge); + try mm.run(n, hidden, patch_width, d_px, t.patch_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.embed, n, 1, 256, .{ acc, t.patch_b, t.pos, d_idx, d_wts, x, int(hidden) }); + const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); + for (t.blocks) |b| { + try t.go(ops, t.f.layernorm, n, 1, 256, .{ x, b.norm1_w, b.norm1_b, h, int(hidden), eps }); + try mm.run(n, 3 * hidden, hidden, h, b.qkv_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.qkv_rope, n, heads, 128, .{ acc, b.qkv_b, d_hw, t.inv, q, k, v, int(n), int(heads), int(head_dim) }); + var s0: usize = 0; + for (grids) |g| { + const len = @as(usize, g.h) * g.w; + try t.go(ops, t.f.attention, (len + 63) / 64, heads, 64, .{ q, k, v, att, int(n), int(heads), int(s0), int(len), scale }); + s0 += len; + } + try mm.run(n, hidden, hidden, att, b.proj_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_residual, n, 1, 256, .{ acc, b.proj_b, x, int(hidden) }); + try t.go(ops, t.f.layernorm, n, 1, 256, .{ x, b.norm2_w, b.norm2_b, h, int(hidden), eps }); + try mm.run(n, intermediate, hidden, h, b.fc1_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_gelu, n, 1, 256, .{ acc, b.fc1_b, mid, int(intermediate), int(1) }); + try mm.run(n, hidden, intermediate, mid, b.fc2_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_residual, n, 1, 256, .{ acc, b.fc2_b, x, int(hidden) }); + } + // merger: LayerNorm over 1152, four merge-ordered rows read as one of 4608 + try t.go(ops, t.f.layernorm, n, 1, 256, .{ x, t.merger_norm_w, t.merger_norm_b, h, int(hidden), eps }); + try mm.run(m4, merged, merged, h, t.fc1_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_gelu, m4, 1, 256, .{ acc, t.fc1_b, mid, int(merged), int(0) }); + try mm.run(m4, out_hidden, merged, mid, t.fc2_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_cast, m4, 1, 256, .{ acc, t.fc2_b, out, int(out_hidden) }); + try ops.s.synchronize(); + } + + /// Splices image rows into a chunk's embeddings `x`: row r takes `features` row src[r] where src[r] >= 0. + pub fn splice(t: *Tower, ops: Gpu, x: u64, features: u64, src: u64, rows: usize) !void { + try t.go(ops, t.f.splice, rows, 1, 256, .{ x, features, src, int(out_hidden) }); + } + + /// glue.attn_prep with three position rows (pos [3][rows], device int32): normed, M-RoPE-rotated q and k. + pub fn attnPrep(t: *Tower, ops: Gpu, qg: u64, key: u64, qn: u64, kn: u64, pos: u64, inv: u64, qout: u64, kout: u64, rows: usize, a: struct { heads: usize, kv_heads: usize, dim: usize, half: usize }, eps_: f32) !void { + try t.go(ops, t.f.attn_prep, rows, a.heads + a.kv_heads, @intCast(a.dim), .{ qg, key, qn, kn, pos, inv, qout, kout, eps_, int(a.heads), int(a.kv_heads), int(a.dim), int(a.half), int(rows), int(mrope_section[1]), int(mrope_section[2]) }); + } + + fn go(t: *Tower, ops: Gpu, f: cuda.Function, gx: usize, gy: usize, block: u32, args: anytype) !void { + _ = t; + var a: cuda.Args = .{}; + inline for (args) |v| a.add(v); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy) }, .block = .{ .x = block } }, ops.s, &a); + } +}; + +/// cuBLASLt plans for the shapes one tower call runs, made on first use. +const Gemms = struct { + lib: *const lt.Library, + plans: [8]?struct { m: usize, n: usize, k: usize, lin: lt.Linear } = @splat(null), + + fn run(g: *Gemms, m: usize, n: usize, k: usize, x: u64, w: u64, out: u64, ws: u64, ws_len: usize, s: cuda.Stream) !void { + for (&g.plans) |*p| { + if (p.*) |*have| { + if (have.m == m and have.n == n and have.k == k) return have.lin.run(x, w, out, ws, ws_len, s.handle); + continue; + } + p.* = .{ .m = m, .n = n, .k = k, .lin = try lt.Linear.init(g.lib, m, n, k, .f32, ws_len) }; + return p.*.?.lin.run(x, w, out, ws, ws_len, s.handle); + } + return error.TooManyShapes; + } + + fn deinit(g: *Gemms) void { + for (&g.plans) |*p| if (p.*) |*have| have.lin.deinit(); + } +}; + +fn int(x: usize) c_int { + return @intCast(x); +} + +/// fp32 to bf16, round to nearest even (torch's .to(bfloat16)). +fn bf16(v: f32) u16 { + const b: u32 = @bitCast(v); + if (std.math.isNan(v)) return 0x7fc0; + return @intCast((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +/// The axial rotary's frequencies: 1 / 10000 ** (i / (head_dim / 2)) for even i, in fp32 as torch computes them. +pub fn invFreq(out: []f32) void { + const dim: f32 = @floatFromInt(head_dim / 2); + for (out, 0..) |*f, j| { + const e: f32 = @as(f32, @floatFromInt(2 * j)) / dim; + f.* = 1.0 / std.math.pow(f32, 10000.0, e); + } +} + +/// One image's patches in merge order: each one's (row, column) for the rotary and 4 bilinear taps into the 48x48 grid. +pub fn positions(g: Grid, hw: []i32, idx: []i32, wts: []f32) void { + const bw = g.w / merge; + const n = @as(usize, g.h) * g.w; + for (0..n) |i| { + const in_col: u32 = @intCast(i % merge); + const in_row: u32 = @intCast((i / merge) % merge); + const block_col: u32 = @intCast((i / (merge * merge)) % bw); + const block_row: u32 = @intCast(i / (merge * merge * bw)); + const r = block_row * merge + in_row; + const c = block_col * merge + in_col; + hw[i * 2] = @intCast(r); + hw[i * 2 + 1] = @intCast(c); + const ht = taps(r, g.h); + const wt = taps(c, g.w); + for (0..2) |a| for (0..2) |b| { + idx[i * 4 + a * 2 + b] = ht.i[a] * grid_side + wt.i[b]; + wts[i * 4 + a * 2 + b] = ht.w[a] * wt.w[b]; + }; + } +} + +const Taps = struct { i: [2]i32, w: [2]f32 }; + +fn taps(index: u32, size: u32) Taps { + const side_m1: f32 = grid_side - 1; + const denom: f32 = @floatFromInt(@max(size, 2) - 1); + const src = @as(f32, @floatFromInt(index)) * side_m1 / denom; + const fl = @floor(src); + var out: Taps = undefined; + for (0..2) |o| { + const raw: i32 = @as(i32, @intFromFloat(fl)) + @as(i32, @intCast(o)); + out.i[o] = std.math.clamp(raw, 0, grid_side - 1); + const dist = @abs(src - fl - @as(f32, @floatFromInt(o))); + out.w[o] = @max(1.0 - dist, 0.0); + } + return out; +} + +test "bilinear taps match align_corners resampling at the ends and middle" { + const a = taps(0, 10); + try std.testing.expectEqual(@as(i32, 0), a.i[0]); + try std.testing.expectEqual(@as(f32, 1), a.w[0]); + const b = taps(9, 10); + try std.testing.expectEqual(@as(i32, 47), b.i[0]); + try std.testing.expectEqual(@as(f32, 1), b.w[0]); +} + +/// An image prompt's rows for its prompt pass (0.6.6's EncodedVision): tower rows, feature rows, positions. +pub const Media = struct { + gpa: std.mem.Allocator, + tower: *Tower, + features: cuda.DeviceBuffer, // bf16 [image rows, out_hidden] + src: []i32, // [prompt]: feature row or -1 + pos: []i32, // [3][prompt]: t, h, w + delta: i32, + dev: cuda.DeviceBuffer, // a chunk's src and [3][rows] positions + + /// Encodes `images` and lays out the prompt's positions as transformers' get_rope_index does (see `layout`). + pub fn init(gpa: std.mem.Allocator, tower: *Tower, ops: Gpu, prompt: []const u32, images: anytype, chunk_rows: usize) !*Media { + const n = prompt.len; + const m = try gpa.create(Media); + errdefer gpa.destroy(m); + var rows: usize = 0; + for (images) |img| rows += img.tokens; + m.* = .{ .gpa = gpa, .tower = tower, .features = try cuda.DeviceBuffer.alloc(ops.d, rows * out_hidden * 2), .src = &.{}, .pos = &.{}, .delta = 0, .dev = undefined }; + errdefer m.features.free(); + m.dev = try cuda.DeviceBuffer.alloc(ops.d, chunk_rows * 4 * 4); + errdefer m.dev.free(); + m.src = try gpa.alloc(i32, n); + errdefer gpa.free(m.src); + m.pos = try gpa.alloc(i32, 3 * n); + errdefer gpa.free(m.pos); + @memset(m.src, -1); + // the tower: runs of whole images within one call's patches, in prompt order + var done: usize = 0; // feature rows written + var i: usize = 0; + while (i < images.len) { + var j = i; + var patches: usize = 0; + while (j < images.len and (j == i or patches + images[j].gh * images[j].gw <= max_patches)) : (j += 1) patches += images[j].gh * images[j].gw; + const px = try gpa.alloc(f32, patches * patch_width); + defer gpa.free(px); + const grids = try gpa.alloc(Grid, j - i); + defer gpa.free(grids); + var at: usize = 0; + for (images[i..j], grids) |img, *g| { + if (img.pixels.len != @as(usize, img.gh) * img.gw * patch_width or img.tokens * merge * merge != img.gh * img.gw) return error.BadImagePatches; + @memcpy(px[at..][0..img.pixels.len], img.pixels); + at += img.pixels.len; + g.* = .{ .h = img.gh, .w = img.gw }; + } + try tower.encode(ops, px, grids, m.features.ptr + done * out_hidden * 2); + for (images[i..j]) |img| done += img.tokens; + i = j; + } + m.delta = try layout(prompt, images, m.src, m.pos); + return m; + } + + pub fn deinit(m: *Media) void { + m.features.free(); + m.dev.free(); + m.gpa.free(m.src); + m.gpa.free(m.pos); + m.gpa.destroy(m); + } + + /// Whether rows [p0, p0 + w) hold an image row. + pub fn hasImage(m: *const Media, p0: usize, w: usize) bool { + for (m.src[p0..][0..w]) |v| if (v >= 0) return true; + return false; + } +}; + +/// The prompt's rotary positions ([3][n]) and feature rows (src, -1 for text) per get_rope_index; returns rope_delta. +pub fn layout(prompt: []const u32, images: anytype, src: []i32, pos: []i32) !i32 { + const n = prompt.len; + @memset(src, -1); + var next: i32 = 0; + var cursor: usize = 0; + var row: i32 = 0; + for (images) |img| { + const begin: usize = img.at; + const h: usize = img.gh / merge; + const w: usize = img.gw / merge; + const end = begin + h * w; + if (begin < cursor or begin == 0 or end >= n or prompt[begin - 1] != vision_start or prompt[end] != vision_end) return error.BadImagePlaceholders; + for (prompt[begin..end]) |t| if (t != image_token) return error.BadImagePlaceholders; + for (cursor..begin) |r| { + const v = next + @as(i32, @intCast(r - cursor)); + for (0..3) |a| pos[a * n + r] = v; + } + const base = next + @as(i32, @intCast(begin - cursor)); + for (0..h * w) |k| { + const r = begin + k; + pos[r] = base; + pos[n + r] = base + @as(i32, @intCast(k / w)); + pos[2 * n + r] = base + @as(i32, @intCast(k % w)); + src[r] = row; + row += 1; + } + next = base + @as(i32, @intCast(@max(h, w))); + cursor = end; + } + for (cursor..n) |r| { + const v = next + @as(i32, @intCast(r - cursor)); + for (0..3) |a| pos[a * n + r] = v; + } + return next - @as(i32, @intCast(cursor)); +} + +test "media positions: text counts up, an image sits at one position with its grid, text resumes past its side" { + const I = struct { gh: u32, gw: u32, at: u32, tokens: u32 }; + const prompt = [_]u32{ 7, vision_start, image_token, image_token, image_token, image_token, image_token, image_token, vision_end, 9 }; + var src: [10]i32 = undefined; + var pos: [30]i32 = undefined; + const delta = try layout(&prompt, &[_]I{.{ .gh = 4, .gw = 6, .at = 2, .tokens = 6 }}, &src, &pos); + try std.testing.expectEqual(@as(i32, -3), delta); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 2, 2, 2, 2, 2, 5, 6 }, pos[0..10]); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 2, 2, 3, 3, 3, 5, 6 }, pos[10..20]); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 3, 4, 2, 3, 4, 5, 6 }, pos[20..30]); + try std.testing.expectEqualSlices(i32, &.{ -1, -1, 0, 1, 2, 3, 4, 5, -1, -1 }, &src); +} diff --git a/zig/src/families/qwen27/cuda/weights.zig b/zig/src/families/qwen27/cuda/weights.zig new file mode 100644 index 0000000000..5c796bd43a --- /dev/null +++ b/zig/src/families/qwen27/cuda/weights.zig @@ -0,0 +1,252 @@ +//! The 27B's weights on the GPU in the Python engine's layouts: tiled projections, the stored embedding, fp32 gates. + +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const source = @import("nemotron").source; +const c = @import("shape.zig"); +const config_eos = @import("../config.zig").max_eos; +const kern = @import("kernels.zig"); + +pub const QLinear = kern.QLinear; +const Tensor = core.checkpoint.Tensor; +const prefix = "language_model."; + +/// The token table as stored (MLX words, scales, biases): a row lookup, not a matmul. +pub const Embed = struct { w: u64, s: u64, b: u64 }; +pub const Delta = struct { qkv: QLinear, z: QLinear, b: QLinear, a: QLinear, out: QLinear, conv: u64, a_log: u64, dt_bias: u64, norm: u64 }; +pub const Attention = struct { q: QLinear, k: QLinear, v: QLinear, o: QLinear, q_norm: u64, k_norm: u64 }; +pub const Mixer = union(enum) { delta: Delta, attention: Attention }; +pub const Layer = struct { input_norm: u64, post_norm: u64, mixer: Mixer, gate: QLinear, up: QLinear, down: QLinear }; + +pub const Weights = struct { + gpa: std.mem.Allocator, + g: c.Geometry, + embed: Embed = undefined, + layers: []Layer = &.{}, + norm: u64 = 0, + head: QLinear = undefined, + inv_freq: u64 = 0, // (rotary_dim / 2,) fp32 + eos: [config_eos]u32 = undefined, // config.json's end tokens, then generation_config.json's + eos_count: usize = 0, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.* = undefined; + } + + pub fn isEos(w: *const Weights, token: u32) bool { + for (w.eos[0..w.eos_count]) |e| if (e == token) return true; + return false; + } + + /// Device bytes the weights hold. + pub fn bytes(w: *const Weights) usize { + var n: usize = 0; + for (w.buffers.items) |b| n += b.len; + return n; + } +}; + +const Loader = struct { + gpa: std.mem.Allocator, + ops: kern.Ops, + w: *Weights, + src: *source.Source, + scratch: cuda.DeviceBuffer, + host: std.ArrayList(u8) = .empty, + + fn alloc(L: *Loader, len: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(L.ops.k.d, len); + try L.w.buffers.append(L.gpa, b); + return b.ptr; + } + + /// Device scratch of at least `len` bytes; growing waits for the stream so pending packs keep their inputs. + fn tmp(L: *Loader, len: usize) !u64 { + if (L.scratch.len < len) { + try L.src.flush(); + try L.ops.s.synchronize(); + L.scratch.free(); + L.scratch = try cuda.DeviceBuffer.alloc(L.ops.k.d, len); + } + return L.scratch.ptr; + } + + /// The host staging buffer, once the stream has read its last contents. + fn staging(L: *Loader, len: usize) ![]u8 { + try L.src.flush(); + try L.ops.s.synchronize(); + try L.host.resize(L.gpa, len); + return L.host.items; + } + + fn raw(L: *Loader, t: Tensor) !u64 { + const ptr = try L.alloc(t.bytes.len); + try L.src.upload(ptr, t.bytes); + return ptr; + } + + /// `.float()` of a bf16 tensor (or an f32 one as stored): exact. + fn widen(L: *Loader, t: Tensor) !u64 { + if (t.dtype == .f32) return L.raw(t); + if (t.dtype != .bf16) return error.UnexpectedTensor; + const n = t.bytes.len / 2; + const out = std.mem.bytesAsSlice(u32, try L.staging(n * 4)); + const in = try L.src.view(t.bytes); + for (out, 0..) |*o, i| o.* = @as(u32, std.mem.readInt(u16, in[2 * i ..][0..2], .little)) << 16; + const ptr = try L.alloc(n * 4); + try L.ops.upload(ptr, L.host.items); + return ptr; + } + + /// qmm_fast.tile: MLX words, scales and biases packed into the lane matmul's tiled layout. + fn tile(L: *Loader, ck: *core.Checkpoint, name: []const u8, n: usize, k: usize) !QLinear { + var parts: [3]Tensor = undefined; + var buf: [192]u8 = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |s, i| parts[i] = try ck.get(try std.fmt.bufPrint(&buf, "{s}{s}.{s}", .{ prefix, name, s })); + const k8 = k / 8; + const kg = k / 64; + if (parts[0].dtype != .u32 or parts[1].dtype != .bf16 or parts[2].dtype != .bf16) return error.UnsupportedQuantization; + if (!parts[0].is(.u32, &.{ n, k8 }) or !parts[1].is(.bf16, &.{ n, kg }) or !parts[2].is(.bf16, &.{ n, kg })) { + std.log.err("{s}: not a 4-bit group-64 ({d}, {d}) projection", .{ name, n, k }); + return error.UnexpectedTensor; + } + const npad = (n + 127) / 128 * 128; + const sizes = [3]usize{ n * k8 * 4, n * kg * 2, n * kg * 2 }; + const base = try L.tmp(sizes[0] + sizes[1] + sizes[2]); + const at = [3]usize{ 0, sizes[0], sizes[0] + sizes[1] }; + for (0..3) |j| try L.src.upload(base + at[j], parts[j].bytes); + const q: QLinear = .{ .w = try L.alloc(npad * k / 2), .s = try L.alloc(kg * npad * 2), .b = try L.alloc(kg * npad * 2), .n = n, .k = k, .npad = npad }; + const total: u64 = @as(u64, npad / 64) * kg * 512; + try L.src.flush(); + var a: cuda.Args = .{}; + a.add(base); + for ([_]usize{ n, k8, kg }) |v| a.add(@as(c_int, @intCast(v))); + a.add(q.w); + a.add(@as(c_longlong, @intCast(total))); + try cuda.launch.launch(L.ops.k.pack_dense, .{ .grid = .{ .x = @intCast((total + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &a); + for ([_]u64{ q.s, q.b }, [_]usize{ at[1], at[2] }) |out, off| { + var t: cuda.Args = .{}; + t.add(base + off); + for ([_]usize{ n, kg, npad }) |v| t.add(@as(c_int, @intCast(v))); + t.add(out); + const cells = @as(u64, kg) * npad; + try cuda.launch.launch(L.ops.k.transpose16, .{ .grid = .{ .x = @intCast((cells + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &t); + } + return q; + } + + fn vector(L: *Loader, ck: *core.Checkpoint, name: []const u8, len: usize) !u64 { + var buf: [192]u8 = undefined; + return L.raw(try ck.expect(try std.fmt.bufPrint(&buf, "{s}{s}", .{ prefix, name }), .bf16, &.{len})); + } + + fn delta(L: *Loader, ck: *core.Checkpoint, p: []const u8, g: c.Geometry) !Delta { + var b1: [160]u8 = undefined; + var b2: [192]u8 = undefined; + const at = struct { + fn f(buf: []u8, pre: []const u8, name: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}linear_attn.{s}", .{ pre, name }); + } + }.f; + var d: Delta = undefined; + d.qkv = try L.tile(ck, try at(&b1, p, "in_proj_qkv"), g.convDim(), g.hidden); + d.z = try L.tile(ck, try at(&b1, p, "in_proj_z"), g.vInner(), g.hidden); + d.b = try L.tile(ck, try at(&b1, p, "in_proj_b"), g.linear_v_heads, g.hidden); + d.a = try L.tile(ck, try at(&b1, p, "in_proj_a"), g.linear_v_heads, g.hidden); + d.out = try L.tile(ck, try at(&b1, p, "out_proj"), g.hidden, g.vInner()); + // conv1d.weight (C, 4, 1) is (C, 4) as stored: the reshape moves no bytes + d.conv = try L.raw(try ck.expect(try std.fmt.bufPrint(&b2, "{s}{s}", .{ prefix, try at(&b1, p, "conv1d.weight") }), .bf16, &.{ g.convDim(), c.conv_taps, 1 })); + d.a_log = try L.widen(try ck.get(try std.fmt.bufPrint(&b2, "{s}{s}", .{ prefix, try at(&b1, p, "A_log") }))); + d.dt_bias = try L.widen(try ck.get(try std.fmt.bufPrint(&b2, "{s}{s}", .{ prefix, try at(&b1, p, "dt_bias") }))); + d.norm = try L.vector(ck, try at(&b1, p, "norm.weight"), c.linear_dim); + return d; + } + + fn attention(L: *Loader, ck: *core.Checkpoint, p: []const u8, g: c.Geometry) !Attention { + var b1: [160]u8 = undefined; + const at = struct { + fn f(buf: []u8, pre: []const u8, name: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}self_attn.{s}", .{ pre, name }); + } + }.f; + return .{ + .q = try L.tile(ck, try at(&b1, p, "q_proj"), 2 * g.qInner(), g.hidden), + .k = try L.tile(ck, try at(&b1, p, "k_proj"), g.kvInner(), g.hidden), + .v = try L.tile(ck, try at(&b1, p, "v_proj"), g.kvInner(), g.hidden), + .o = try L.tile(ck, try at(&b1, p, "o_proj"), g.hidden, g.qInner()), + .q_norm = try L.vector(ck, try at(&b1, p, "q_norm.weight"), c.head_dim), + .k_norm = try L.vector(ck, try at(&b1, p, "k_norm.weight"), c.head_dim), + }; + } +}; + +/// weights.inv_freq: theta ** (-i / half) in float64, rounded to fp32. +pub fn invFreq(out: []f32) void { + const half: f64 = @floatFromInt(out.len); + for (out, 0..) |*f, i| f.* = @floatCast(std.math.pow(f64, c.theta, -@as(f64, @floatFromInt(i)) / half)); +} + +/// weights.load (tiled, one GPU): the model folder's text tensors on the GPU, leftovers refused. +pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, cfg: c.Config) !Weights { + const g = cfg.g; + var w: Weights = .{ .gpa = gpa, .g = g, .eos = cfg.eos, .eos_count = cfg.eos_count }; + errdefer w.deinit(); + var src = try source.Source.init(gpa, .{ .d = ops.k.d, .s = ops.s, .discrete = ops.k.discrete }); + defer src.deinit(); + var L: Loader = .{ .gpa = gpa, .ops = ops, .w = &w, .src = &src, .scratch = try cuda.DeviceBuffer.alloc(ops.k.d, 1 << 20) }; + defer { + src.flush() catch {}; + ops.s.synchronize() catch {}; + L.scratch.free(); + L.host.deinit(gpa); + } + // the vision tower and the MTP head stay on disk, as weights._Tensors skips them + var ck = try core.Checkpoint.openModelPrefix(gpa, io, dir, prefix); + defer ck.close(); + try src.add(&ck); + w.layers = try gpa.alloc(Layer, g.layers); + for (w.layers, 0..) |*layer, i| { + var pb: [64]u8 = undefined; + var nb: [160]u8 = undefined; + const p = try std.fmt.bufPrint(&pb, "model.layers.{d}.", .{i}); + const join = struct { + fn f(buf: []u8, a: []const u8, b: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ a, b }); + } + }.f; + layer.input_norm = try L.vector(&ck, try join(&nb, p, "input_layernorm.weight"), g.hidden); + layer.mixer = if (c.linear(i)) .{ .delta = try L.delta(&ck, p, g) } else .{ .attention = try L.attention(&ck, p, g) }; + layer.gate = try L.tile(&ck, try join(&nb, p, "mlp.gate_proj"), g.intermediate, g.hidden); + layer.up = try L.tile(&ck, try join(&nb, p, "mlp.up_proj"), g.intermediate, g.hidden); + layer.down = try L.tile(&ck, try join(&nb, p, "mlp.down_proj"), g.hidden, g.intermediate); + layer.post_norm = try L.vector(&ck, try join(&nb, p, "post_attention_layernorm.weight"), g.hidden); + } + w.embed = .{ + .w = try L.raw(try ck.expect(prefix ++ "model.embed_tokens.weight", .u32, &.{ c.vocab, g.hidden / 8 })), + .s = try L.raw(try ck.expect(prefix ++ "model.embed_tokens.scales", .bf16, &.{ c.vocab, g.hidden / 64 })), + .b = try L.raw(try ck.expect(prefix ++ "model.embed_tokens.biases", .bf16, &.{ c.vocab, g.hidden / 64 })), + }; + w.norm = try L.vector(&ck, "model.norm.weight", g.hidden); + w.head = try L.tile(&ck, "lm_head", c.vocab, g.hidden); + if (ck.unused() != 0) return error.UnusedCheckpointTensors; + var inv: [c.rotary_dim / 2]f32 = undefined; + invFreq(&inv); + w.inv_freq = try L.alloc(@sizeOf(@TypeOf(inv))); + try ops.upload(w.inv_freq, std.mem.asBytes(&inv)); + try src.flush(); + try ops.s.synchronize(); + return w; +} + +test "inv_freq: theta ** (-i / 32) rounded to fp32" { + var inv: [32]f32 = undefined; + invFreq(&inv); + try std.testing.expectEqual(@as(f32, 1.0), inv[0]); + try std.testing.expectEqual(@as(f32, 0.6042963862419128), inv[1]); + try std.testing.expectEqual(@as(f32, 0.22067341208457947), inv[3]); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 851f919480..f80b52f047 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -4,21 +4,21 @@ const cuda = @import("cuda"); const api = @import("engine_api"); const lanes = @import("lanes"); const nemotron = @import("nemotron"); +const qwen27 = @import("qwen27"); const Allocator = std.mem.Allocator; const budget = @import("cuda_memory.zig"); const lane_backend = @import("cuda_bound.zig"); const nemotron_slide = @import("nemotron_slide.zig"); /// CUDA families provide metadata, open their lane backend and explain their refusals. -const registry = .{nemotron.native}; - -/// Nemotron's prompt-cache copies. A file-level value so the store's pointer stays valid for the process. -const nemotron_snaps: api.prompt_cache.Snapshots.VTable = .{ - .bytes = nemotron.native.snap_bytes, - .save = nemotron.native.snap_save, - .restore = nemotron.native.snap_restore, - .drop = nemotron.native.snap_drop, -}; +const registry = .{ nemotron.native, qwen27.native }; + +/// A family's prompt-cache copies. A comptime value per family, so the store's pointer stays valid for the process. +fn Snaps(comptime F: type) type { + return struct { + const vtable: api.prompt_cache.Snapshots.VTable = .{ .bytes = F.snap_bytes, .save = F.snap_save, .restore = F.snap_restore, .drop = F.snap_drop }; + }; +} pub const backends: []const []const u8 = &.{"cuda"}; pub const families: []const api.Family = blk: { @@ -328,14 +328,32 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O problem.* = try std.fmt.allocPrint(a, "the checkpoint's {d:.1} GiB of weights do not fit the {d:.1} GiB the CUDA memory budget grants ({d:.1} GiB free less a {d:.1} GiB reserve{s}); free device memory or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB", .{ toGib(weights), toGib(before.room(held0)), toGib(before.free), toGib(before.reserve), if (before.limit != null) ", under TENSORFOLD_CUDA_MEMORY_LIMIT_GB" else "" }); return null; } - const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, .{ .context = @intCast(window), .drafts = o.drafts, .segments = segments, .slide = o.slide }) catch |e| { + var family_options: F.Options = .{ .context = @intCast(window), .drafts = o.drafts, .segments = segments }; + if (@hasField(F.Options, "slide")) family_options.slide = o.slide; + if (@hasField(F.Options, "drafter")) family_options.drafter = o.drafter; + if (o.vision) |v| { + if (!@hasField(F.Options, "vision")) { + problem.* = try std.fmt.allocPrint(a, "--vision: the native CUDA engine reads images for Qwen3.8-27B only, not {s} checkpoints", .{o.model_type}); + return null; + } + family_options.vision = .{ .image_tokens = v.image_tokens, .max_images = v.max_images }; + } + if (o.kv8) { + if (!@hasField(F.Options, "kv8")) { + problem.* = try std.fmt.allocPrint(a, "--kv-cache fp8: the native CUDA engine keeps fp8 caches for Qwen3.8-27B only, not {s} checkpoints", .{o.model_type}); + return null; + } + family_options.kv8 = true; + } + const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, family_options) catch |e| { problem.* = try std.fmt.allocPrint(a, "the native CUDA engine cannot load {s} with {s} glue kernels ({s})", .{ o.dir, kernels orelse "its own", @errorName(e) }); return null; }; defer if (!opened) loaded.deinit(loaded.ctx); const model = cuda.usage(false).device - held0; const after = try pool(a, io, &g.ctx, problem) orelse return null; - const room = after.room(model) -| loaded.learn_bytes; + const vision_bytes: usize = if (@hasField(@TypeOf(loaded), "vision_bytes")) loaded.vision_bytes else 0; + const room = after.room(model) -| loaded.learn_bytes -| vision_bytes; const free = loaded.free_streams; const streams = budget.admit(room, loaded.stream_bytes, free, o.lanes, o.lanes_fixed) catch |e| { problem.* = switch (e) { @@ -344,27 +362,35 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O }; return null; }; + if (@hasDecl(F, "fit")) F.fit(loaded.ctx, streams) catch |e| { + problem.* = try std.fmt.allocPrint(a, "the native CUDA engine cannot size its attention scratch for {d} stream{s} ({s})", .{ streams, if (streams == 1) "" else "s", @errorName(e) }); + return null; + }; const h = try gpa.create(Host); errdefer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = g, .family = loaded.ctx, .release = loaded.deinit, .inner = loaded.backend, .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .lone = loaded.lone }; - const cache = budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)); - h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in passes of up to {d} rows{s}{s}; {s}", .{ - capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", - if (cache > 0) try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache", .{toGib(cache)}) else ", no prompt cache", if (kernels) |dir| try std.fmt.allocPrint(a, "glue kernels captured at {s}", .{dir}) else "own glue kernels", + // prompt-cache snapshots live in device room (Nemotron) or pinned host memory (the 27B); none means no cache + const cache = if (!@hasDecl(F, "snap_bytes")) 0 else if (@hasDecl(F, "snap_host")) hostCacheBytes(a, io, o.prompt_cache_gib) else budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)); + h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window{s}, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in passes of up to {d} rows{s}{s}; {s}", .{ + capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else if (vision_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for the image tower's calls", .{toGib(vision_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, if (o.kv8) " (fp8 caches)" else "", toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", + if (cache > 0) try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache{s}", .{ toGib(cache), if (@hasDecl(F, "snap_host")) " in host memory" else "" }) else ", no prompt cache", if (kernels) |dir| try std.fmt.allocPrint(a, "glue kernels captured at {s}", .{dir}) else "own glue kernels", }); errdefer gpa.free(h.startup); - if (cache > 0) { + if (@hasDecl(F, "snap_bytes") and cache > 0) { const pc = api.prompt_cache; const store = try gpa.create(pc.Store); - // states keep at any row at no prompt call (the head reads one token on); replies prefill when it is quiet - store.* = pc.Store.init(gpa, .{ .ptr = loaded.target, .vtable = &nemotron_snaps }, .{ .lookahead = 1, .min_prompt = 0, .warm = .waits }, cache - try nemotron.native.snap_ready(loaded.target, cache)); + // Nemotron keeps states at any row, head one token on; the 27B on its zero-anchored grid where cache-off cuts + const rules: pc.Rules = if (@hasDecl(F, "snap_host")) .{ .lookahead = F.snap_lookahead, .planned = true, .grid = F.prompt_rows } else .{ .lookahead = 1, .min_prompt = 0, .warm = .waits }; + const ready: u64 = if (@hasDecl(F, "snap_ready")) try F.snap_ready(loaded.target, cache) else 0; + store.* = pc.Store.init(gpa, .{ .ptr = loaded.target, .vtable = &Snaps(F).vtable }, rules, cache - ready); h.store = store; + if (@hasDecl(F, "useCache")) F.useCache(loaded.ctx); } errdefer if (h.store) |store| { store.deinit(); gpa.destroy(store); }; - if (loaded.learns != null) { + if (@hasDecl(F, "slide")) if (loaded.learns != null) { const Slide = nemotron_slide.Adapter(F.slide); h.dir = try gpa.dupe(u8, o.dir); const s = try gpa.create(Slide); @@ -378,17 +404,38 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O } }.f; h.learn = s.hook(); - } + }; errdefer if (h.slide) |s| { h.slide_free.?(gpa, s); gpa.free(h.dir); }; // the family cuts its own prompt grid from position 0, as `tensorfold run` does: prefill_step 0 - try h.serve(io, loaded.facts, loaded.rows, .{ .lanes = streams, .context_window = @intCast(window), .startup = h.startup, .prompt_cache = h.store != null, .warm_turns = h.store != null, .logprobs = loaded.backend.vtable.first_row != null, .prompt_logprobs = loaded.backend.vtable.prompt_rows, .structures = loaded.backend.vtable.first_masked != null }, .{ .ctx = loaded.ctx, .text = F.explain }); + const vision: ?api.Vision = if (@hasDecl(F, "prepareImage")) (if (o.vision) |v| .{ + .ctx = h, + .prepare = struct { + fn f(_: *anyopaque, al: Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + const p = try F.prepareImage(al, bytes, max_tokens); + return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash }; + } + }.f, + .image_token = F.image_token, + .markers = &F.image_markers, + .image_tokens = v.image_tokens, + .max_images = v.max_images, + } else null) else null; + try h.serve(io, loaded.facts, loaded.rows, .{ .lanes = streams, .context_window = @intCast(window), .startup = h.startup, .prompt_cache = h.store != null, .warm_turns = h.store != null and !@hasDecl(F, "snap_host"), .logprobs = loaded.backend.vtable.first_row != null, .prompt_logprobs = loaded.backend.vtable.prompt_rows, .structures = loaded.backend.vtable.first_masked != null, .vision = vision }, .{ .ctx = loaded.ctx, .text = F.explain }); opened = true; return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; } +/// A host-memory prompt cache: --prompt-cache-gib, else 8 GiB, at most half the host's available memory. +fn hostCacheBytes(a: Allocator, io: std.Io, asked: ?f64) u64 { + const want: u64 = if (asked) |g| (if (g > 0) std.math.lossyCast(u64, g * gib) else 0) else 8 << 30; + const text = budget.procText(a, io, "/proc/meminfo") orelse return 0; + const m = budget.meminfo(text) orelse return 0; + return @min(want, m.available / 2); +} + fn toGib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / gib; } diff --git a/zig/src/native/cuda_bound.zig b/zig/src/native/cuda_bound.zig index 40977dfa50..f8f5702971 100644 --- a/zig/src/native/cuda_bound.zig +++ b/zig/src/native/cuda_bound.zig @@ -18,6 +18,12 @@ pub fn vtable(comptime H: type, v: be.Backend.VTable) be.Backend.VTable { return x.inner.vtable.prefill_step.?(x.inner.ptr, s); } }.f else null, + .prefill_many = if (v.prefill_many != null) struct { + fn f(p: *anyopaque, streams: []const *lanes.Stream, errs: []?anyerror) anyerror!void { + const x = H.bind(p); + return x.inner.vtable.prefill_many.?(x.inner.ptr, streams, errs); + } + }.f else null, .first = struct { fn f(p: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { const x = H.bind(p); diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index dab379dbf3..63962a0ef8 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -16,6 +16,7 @@ pub const Host = struct { eng: *ge.Engine, slots: glm.slots.Slots, back: glm.backend.Backend, + markers: [3]u32 = undefined, // the image wrapper's tokens (--vision): begin, image, end cfg: lanes.Config, wall: lanes.backend.WallClock, core: lanes.Engine, @@ -79,8 +80,9 @@ fn learnedStates(gpa: Allocator, eng: *const ge.Engine, sl: *glm.slots.Slots, ro } /// A GLM-5.3-Flash checkpoint served: `window` tokens of cache a stream, warmed first (the pair: `speed_up`). -pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, learn: ?[]const u8, learn_cap: u64, learn_floor: u64) !*Host { - const eng = try ge.Engine.loadWith(gpa, dir, window + 64, speed_up, learn != null); +pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, learn: ?[]const u8, learn_cap: u64, learn_floor: u64, vision: ?api.VisionOpen) !*Host { + const limits: ?glm.vision.Limits = if (vision) |v| .{ .image_tokens = v.image_tokens, .max_images = v.max_images } else null; + const eng = try ge.Engine.loadWith(gpa, dir, window + 64, speed_up, learn != null, limits); errdefer eng.deinit(); var toks: [96]u32 = undefined; for (&toks, 0..) |*t, i| t.* = @intCast(1000 + i); @@ -103,8 +105,9 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.wall = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.cfg, h.back.backend(), h.wall.clock()); errdefer h.core.deinit(); + if (eng.vision) |v| h.markers = .{ v.c.image_start, v.c.image_token, v.c.image_end }; const serves = @min(window, glm.pool.capacity(&h.slots) -| (glm.state.max_rows + 1)); // prompt + reply a stream's caches hold beside its last window (a pool keeps whole blocks) - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-zig", .lanes = n, .context_window = serves, .prefill_step = eng.chunk_rows, .greedy_only = true, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-zig", .lanes = n, .context_window = serves, .prefill_step = eng.chunk_rows, .greedy_only = true, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null, .vision = if (eng.vision) |v| .{ .ctx = h, .prepare = prepareImage, .image_token = v.c.image_token, .markers = &h.markers, .image_tokens = eng.vision_limits.image_tokens, .max_images = eng.vision_limits.max_images } else null }); h.cache = null; const budget = cacheBudget(eng, cache_gib); if (!eng.followsPeer() and budget > 0) { @@ -135,6 +138,13 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: return h; } +/// Info.vision's prepare: an image's bytes to the tower's patches (families/glm/image.zig), on the HTTP thread. +fn prepareImage(ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + const h: *Host = @ptrCast(@alignCast(ctx)); + const p = try glm.image.prepare(a, bytes, h.eng.vision.?.c, max_tokens); + return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash }; +} + /// Slots.grow: the prompt cache charges a kept state's prefixes when its budget has room (the host thread's store). fn growSnap(ctx: *anyopaque, saved: *anyopaque, extra: u64) bool { const h: *Host = @ptrCast(@alignCast(ctx)); diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 39fe531408..10d8808f96 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -102,6 +102,10 @@ const Host = struct { /// The engine for `o.dir`, or null with `problem` set when no Metal engine reads the checkpoint. pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { const dense = std.mem.eql(u8, o.model_type, "qwen3_5") and qwen27Engine(a, io, o.dir); + if (o.kv8) { + problem.* = "--kv-cache fp8: the CUDA engine keeps fp8 caches; the Metal engines keep bf16"; + return null; + } if (try refusal(a, o, dense)) |why| { problem.* = why; return null; @@ -113,6 +117,10 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (dense) return openQwen27(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "qwen4_exp")) return openFlashNext(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "glm5_next")) return openGlm(a, gpa, io, o, problem); + if (o.vision != null) { + problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash only, not {s} checkpoints", .{o.model_type}); + return null; + } if (std.mem.eql(u8, o.model_type, "glm_moe_dsa")) return openGlmDsa(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "qwen3_5")) return @import("qwen35.zig").open(a, gpa, io, o, problem); if (!std.mem.eql(u8, o.model_type, "nemotron_h")) { @@ -353,7 +361,11 @@ fn openGlm(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]co } const pool = mtl.objc.Pool.push(); defer pool.pop(); - const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.learn, @intFromFloat(o.learn_gib * (1 << 30)), @intFromFloat(o.learn_min_free_gib * (1 << 30))) catch |e| { + if (o.vision != null and o.speed_up != null) { + problem.* = try std.fmt.allocPrint(a, "--vision is served on one Mac; the --speed-up pair reads text only", .{}); + return null; + } + const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.learn, @intFromFloat(o.learn_gib * (1 << 30)), @intFromFloat(o.learn_min_free_gib * (1 << 30)), o.vision) catch |e| { if (e == error.BadLoadLimit) problem.* = "GLM_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 70% of RAM" else problem.* = if (linkProblem(e)) |link| try std.fmt.allocPrint(a, "the native GLM-5.3-Flash engine cannot load {s}: {s}", .{ o.dir, link }) else try std.fmt.allocPrint(a, "the native GLM-5.3-Flash engine cannot load {s} ({s})", .{ o.dir, @errorName(e) }); return null; }; diff --git a/zig/src/server/anthropic.zig b/zig/src/server/anthropic.zig index bf465e7ac2..e8e6d38985 100644 --- a/zig/src/server/anthropic.zig +++ b/zig/src/server/anthropic.zig @@ -51,7 +51,7 @@ fn countTokens(srv: *Server, cx: *Cx, chat: Value) errors.Refused!usize { const thinking = try fields.thinkingFields(cx, chat, srv.effort_levels); const on = thinking.enable orelse srv.config.enable_thinking; const tools = try tool_specs.active(cx, chat.get("tools"), chat.get("tool_choice")); - const msgs = try messages_mod.normalize(cx, chat.get("messages"), "system", srv.needs_user_after_tool); + const msgs = try messages_mod.normalizeWith(cx, chat.get("messages"), "system", srv.needs_user_after_tool, srv.info.vision != null); const ids_ = prompt.renderIds(srv, cx, msgs, tools, on, srv.effortFor(thinking.effort), true) catch |e| switch (e) { error.Refused => return cx.other(cx.message), else => |x| return x, diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 7c702ef432..d3427ff4c0 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -141,6 +141,8 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa .decode_spans = try prompt_mod.replySpans(srv, cx, rendered.ids), // from the tokens alone, for every request: cached states are keyed by tokens .tools_json = if (input.tools.len > 0) try json.stringify(a, .{ .array = @constCast(input.tools) }, .{ .ascii = false }) else "", .decide = if (input.prompt == null and !background) prompt_mod.decideOf(srv, rendered.ids) else null, + .images = rendered.images, + .cache_key = rendered.cache_key, }; try srv.checkFeatures(cx, f, input.tools.len > 0, thinking, rendered.ids, input.tools, &request); if (thinking) { @@ -230,35 +232,6 @@ pub fn release(srv: *Server, preparing: bool) void { if (preparing) _ = srv.preparing.fetchSub(1, .acq_rel); } -/// The text a stream has sent: Python's ``streamed = visible``, grown by its delta while it only grows. -const Shown = struct { - text: std.ArrayList(u8) = .empty, - chars: usize = 0, - at: ?[*]const u8 = null, // where the last shown text lay; the decode buffer only grows, so that prefix holds - extends: bool = false, - - /// Python's ``now[len(shown):]``; ``stable``: ``now`` lies in the append-only decode buffer. - fn after(s: *Shown, now: []const u8, stable: bool) []const u8 { - const sent = s.text.items; - s.extends = (stable and s.at == now.ptr and now.len >= sent.len) or std.mem.startsWith(u8, now, sent); - if (!s.extends) return reply_text.afterChars(now, s.chars); - if (stable) s.at = now.ptr; // the buffer moved but kept its bytes: the next check is free again - return now[sent.len..]; - } - - fn set(s: *Shown, a: Allocator, now: []const u8, delta: []const u8) Allocator.Error!void { - if (s.extends) { - try s.text.appendSlice(a, delta); - s.chars += reply_text.charCount(delta); - } else { - s.text = .empty; - try s.text.appendSlice(a, now); - s.chars = reply_text.charCount(now); - } - s.at = now.ptr; - } -}; - /// The token loop and the text it streams. const Generation = struct { srv: *Server, @@ -276,8 +249,8 @@ const Generation = struct { collected: std.ArrayList(u32) = .empty, visible: reply_text.Incremental = .{}, hidden: std.ArrayList(u8) = .empty, // reused for the answer without its call blocks - streamed: Shown = .{}, // what content streamed, kept apart from the decode buffer that grows under slices - streamed_reasoning: Shown = .{}, + streamed: reply_text.Shown = .{}, // what content streamed, kept apart from the decode buffer that grows under slices + streamed_reasoning: reply_text.Shown = .{}, streaming_done: bool = false, first_ns: ?i96 = null, last_ns: ?i96 = null, diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index 76b205eeaa..16eabe0d3e 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -49,11 +49,12 @@ pub const flags = [_]Flag{ .{ .name = "--api-key-file", .native = true }, .{ .name = "--metrics-open", .kind = .store_true, .native = true }, .{ .name = "--dashboard", .kind = .store_true, .native = true }, - .{ .name = "--vision", .kind = .store_true }, - .{ .name = "--vision-urls", .kind = .store_true }, + .{ .name = "--vision", .kind = .store_true, .native = true }, + .{ .name = "--kv-cache", .choices = &.{ "bf16", "fp8" }, .native = true }, + .{ .name = "--vision-urls", .kind = .store_true, .native = true }, .{ .name = "--vision-offload", .kind = .store_true }, - .{ .name = "--vision-max-images" }, - .{ .name = "--vision-image-tokens" }, + .{ .name = "--vision-max-images", .native = true }, + .{ .name = "--vision-image-tokens", .native = true }, .{ .name = "--context", .native = true }, .{ .name = "--speed-up", .native = !cuda_build }, .{ .name = "--max-tokens", .native = true }, @@ -169,6 +170,11 @@ pub const Args = struct { master: []const u8 = "", master_port: u16 = 29551, policy: []const u8 = "", // every --policy joined by commas + kv_cache: []const u8 = "bf16", // fp8: e4m3 attention caches, a scale a row (about twice the context) + vision: bool = false, // image input (GLM-5.3-Flash): data-URL image_url parts in user messages + vision_urls: bool = false, // with --vision, public HTTPS image URLs too (media_fetch.zig) + vision_max_images: u32 = 4, + vision_image_tokens: u32 = 4096, cortheon: bool = false, // Cortheon's program, research before building, and cortheon_search/cortheon_fetch run by the server }; @@ -221,6 +227,7 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou } out.model = model orelse return fail(u, a, "the following arguments are required: model", .{}); try ranks(u, a, out); + if (out.vision_urls and !out.vision) return fail(u, a, "--vision-urls needs --vision", .{}); out.alias = alias.items; out.api_key = keys.items; return out; @@ -275,7 +282,15 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa const n = try int(u, a, name, v); if (n < 0) return fail(u, a, "argument --compact-keep: expected a token count from 0: '{s}'", .{v}); out.compact_keep = @intCast(n); - } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--cortheon")) out.cortheon = true; + } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--cortheon")) out.cortheon = true else if (is(name, "--vision")) out.vision = true else if (is(name, "--kv-cache")) out.kv_cache = v else if (is(name, "--vision-urls")) out.vision_urls = true else if (is(name, "--vision-max-images")) { + const n = try int(u, a, name, v); + if (n < 1 or n > 64) return fail(u, a, "argument --vision-max-images: expected 1 to 64 images: '{s}'", .{v}); + out.vision_max_images = @intCast(n); + } else if (is(name, "--vision-image-tokens")) { + const n = try int(u, a, name, v); + if (n < 16 or n > 16384) return fail(u, a, "argument --vision-image-tokens: expected 16 to 16384 tokens: '{s}'", .{v}); + out.vision_image_tokens = @intCast(n); + } } /// The CUDA build's --device and --segments; false for any other flag. @@ -367,6 +382,8 @@ pub fn request(a: Allocator, dir: []const u8, model_type: []const u8, args: Args .master = args.master, .master_port = args.master_port, .policy = args.policy, + .kv8 = std.mem.eql(u8, args.kv_cache, "fp8"), + .vision = if (args.vision) .{ .image_tokens = args.vision_image_tokens, .max_images = args.vision_max_images } else null, }; } @@ -451,6 +468,10 @@ test "parse and capabilities share the table" { try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-at", "0" }, &u)); try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-at", "2" }, &u)); try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-keep", "-1" }, &u)); + const urls = try parse(a, &.{ "m", "--vision", "--vision-urls" }, &u); + try std.testing.expect(urls.vision and urls.vision_urls); + try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--vision-urls" }, &u)); + try std.testing.expectEqualStrings("--vision-urls needs --vision", u.message); } test "--device and --segments: CUDA builds serve them, values checked; --speed-up is the Mac build's" { diff --git a/zig/src/server/hf_text.zig b/zig/src/server/hf_text.zig index 65c3a474d5..27ee33fde5 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -211,6 +211,7 @@ pub const HfText = struct { .template_source = sourceFn, .special = specialFn, .token_bytes = tokenBytesFn, + .encode_plain = encodePlainFn, } }; } @@ -231,6 +232,10 @@ pub const HfText = struct { return std.mem.concat(a, u32, &.{ t.prefix, ids, t.suffix }); } + fn encodePlainFn(ctx: *anyopaque, a: Allocator, s: []const u8) model_text.Error![]u32 { + return self(ctx).tok.encodePlain(a, s) catch |e| if (e == error.OutOfMemory) error.OutOfMemory else error.Template; + } + fn decodeFn(ctx: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { return self(ctx).tok.decode(a, ids, false) catch |e| if (e == error.OutOfMemory) error.OutOfMemory else a.dupe(u8, "\u{fffd}"); } diff --git a/zig/src/server/images.zig b/zig/src/server/images.zig new file mode 100644 index 0000000000..a4823c4610 --- /dev/null +++ b/zig/src/server/images.zig @@ -0,0 +1,430 @@ +//! Image input (--vision): image_url parts to the engine's tower input, the prompt's placeholders to image tokens. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json.zig"); +const errors = @import("errors.zig"); +const messages_mod = @import("messages.zig"); +const model_text = @import("model_text.zig"); +const media_fetch = @import("media_fetch.zig"); +const Value = json.Value; +const Cx = errors.Cx; + +/// images.py's limits: an image's and a request's encoded bytes, and the visual tokens of a low-detail image. +pub const max_image_bytes = 10 << 20; +pub const max_request_bytes = 20 << 20; +const low_detail_tokens = 256; + +pub const Expanded = struct { + ids: []const u32, + history_len: usize, + images: []const api.Image, + cache_key: []const u32, +}; + +const Part = struct { url: []const u8, low: bool }; + +/// The image parts of normalized `messages`, in the order the template meets them. +fn parts(cx: *Cx, messages: Value) errors.Refused![]const Part { + var out: std.ArrayList(Part) = .empty; + if (messages != .array) return out.items; + for (messages.array) |m| { + const content = m.get("content") orelse continue; + if (content != .array) continue; + for (content.array) |p| { + const kind = p.get("type") orelse continue; + if (kind != .string or !std.mem.eql(u8, kind.string, "image_url")) continue; + const iu = p.get("image_url").?; + const detail = iu.get("detail"); + try out.append(cx.a, .{ .url = iu.get("url").?.string, .low = detail != null and std.mem.eql(u8, detail.?.string, "low") }); + } + } + return out.items; +} + +/// --vision-urls: how a public HTTPS image's bytes are fetched (media_fetch.zig, or a test's fixtures). +pub const Fetch = struct { + ctx: ?*anyopaque = null, + io: std.Io, + get: *const fn (ctx: ?*anyopaque, a: std.mem.Allocator, io: std.Io, url: []const u8, max_bytes: usize, deadline: std.Io.Timestamp, f: *media_fetch.Failure) media_fetch.Error![]const u8, + + /// The network, as media_fetch checks it. + pub fn network(io: std.Io) Fetch { + return .{ .io = io, .get = struct { + fn get(_: ?*anyopaque, a: std.mem.Allocator, i: std.Io, url: []const u8, max_bytes: usize, deadline: std.Io.Timestamp, f: *media_fetch.Failure) media_fetch.Error![]const u8 { + return (try media_fetch.fetch(a, i, url, max_bytes, deadline, &media_fetch.image_media, f)).data; + } + }.get }; + } +}; + +/// An image part's bytes, at most `limit`: a data URL's, or with --vision-urls a public HTTPS URL's before `deadline`. +pub fn sourceBytes(cx: *Cx, fetch: ?Fetch, url: []const u8, limit: usize, deadline: std.Io.Timestamp) errors.Refused![]const u8 { + if (std.ascii.startsWithIgnoreCase(url, "data:")) { + const bytes = try dataBytes(cx, url); + if (bytes.len > limit) return cx.refuse("the request's images exceed 20 MB encoded"); + return bytes; + } + if (!std.mem.startsWith(u8, url, "https://")) return cx.refuse("images require data URLs or public HTTPS URLs"); + const f = fetch orelse return cx.refuse("image URLs are off on this server; send the image as a data URL, or start the server with --vision-urls"); + if (url.len > media_fetch.max_url_chars) return cx.refuse("image URL is too long"); + var failure: media_fetch.Failure = .{}; + const bytes = f.get(f.ctx, cx.a, f.io, url, limit, deadline, &failure) catch |e| switch (e) { + error.OutOfMemory => return error.OutOfMemory, + error.Media => return cx.refuse(failure.text), + }; + if (bytes.len == 0) return cx.refuse("image is empty or exceeds the encoded byte limit"); + return bytes; +} + +/// A data URL's bytes (base64 or percent-encoded). +pub fn dataBytes(cx: *Cx, url: []const u8) errors.Refused![]const u8 { + if (!std.ascii.startsWithIgnoreCase(url, "data:")) return cx.refuse("invalid image data URL"); + const comma = std.mem.indexOfScalar(u8, url, ',') orelse return cx.refuse("invalid image data URL"); + const header = url[5..comma]; + const payload = url[comma + 1 ..]; + if (header.len > 256) return cx.refuse("invalid image data URL"); + var it = std.mem.splitScalar(u8, header, ';'); + _ = it.next(); + const enc = it.next(); + if (it.next() != null or (enc != null and !std.ascii.eqlIgnoreCase(enc.?, "base64"))) return cx.refuse("image data URL supports only optional base64 encoding"); + if (enc != null) { + if (payload.len > 4 * ((max_image_bytes + 2) / 3)) return cx.refuse("image data URL exceeds the encoded byte limit"); + const d = std.base64.standard.Decoder; + const n = d.calcSizeForSlice(payload) catch return cx.refuse("invalid image data URL encoding"); + const out = try cx.a.alloc(u8, n); + d.decode(out, payload) catch return cx.refuse("invalid image data URL encoding"); + if (out.len == 0 or out.len > max_image_bytes) return cx.refuse("image is empty or exceeds the encoded byte limit"); + return out; + } + if (payload.len > max_image_bytes * 3) return cx.refuse("image data URL exceeds the encoded byte limit"); + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < payload.len) : (i += 1) { + if (payload[i] == '%' and i + 2 < payload.len) { + const b = std.fmt.parseInt(u8, payload[i + 1 .. i + 3], 16) catch return cx.refuse("invalid image data URL encoding"); + try out.append(cx.a, b); + i += 2; + } else try out.append(cx.a, payload[i]); + } + if (out.items.len == 0 or out.items.len > max_image_bytes) return cx.refuse("image is empty or exceeds the encoded byte limit"); + return out.items; +} + +pub const Format = enum { png, jpeg, gif, webp, other }; + +/// The image's format from its first bytes, before any decoder sees it. +pub fn sniff(bytes: []const u8) Format { + if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n")) return .png; + if (std.mem.startsWith(u8, bytes, "\xff\xd8\xff")) return .jpeg; + if (std.mem.startsWith(u8, bytes, "GIF87a") or std.mem.startsWith(u8, bytes, "GIF89a")) return .gif; + if (bytes.len >= 12 and std.mem.eql(u8, bytes[0..4], "RIFF") and std.mem.eql(u8, bytes[8..12], "WEBP")) return .webp; + return .other; +} + +fn refusal(cx: *Cx, i: usize, err: anyerror) errors.Refused { + return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.ImageTooLarge => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} exceeds the limits: 10 MB encoded, 8192 pixels a side, 16 megapixels", .{i + 1})), + error.Animated => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d}: animated and multipage images are unsupported; send a single frame", .{i + 1})), + error.ImageTooSmall => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d}: the visual-token budget is too small for an image", .{i + 1})), + else => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} could not be decoded; send PNG or JPEG", .{i + 1})), + }; +} + +/// A quoted marker's stand-in while the template renders: two private-use code points, the second naming the marker. +const sentinel = "\u{F0000}"; + +/// The image markers' text (Vision.markers), longest first so one never matches inside another. +pub fn markerText(text: model_text.Text, a: std.mem.Allocator, v: api.Vision) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + for (v.markers) |id| { + const s = try text.tokenString(a, id); + if (s.len > 0) try out.append(a, s); + } + std.mem.sort([]const u8, out.items, {}, struct { + fn longer(_: void, x: []const u8, y: []const u8) bool { + return x.len > y.len; + } + }.longer); + return out.items; +} + +/// `messages` with each marker the text spells replaced by its sentinel, so only the template's become images (#511). +pub fn shield(a: std.mem.Allocator, v: Value, markers: []const []const u8) !Value { + return switch (v) { + .string => |s| .{ .string = try shieldText(a, s, markers) }, + .array => |items| blk: { + const out = try a.alloc(Value, items.len); + for (items, out) |x, *o| o.* = try shield(a, x, markers); + break :blk .{ .array = out }; + }, + .object => |o| blk: { + const out = try json.newObject(a); + var it = o.iterator(); + while (it.next()) |kv| try out.put(a, kv.key_ptr.*, try shield(a, kv.value_ptr.*, markers)); + break :blk .{ .object = out }; + }, + else => v, + }; +} + +fn shieldText(a: std.mem.Allocator, s: []const u8, markers: []const []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + var changed = false; + outer: while (i < s.len) { + for (markers, 0..) |m, k| if (std.mem.startsWith(u8, s[i..], m)) { + try out.appendSlice(a, sentinel); + try out.appendSlice(a, try std.fmt.allocPrint(a, "{u}", .{@as(u21, @intCast(0xF0001 + k))})); + i += m.len; + changed = true; + continue :outer; + }; + try out.append(a, s[i]); + i += 1; + } + return if (changed) out.items else s; +} + +/// The rendered prompt's ids, each sentinel's marker as ordinary text tokens; otherwise exactly `encode`'s ids. +pub fn encodeShielded(text: model_text.Text, a: std.mem.Allocator, rendered: []const u8, markers: []const []const u8) model_text.Error![]u32 { + var ids: std.ArrayList(u32) = .empty; + var rest = rendered; + while (std.mem.indexOf(u8, rest, sentinel)) |at| { + const after = rest[at + sentinel.len ..]; + const cp: u21 = if (after.len >= 4) std.unicode.utf8Decode(after[0..4]) catch 0 else 0; + const k: usize = if (cp >= 0xF0001) cp - 0xF0001 else markers.len; + if (k >= markers.len) { // not one of ours: the code point is ordinary text + try ids.appendSlice(a, try text.encode(a, rest[0 .. at + sentinel.len], false)); + rest = after; + continue; + } + try ids.appendSlice(a, try text.encode(a, rest[0..at], false)); + try ids.appendSlice(a, try text.encodePlain(a, markers[k])); + rest = after[4..]; + } + try ids.appendSlice(a, try text.encode(a, rest, false)); + return ids.items; +} + +/// The prompt with each image's placeholder expanded to its tokens, the images and the cache key; null without vision. +pub fn expand(vision: ?api.Vision, fetch: ?Fetch, cx: *Cx, messages: Value, ids: []const u32, history_len: usize) errors.Refused!?Expanded { + const v = vision orelse return null; + const ps = try parts(cx, messages); + var marks: usize = 0; + for (ids) |t| marks += @intFromBool(t == v.image_token); + if (marks != ps.len) return cx.fail(.server, "the chat template wrote {d} image placeholders for {d} image parts", .{ marks, ps.len }); + if (ps.len == 0) return null; + if (ps.len > v.max_images) return cx.refuse(try std.fmt.allocPrint(cx.a, "a request may hold at most {d} images (--vision-max-images); it has {d}", .{ v.max_images, ps.len })); + const budget = v.image_tokens / @as(u32, @intCast(ps.len)); + if (budget < 1) return cx.refuse("the image count exceeds the visual-token budget"); + const prepared = try cx.a.alloc(api.PreparedImage, ps.len); + var bytes_total: usize = 0; + var extra: usize = 0; + // every URL's download inside one request's seconds (images.py total_timeout_seconds) + const deadline: std.Io.Timestamp = if (fetch) |f| std.Io.Clock.awake.now(f.io).addDuration(.fromSeconds(media_fetch.total_s)) else .{ .nanoseconds = 0 }; + for (ps, prepared, 0..) |p, *out, i| { + const bytes = try sourceBytes(cx, fetch, p.url, @min(max_image_bytes, max_request_bytes - bytes_total), deadline); + bytes_total += bytes.len; + switch (sniff(bytes)) { // the Python frontend's formats (images.py: JPEG, PNG, WebP), WebP not yet decoded here + .png, .jpeg => {}, + .webp => return cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} is WebP, which this server does not decode yet; send PNG or JPEG", .{i + 1})), + .gif, .other => return cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} is not PNG or JPEG; send one of those", .{i + 1})), + } + const cap = if (p.low) @min(budget, low_detail_tokens) else budget; + out.* = v.prepare(v.ctx, cx.a, bytes, cap) catch |e| return refusal(cx, i, e); + if (out.tokens == 0 or out.tokens > cap) return cx.refuse("the image processor exceeded the per-image visual-token budget"); + extra += out.tokens - 1; + } + const n = ids.len + extra; + const out_ids = try cx.a.alloc(u32, n); + const key = try cx.a.alloc(u32, n); + const imgs = try cx.a.alloc(api.Image, ps.len); + var hist = history_len; + var at: usize = 0; + var k: usize = 0; + for (ids, 0..) |t, src| { + if (t != v.image_token) { + out_ids[at] = t; + key[at] = t; + at += 1; + continue; + } + const img = prepared[k]; + imgs[k] = .{ .pixels = img.pixels, .gh = img.gh, .gw = img.gw, .at = @intCast(at), .tokens = img.tokens }; + if (src < history_len) hist += img.tokens - 1; + for (0..img.tokens) |j| { + out_ids[at + j] = t; + // the cache's ids for this image's rows: past the vocabulary, by content and row + key[at + j] = 0x8000_0000 | @as(u32, @truncate(std.hash.Wyhash.hash(img.hash, std.mem.asBytes(&j)) & 0x7fff_ffff)); + } + at += img.tokens; + k += 1; + } + return .{ .ids = out_ids, .history_len = hist, .images = imgs, .cache_key = key }; +} + +test "data URLs decode; remote URLs are refused" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var cx: Cx = .{ .a = arena.allocator() }; + try std.testing.expectEqualStrings("hi!", try dataBytes(&cx, "data:image/png;base64,aGkh")); + try std.testing.expectEqualStrings("a b", try dataBytes(&cx, "data:text/plain,a%20b")); + try std.testing.expectError(error.Refused, dataBytes(&cx, "data:image/png;base64,***")); + // without --vision-urls an https URL is refused with the flag's name; other schemes always + const never: std.Io.Timestamp = .{ .nanoseconds = 0 }; + try std.testing.expectError(error.Refused, sourceBytes(&cx, null, "https://example.com/x.png", max_image_bytes, never)); + try std.testing.expectEqualStrings("image URLs are off on this server; send the image as a data URL, or start the server with --vision-urls", cx.message); + for ([_][]const u8{ "http://example.com/x.png", "ftp://example.com/x.png", "HTTPS://example.com/x.png", "file:///etc/passwd" }) |u| { + try std.testing.expectError(error.Refused, sourceBytes(&cx, null, u, max_image_bytes, never)); + try std.testing.expectEqualStrings("images require data URLs or public HTTPS URLs", cx.message); + } + try std.testing.expectError(error.Refused, sourceBytes(&cx, null, "data:,abc", 2, never)); +} + +fn fakePrepare(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + _ = ctx; + _ = max_tokens; + const tokens: u32 = @intCast(bytes.len - 3); // the test's images: a JPEG's first bytes, then one token a byte + return .{ .pixels = try a.alloc(f32, 0), .gh = 2, .gw = 2 * tokens, .tokens = tokens, .hash = bytes[3] }; +} + +test "placeholders expand to each image's tokens, the history and cache key with them" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + var dummy: u8 = 0; + const v: api.Vision = .{ .ctx = &dummy, .prepare = fakePrepare, .image_token = 9, .image_tokens = 64, .max_images = 4 }; + const text = + \\[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,%FF%D8%FFab"}}, {"type": "text", "text": "x"}]}, + \\ {"role": "assistant", "content": "y"}, + \\ {"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,%FF%D8%FFcde"}}]}] + ; + const msgs = switch (try json.parseText(a, text)) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + const ids = [_]u32{ 1, 9, 2, 3, 9, 4 }; + const x = (try expand(v, null, &cx, msgs, &ids, 4)).?; + try std.testing.expectEqualSlices(u32, &.{ 1, 9, 9, 2, 3, 9, 9, 9, 4 }, x.ids); + try std.testing.expectEqual(@as(usize, 5), x.history_len); // the first image is in the history, the second not + try std.testing.expectEqual(@as(u32, 1), x.images[0].at); + try std.testing.expectEqual(@as(u32, 5), x.images[1].at); + try std.testing.expect(x.cache_key[1] >= 0x8000_0000 and x.cache_key[1] != x.cache_key[2]); + try std.testing.expectEqual(@as(u32, 2), x.cache_key[3]); + // a placeholder the images do not account for is refused + try std.testing.expectError(error.Refused, expand(v, null, &cx, msgs, &[_]u32{ 9, 9, 9 }, 0)); + _ = messages_mod; +} + +test "--vision-urls: an https part's bytes come from the fetch, within what the request has left" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + var dummy: u8 = 0; + const v: api.Vision = .{ .ctx = &dummy, .prepare = fakePrepare, .image_token = 9, .image_tokens = 64, .max_images = 4 }; + const Pages = struct { + var limits: [4]usize = undefined; + var n: usize = 0; + fn get(_: ?*anyopaque, al: std.mem.Allocator, _: std.Io, url: []const u8, max_bytes: usize, _: std.Io.Timestamp, f: *media_fetch.Failure) media_fetch.Error![]const u8 { + limits[n] = max_bytes; + n += 1; + if (std.mem.eql(u8, url, "https://e.com/a.jpg")) return al.dupe(u8, "\xff\xd8\xffxyz"); + f.text = "image download returned HTTP 404"; + return error.Media; + } + }; + const fetch: Fetch = .{ .io = std.testing.io, .get = Pages.get }; + const text = + \\[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,%FF%D8%FFab"}}, + \\ {"type": "image_url", "image_url": {"url": "https://e.com/a.jpg"}}]}] + ; + const msgs = switch (try json.parseText(a, text)) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + const x = (try expand(v, fetch, &cx, msgs, &[_]u32{ 1, 9, 9, 2 }, 0)).?; + try std.testing.expectEqualSlices(u32, &.{ 1, 9, 9, 9, 9, 9, 2 }, x.ids); // 2 tokens, then the fetched image's 3 + try std.testing.expectEqual(@as(u32, 3), x.images[1].at); + try std.testing.expectEqual(@as(usize, max_image_bytes), Pages.limits[0]); // 5 bytes used of 20 MB: 10 MB left + // the fetch's refusal is the request's; without the fetch the URL is refused by the flag's name + const missing = switch (try json.parseText(a, "[{\"role\": \"user\", \"content\": [{\"type\": \"image_url\", \"image_url\": {\"url\": \"https://e.com/gone.png\"}}]}]")) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + try std.testing.expectError(error.Refused, expand(v, fetch, &cx, missing, &[_]u32{9}, 0)); + try std.testing.expectEqualStrings("image download returned HTTP 404", cx.message); + try std.testing.expectError(error.Refused, expand(v, null, &cx, missing, &[_]u32{9}, 0)); + try std.testing.expectEqualStrings("image URLs are off on this server; send the image as a data URL, or start the server with --vision-urls", cx.message); +} + +/// A test tokenizer: "<|image|>" is token 9 unless read plainly, every other byte its own id plus 100. +const MarkText = struct { + fn text() model_text.Text { + return .{ .ctx = undefined, .vtable = &.{ .encode = encode, .decode = undefined, .token_id = undefined, .token_string = tokenString, .vocab_size = undefined, .eos_ids = undefined, .render = undefined, .template_source = undefined, .encode_plain = plain } }; + } + fn encode(_: *anyopaque, a: std.mem.Allocator, s: []const u8, _: bool) model_text.Error![]u32 { + var out: std.ArrayList(u32) = .empty; + var i: usize = 0; + while (i < s.len) { + if (std.mem.startsWith(u8, s[i..], "<|image|>")) { + try out.append(a, 9); + i += 9; + } else { + try out.append(a, @as(u32, s[i]) + 100); + i += 1; + } + } + return out.items; + } + fn plain(_: *anyopaque, a: std.mem.Allocator, s: []const u8) model_text.Error![]u32 { + const out = try a.alloc(u32, s.len); + for (out, s) |*o, c| o.* = @as(u32, c) + 100; + return out; + } + fn tokenString(_: *anyopaque, a: std.mem.Allocator, id: u32) std.mem.Allocator.Error![]u8 { + return a.dupe(u8, if (id == 9) "<|image|>" else ""); + } +}; + +test "a marker the text spells stays text: only the template's markers are image tokens (#511)" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var dummy: u8 = 0; + const v: api.Vision = .{ .ctx = &dummy, .prepare = fakePrepare, .image_token = 9, .markers = &.{9}, .image_tokens = 64, .max_images = 4 }; + const markers = try markerText(MarkText.text(), a, v); + const conversation = + \\[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,ab"}}, {"type": "text", "text": "what is <|image|>?"}]}, + \\ {"role": "tool", "content": "source: x = '<|image|>'"}] + ; + const msgs = switch (try json.parseText(a, conversation)) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + const shielded = try shield(a, msgs, markers); + // the "template": one marker per image part, then each message's text + var rendered: std.ArrayList(u8) = .empty; + try rendered.appendSlice(a, "<|image|>"); + try rendered.appendSlice(a, shielded.array[0].get("content").?.array[1].get("text").?.string); + try rendered.appendSlice(a, shielded.array[1].get("content").?.string); + const ids = try encodeShielded(MarkText.text(), a, rendered.items, markers); + var marks: usize = 0; + for (ids) |t| marks += @intFromBool(t == 9); + try std.testing.expectEqual(@as(usize, 1), marks); + // the quoted markers read as their characters, and text without one is exactly encode's + try std.testing.expectEqualSlices(u32, try MarkText.encode(undefined, a, "<|image|>what is ", false), ids[0..9]); + try std.testing.expectEqual(@as(u32, '<' + 100), ids[9]); + const plain_text = "no markers here"; + try std.testing.expectEqualSlices(u32, try MarkText.encode(undefined, a, plain_text, false), try encodeShielded(MarkText.text(), a, plain_text, markers)); +} + +test "formats from their first bytes: WebP is refused by name" { + try std.testing.expectEqual(Format.png, sniff("\x89PNG\r\n\x1a\nrest")); + try std.testing.expectEqual(Format.jpeg, sniff("\xff\xd8\xff\xe0")); + try std.testing.expectEqual(Format.gif, sniff("GIF89a...")); + try std.testing.expectEqual(Format.webp, sniff("RIFF\x10\x00\x00\x00WEBPVP8 ")); + try std.testing.expectEqual(Format.other, sniff("\x00\x00\x00\x18ftypheic")); +} diff --git a/zig/src/server/media_fetch.zig b/zig/src/server/media_fetch.zig new file mode 100644 index 0000000000..6183039a74 --- /dev/null +++ b/zig/src/server/media_fetch.zig @@ -0,0 +1,485 @@ +//! Public HTTPS images for --vision-urls as TensorFold 0.6.6 fetched them: every address and redirect checked public. +const std = @import("std"); +const Io = std.Io; +const net = std.Io.net; + +pub const Error = error{ OutOfMemory, Media }; + +/// The failure's words for the client (the request is refused with them). +pub const Failure = struct { text: []const u8 = "" }; + +/// images.py's ImageLimits: a URL's characters, the redirects followed, one download's seconds and a request's. +pub const max_url_chars = 4096; +pub const max_redirects = 3; +pub const timeout_s = 10; +pub const total_s = 30; + +/// images_http.MEDIA_TYPES: the declared types an image URL may answer with (WebP is refused after, by its bytes). +pub const image_media = [_][]const u8{ "image/jpeg", "image/png", "image/webp" }; + +fn fail(f: *Failure, text: []const u8) Error { + f.text = text; + return error.Media; +} + +/// Python ipaddress is_global, less multicast, reserved, 192.0.0.0/24, 168.63.129.16 and IPv6 embedding an IPv4 one. +pub fn publicIp(a: net.IpAddress) bool { + switch (a) { + .ip4 => |v| { + const x = std.mem.readInt(u32, &v.bytes, .big); + const blocked = [_]struct { [4]u8, u5 }{ + .{ .{ 0, 0, 0, 0 }, 8 }, .{ .{ 10, 0, 0, 0 }, 8 }, .{ .{ 100, 64, 0, 0 }, 10 }, .{ .{ 127, 0, 0, 0 }, 8 }, + .{ .{ 169, 254, 0, 0 }, 16 }, .{ .{ 172, 16, 0, 0 }, 12 }, .{ .{ 192, 0, 0, 0 }, 24 }, .{ .{ 192, 0, 2, 0 }, 24 }, + .{ .{ 192, 168, 0, 0 }, 16 }, .{ .{ 198, 18, 0, 0 }, 15 }, .{ .{ 198, 51, 100, 0 }, 24 }, .{ .{ 203, 0, 113, 0 }, 24 }, + .{ .{ 224, 0, 0, 0 }, 4 }, .{ .{ 240, 0, 0, 0 }, 4 }, + }; + for (blocked) |blk| { + const mask = ~@as(u32, 0) << @intCast(32 - @as(u6, blk[1])); + if (x & mask == std.mem.readInt(u32, &blk[0], .big) & mask) return false; + } + return !std.mem.eql(u8, &v.bytes, &.{ 168, 63, 129, 16 }); + }, + .ip6 => |v| { + const b = v.bytes; + // global unicast 2000::/3 less documentation, the 2001::/23 IETF block (Teredo among it) and 6to4 + if (b[0] & 0xe0 != 0x20) return false; + if (b[0] == 0x20 and b[1] == 0x01 and b[2] == 0x0d and b[3] == 0xb8) return false; + if (b[0] == 0x20 and b[1] == 0x01 and b[2] < 0x02) return false; + return !(b[0] == 0x20 and b[1] == 0x02); + }, + } +} + +/// A URL as a request takes it: the lowercased host and the percent-quoted path and query. +pub const Url = struct { host: []const u8, target: []const u8 }; + +/// images_http._url: https, port 443, no credentials, fragment, backslash, whitespace, controls, IDNA or IPv6 host. +pub fn parseUrl(a: std.mem.Allocator, value: []const u8, f: *Failure) Error!Url { + if (value.len > max_url_chars) return fail(f, "image URL is too long or contains whitespace/control characters"); + for (value) |c| if (c <= 32 or c == 127) return fail(f, "image URL is too long or contains whitespace/control characters"); + const bad = "image URL must be HTTPS on port 443, without credentials or a fragment"; + if (!std.ascii.startsWithIgnoreCase(value, "https://")) return fail(f, bad); + if (std.mem.indexOfAny(u8, value, "\\#") != null) return fail(f, bad); + const rest = value["https://".len..]; + const end = std.mem.indexOfAny(u8, rest, "/?") orelse rest.len; + const authority = rest[0..end]; + if (std.mem.indexOfScalar(u8, authority, '@') != null or std.mem.startsWith(u8, authority, "[")) return fail(f, bad); + var host = authority; + if (std.mem.lastIndexOfScalar(u8, authority, ':')) |c| { + const port = authority[c + 1 ..]; + if (port.len > 0 and !std.mem.eql(u8, port, "443")) return fail(f, bad); + host = authority[0..c]; + } + if (host.len == 0 or std.mem.indexOfScalar(u8, host, '%') != null) return fail(f, bad); + for (host) |c| if (c >= 128) return fail(f, bad); + const lower = try std.ascii.allocLowerString(a, host); + const name = std.mem.trimEnd(u8, lower, "."); + for ([_][]const u8{ "localhost", "metadata.google.internal", "instance-data" }) |n| if (std.mem.eql(u8, name, n)) return fail(f, "image URLs must use public internet hosts"); + // the path and query, percent-quoted as urllib.parse.quote(safe=...) leaves them + var t: std.ArrayList(u8) = .empty; + const tail = rest[end..]; + if (tail.len == 0 or tail[0] == '?') try t.append(a, '/'); + var in_query = false; + var query_at: usize = 0; + for (tail) |c| { + if (c == '?' and !in_query) { + in_query = true; + try t.append(a, '?'); + query_at = t.items.len; + continue; + } + const safe = std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "/%:@!$&'()*+,;=-._~", c) != null or (in_query and c == '?'); + if (safe) try t.append(a, c) else try t.print(a, "%{X:0>2}", .{c}); + } + if (in_query and t.items.len == query_at) t.items.len -= 1; // an empty query, as urlsplit drops it + return .{ .host = lower, .target = t.items }; +} + +/// The location a redirect names, resolved against `base` (urljoin's absolute, scheme-relative and relative forms). +pub fn join(a: std.mem.Allocator, base: []const u8, location: []const u8) ![]const u8 { + if (std.ascii.startsWithIgnoreCase(location, "https://") or std.ascii.startsWithIgnoreCase(location, "http://")) return a.dupe(u8, location); + if (std.mem.startsWith(u8, location, "//")) return std.fmt.allocPrint(a, "https:{s}", .{location}); + const rest = base["https://".len..]; + const end = std.mem.indexOfAny(u8, rest, "/?") orelse rest.len; + const origin = base[0 .. "https://".len + end]; + if (std.mem.startsWith(u8, location, "/")) return std.fmt.allocPrint(a, "{s}{s}", .{ origin, location }); + const path = rest[end..][0 .. std.mem.indexOfScalar(u8, rest[end..], '?') orelse rest.len - end]; + const dir = if (std.mem.lastIndexOfScalar(u8, path, '/')) |s| path[0 .. s + 1] else "/"; + return std.fmt.allocPrint(a, "{s}{s}{s}", .{ origin, dir, location }); +} + +fn remaining(io: Io, deadline: Io.Timestamp, f: *Failure) Error!i64 { + const left = Io.Clock.awake.now(io).durationTo(deadline).toMilliseconds(); + if (left <= 0) return fail(f, "image download timed out"); + return left; +} + +/// A fetched body and its declared media type. +pub const Body = struct { data: []u8, media: []const u8 }; + +/// What one request gave: the body, or a redirect's location. +pub const Got = union(enum) { body: Body, redirect: []const u8 }; + +/// `url`'s bytes and media type (one of `media_types`), at most `max_bytes`, before `deadline`, redirects rechecked. +pub fn fetch(a: std.mem.Allocator, io: Io, url: []const u8, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Body { + return fetchVia(a, io, url, max_bytes, deadline, media_types, f, Network{}); +} + +/// fetch over `via`, whose request(a, io, url, max_bytes, deadline, media_types, f) answers one checked URL. +pub fn fetchVia(a: std.mem.Allocator, io: Io, url_in: []const u8, max_bytes: usize, deadline_in: Io.Timestamp, media_types: []const []const u8, f: *Failure, via: anytype) Error!Body { + const one = Io.Clock.awake.now(io).addDuration(.fromSeconds(timeout_s)); + const deadline = if (one.nanoseconds < deadline_in.nanoseconds) one else deadline_in; + var url = url_in; + var hop: usize = 0; + while (true) : (hop += 1) { + const u = try parseUrl(a, url, f); + switch (try via.request(a, io, u, max_bytes, deadline, media_types, f)) { + .body => |b| return b, + .redirect => |location| { + if (hop == max_redirects) return fail(f, "image download has too many redirects"); + url = try join(a, url, location); + }, + } + } +} + +/// The GET a checked URL is asked with. +pub fn ask(w: *Io.Writer, u: Url, accept: []const u8) Io.Writer.Error!void { + try w.print("GET {s} HTTP/1.1\r\nHost: {s}\r\nAccept: {s}\r\nAccept-Encoding: identity\r\nUser-Agent: TensorFold-native\r\nConnection: close\r\n\r\n", .{ u.target, u.host, accept }); + try w.flush(); +} + +/// The response from `r`: a redirect's location, or a 200's body when its encoding, declared type and length pass. +pub fn answer(a: std.mem.Allocator, io: Io, r: *Io.Reader, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Got { + const broke = "image download failed or timed out"; + const too_big = "image response exceeds the encoded byte limit"; + const status_line = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + if (status_line.len < 12 or !std.mem.startsWith(u8, status_line, "HTTP/1.")) return fail(f, broke); + const status = std.fmt.parseInt(u16, status_line[9..12], 10) catch return fail(f, broke); + var location: ?[]const u8 = null; + var media: []const u8 = ""; + var length: ?usize = null; + var chunked = false; + var encoded = false; + var header_bytes: usize = 0; + while (true) { + const line = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + header_bytes += line.len; + if (header_bytes > 64 * 1024) return fail(f, broke); + const l = std.mem.trimEnd(u8, line, "\r\n"); + if (l.len == 0) break; + const colon = std.mem.indexOfScalar(u8, l, ':') orelse continue; + const key = std.mem.trim(u8, l[0..colon], " \t"); + const val = std.mem.trim(u8, l[colon + 1 ..], " \t"); + if (std.ascii.eqlIgnoreCase(key, "location")) { + location = try a.dupe(u8, val); + } else if (std.ascii.eqlIgnoreCase(key, "content-type")) { + media = try std.ascii.allocLowerString(a, std.mem.trim(u8, val[0 .. std.mem.indexOfScalar(u8, val, ';') orelse val.len], " \t")); + } else if (std.ascii.eqlIgnoreCase(key, "content-length")) { + if (val.len == 0) return fail(f, too_big); + for (val) |c| if (!std.ascii.isDigit(c)) return fail(f, too_big); + length = std.fmt.parseInt(usize, val, 10) catch return fail(f, too_big); + } else if (std.ascii.eqlIgnoreCase(key, "transfer-encoding")) { + chunked = std.ascii.findIgnoreCase(val, "chunked") != null; + } else if (std.ascii.eqlIgnoreCase(key, "content-encoding") and !std.ascii.eqlIgnoreCase(val, "identity")) encoded = true; + } + _ = try remaining(io, deadline, f); + switch (status) { + 301, 302, 303, 307, 308 => return .{ .redirect = location orelse return fail(f, "image redirect has no destination") }, + 200 => {}, + else => return fail(f, try std.fmt.allocPrint(a, "image download returned HTTP {d}", .{status})), + } + if (encoded) return fail(f, "compressed HTTP image responses are unsupported"); + for (media_types) |m| { + if (std.mem.eql(u8, m, media)) break; + } else return fail(f, "image URL content type must be JPEG, PNG or WebP"); + if (length) |n| if (n > max_bytes) return fail(f, too_big); + var data: std.ArrayList(u8) = .empty; + if (chunked) { + while (true) { + _ = try remaining(io, deadline, f); + const size_line = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + const hex = std.mem.trim(u8, size_line[0 .. std.mem.indexOfScalar(u8, size_line, ';') orelse size_line.len], " \t\r\n"); + const n = std.fmt.parseInt(usize, hex, 16) catch return fail(f, broke); + if (n == 0) break; + if (n > max_bytes - data.items.len) return fail(f, too_big); + try readInto(a, io, r, &data, n, deadline, f); + const crlf = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + if (std.mem.trimEnd(u8, crlf, "\r\n").len != 0) return fail(f, broke); + } + } else if (length) |n| { + try readInto(a, io, r, &data, n, deadline, f); + } else while (true) { // no length: to the end of the stream (Connection: close) + _ = try remaining(io, deadline, f); + const piece = r.peekGreedy(1) catch |e| switch (e) { + error.EndOfStream => break, + else => return fail(f, broke), + }; + if (piece.len > max_bytes - data.items.len) return fail(f, too_big); + try data.appendSlice(a, piece); + r.toss(piece.len); + } + _ = try remaining(io, deadline, f); + return .{ .body = .{ .data = data.items, .media = media } }; +} + +/// Exactly `n` more bytes from `r` onto `data`, in whatever pieces the reader's buffer holds. +fn readInto(a: std.mem.Allocator, io: Io, r: *Io.Reader, data: *std.ArrayList(u8), n: usize, deadline: Io.Timestamp, f: *Failure) Error!void { + var left = n; + while (left > 0) { + _ = try remaining(io, deadline, f); + const piece = r.peekGreedy(1) catch return fail(f, "image download failed or timed out"); + const take = @min(piece.len, left); + try data.appendSlice(a, piece[0..take]); + r.toss(take); + left -= take; + } +} + +/// A TCP connection to the checked address on port 443, its connect bounded by `ms` (std's connect has no timeout). +fn connect(addr: net.IpAddress, ms: i64, f: *Failure) Error!net.Stream { + const c = std.c; + const failed = "image download failed or timed out"; + var storage: c.sockaddr.storage = undefined; + var len: c.socklen_t = undefined; + switch (addr) { + .ip4 => |v| { + const sa: *c.sockaddr.in = @ptrCast(@alignCast(&storage)); + sa.* = std.mem.zeroes(c.sockaddr.in); + sa.family = c.AF.INET; + sa.port = std.mem.nativeToBig(u16, 443); + sa.addr = @bitCast(v.bytes); + len = @sizeOf(c.sockaddr.in); + }, + .ip6 => |v| { + const sa: *c.sockaddr.in6 = @ptrCast(@alignCast(&storage)); + sa.* = std.mem.zeroes(c.sockaddr.in6); + sa.family = c.AF.INET6; + sa.port = std.mem.nativeToBig(u16, 443); + sa.addr = v.bytes; + len = @sizeOf(c.sockaddr.in6); + }, + } + const fd = c.socket(@as(c_uint, storage.family), c.SOCK.STREAM, 0); + if (fd < 0) return fail(f, failed); + errdefer _ = c.close(fd); + _ = c.fcntl(fd, c.F.SETFD, @as(c_int, c.FD_CLOEXEC)); + const flags = c.fcntl(fd, c.F.GETFL); + const nonblock: c_int = @bitCast(@as(u32, @bitCast(c.O{ .NONBLOCK = true }))); + if (flags < 0 or c.fcntl(fd, c.F.SETFL, flags | nonblock) < 0) return fail(f, failed); + if (c.connect(fd, @ptrCast(&storage), len) != 0) { + if (c.errno(@as(c_int, -1)) != .INPROGRESS) return fail(f, failed); + var pfd = [_]c.pollfd{.{ .fd = fd, .events = c.POLL.OUT, .revents = 0 }}; + if (c.poll(&pfd, 1, @intCast(@min(ms, std.math.maxInt(c_int)))) != 1) return fail(f, failed); + var err: c_int = 0; + var err_len: c.socklen_t = @sizeOf(c_int); + if (c.getsockopt(fd, c.SOL.SOCKET, c.SO.ERROR, &err, &err_len) != 0 or err != 0) return fail(f, failed); + } + if (c.fcntl(fd, c.F.SETFL, flags) < 0) return fail(f, failed); + const tv: c.timeval = .{ .sec = @intCast(@divTrunc(ms, 1000)), .usec = @intCast(@mod(ms, 1000) * 1000) }; + _ = c.setsockopt(fd, c.SOL.SOCKET, c.SO.RCVTIMEO, &tv, @sizeOf(c.timeval)); + _ = c.setsockopt(fd, c.SOL.SOCKET, c.SO.SNDTIMEO, &tv, @sizeOf(c.timeval)); + return .{ .socket = .{ .handle = fd, .address = addr } }; +} + +var bundle_lock: Io.RwLock = .init; +var bundle: std.crypto.Certificate.Bundle = .empty; +var bundle_loaded = false; + +/// The network: every address the host resolves to checked public, then TLS verified for the host on the first. +const Network = struct { + fn request(_: Network, a: std.mem.Allocator, io: Io, u: Url, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Got { + const unresolved = "image host could not be resolved"; + var first: ?net.IpAddress = null; + if (net.IpAddress.parseIp4(u.host, 443)) |literal| { + if (!publicIp(literal)) return fail(f, "image URLs must resolve only to public internet addresses"); + first = literal; + } else |_| { + const name = net.HostName.init(std.mem.trimEnd(u8, u.host, ".")) catch return fail(f, unresolved); + var results: [32]net.HostName.LookupResult = undefined; + var q: Io.Queue(net.HostName.LookupResult) = .init(&results); + name.lookup(io, &q, .{ .port = 443 }) catch return fail(f, unresolved); + while (q.getOneUncancelable(io)) |r| switch (r) { + .address => |addr| { + if (!publicIp(addr)) return fail(f, "image URLs must resolve only to public internet addresses"); + if (first == null) first = addr; + }, + .canonical_name => {}, + } else |_| {} + } + const addr = first orelse return fail(f, unresolved); + { + bundle_lock.lockUncancelable(io); + defer bundle_lock.unlock(io); + if (!bundle_loaded) { + bundle.rescan(std.heap.page_allocator, io, Io.Clock.real.now(io)) catch return fail(f, "image download failed: no CA certificates on the server"); + bundle_loaded = true; + } + } + const stream = try connect(addr, try remaining(io, deadline, f), f); + defer stream.close(io); + const tls_len = std.crypto.tls.Client.min_buffer_len; + const bufs = try a.alloc(u8, 4 * tls_len); + var sr = stream.reader(io, bufs[0..tls_len]); + var sw = stream.writer(io, bufs[tls_len .. 2 * tls_len]); + var entropy: [std.crypto.tls.Client.Options.entropy_len]u8 = undefined; + io.random(&entropy); + var tls = std.crypto.tls.Client.init(&sr.interface, &sw.interface, .{ + .host = .{ .explicit = std.mem.trimEnd(u8, u.host, ".") }, + .ca = .{ .bundle = .{ .gpa = std.heap.page_allocator, .io = io, .lock = &bundle_lock, .bundle = &bundle } }, + .read_buffer = bufs[2 * tls_len .. 3 * tls_len], + .write_buffer = bufs[3 * tls_len ..], + .entropy = &entropy, + .realtime_now = Io.Clock.real.now(io), + .allow_truncation_attacks = true, // HTTP's own length and chunk framing end the body + }) catch return fail(f, "image download failed or timed out"); // images_http.py: an ssl.SSLError is an OSError + const accept = try std.mem.join(a, ", ", media_types); + ask(&tls.writer, u, accept) catch return fail(f, "image download failed or timed out"); + sw.interface.flush() catch return fail(f, "image download failed or timed out"); + return answer(a, io, &tls.reader, max_bytes, deadline, media_types, f); + } +}; + +test "public addresses as Python's ipaddress checks them" { + const ip4 = struct { + fn of(b: [4]u8) net.IpAddress { + return .{ .ip4 = .{ .bytes = b, .port = 443 } }; + } + }.of; + const ip6 = struct { + fn of(text: []const u8) net.IpAddress { + return net.IpAddress.parseIp6(text, 443) catch unreachable; + } + }.of; + for ([_][4]u8{ .{ 8, 8, 8, 8 }, .{ 151, 101, 1, 69 }, .{ 1, 1, 1, 1 } }) |b| try std.testing.expect(publicIp(ip4(b))); + for ([_][4]u8{ .{ 10, 1, 2, 3 }, .{ 127, 0, 0, 1 }, .{ 169, 254, 169, 254 }, .{ 172, 20, 0, 1 }, .{ 192, 168, 1, 1 }, .{ 100, 100, 0, 1 }, .{ 0, 0, 0, 0 }, .{ 224, 0, 0, 1 }, .{ 255, 255, 255, 255 }, .{ 168, 63, 129, 16 }, .{ 192, 0, 0, 9 }, .{ 198, 18, 0, 1 }, .{ 203, 0, 113, 5 } }) |b| + try std.testing.expect(!publicIp(ip4(b))); + try std.testing.expect(publicIp(ip6("2606:4700::1111"))); + for ([_][]const u8{ "::1", "::", "fe80::1", "fc00::1", "ff02::1", "::ffff:8.8.8.8", "2002:808:808::1", "2001::1", "2001:db8::1", "64:ff9b::808:808" }) |t| + try std.testing.expect(!publicIp(ip6(t))); +} + +test "URLs as images_http._url takes them" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f: Failure = .{}; + const ok = try parseUrl(a, "https://Example.COM:443/img/c.png?x=%20&y=\xc3\xa4?z", &f); + try std.testing.expectEqualStrings("example.com", ok.host); + try std.testing.expectEqualStrings("/img/c.png?x=%20&y=%C3%A4?z", ok.target); + try std.testing.expectEqualStrings("/", (try parseUrl(a, "https://example.com", &f)).target); + try std.testing.expectEqualStrings("/", (try parseUrl(a, "https://example.com?", &f)).target); + try std.testing.expectEqualStrings("/a??", (try parseUrl(a, "https://example.com/a??", &f)).target); + try std.testing.expectEqualStrings("/%5Ba%5D%22%3C", (try parseUrl(a, "https://example.com/[a]\"<", &f)).target); + const cases = [_]struct { []const u8, []const u8 }{ + .{ "https://example.com/a b.png", "image URL is too long or contains whitespace/control characters" }, + .{ "http://example.com/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://user:pw@example.com/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://example.com:8443/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://example.com/x#frag", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://example.com\\@evil/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https:///x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://[::1]/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://localhost/x", "image URLs must use public internet hosts" }, + .{ "https://LOCALHOST./x", "image URLs must use public internet hosts" }, + .{ "https://metadata.google.internal/x", "image URLs must use public internet hosts" }, + }; + for (cases) |c| { + try std.testing.expectError(error.Media, parseUrl(a, c[0], &f)); + try std.testing.expectEqualStrings(c[1], f.text); + } + const long = try a.alloc(u8, max_url_chars + 1); + @memcpy(long[0.."https://e.com/".len], "https://e.com/"); + @memset(long["https://e.com/".len..], 'a'); + try std.testing.expectError(error.Media, parseUrl(a, long, &f)); + try std.testing.expectEqualStrings("https://e.com/b/c.png", try join(a, "https://e.com/b/a.png?q", "c.png")); + try std.testing.expectEqualStrings("https://e.com/z", try join(a, "https://e.com/b/a.png", "/z")); + try std.testing.expectEqualStrings("https://cdn.e.com/z", try join(a, "https://e.com/b/a.png", "//cdn.e.com/z")); + try std.testing.expectEqualStrings("http://e.com/z", try join(a, "https://e.com/b", "http://e.com/z")); +} + +/// Canned responses by host and path, for the HTTP rules without a network. +const Fixtures = struct { + pages: []const struct { []const u8, []const u8 }, + asked: *std.ArrayList(u8), + + fn request(self: Fixtures, a: std.mem.Allocator, io: Io, u: Url, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Got { + var w: Io.Writer.Allocating = .init(a); + ask(&w.writer, u, try std.mem.join(a, ", ", media_types)) catch return error.OutOfMemory; + try self.asked.appendSlice(a, w.written()); + const key = try std.fmt.allocPrint(a, "{s}{s}", .{ u.host, u.target }); + for (self.pages) |p| if (std.mem.eql(u8, p[0], key)) { + var r: Io.Reader = .fixed(p[1]); + return answer(a, io, &r, max_bytes, deadline, media_types, f); + }; + return fail(f, "image host could not be resolved"); + } +}; + +test "responses as images_http._request reads them: redirects, types, lengths, encodings" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const io = std.testing.io; + var asked: std.ArrayList(u8) = .empty; + const png = "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: 5\r\n\r\n\x89PNG!"; + const fx: Fixtures = .{ .asked = &asked, .pages = &.{ + .{ "e.com/a.png", png }, + .{ "e.com/chunked", "HTTP/1.1 200 OK\r\ncontent-type: Image/JPEG; q=1\r\nTransfer-Encoding: chunked\r\n\r\n3;x\r\n\xff\xd8\xff\r\n2\r\nab\r\n0\r\n\r\n" }, + .{ "e.com/eof", "HTTP/1.0 200 OK\r\nContent-Type: image/jpeg\r\n\r\n\xff\xd8\xffxyz" }, + .{ "e.com/r1", "HTTP/1.1 302 Found\r\nLocation: /r2\r\n\r\n" }, + .{ "e.com/r2", "HTTP/1.1 301 Moved\r\nLocation: https://cdn.e.com/b/x\r\n\r\n" }, + .{ "cdn.e.com/b/x", "HTTP/1.1 307 Temporary\r\nLocation: y.png\r\n\r\n" }, + .{ "cdn.e.com/b/y.png", png }, + .{ "e.com/loop", "HTTP/1.1 302 Found\r\nLocation: /loop\r\n\r\n" }, + .{ "e.com/plain", "HTTP/1.1 302 Found\r\nLocation: http://e.com/a.png\r\n\r\n" }, + .{ "e.com/inner", "HTTP/1.1 302 Found\r\nLocation: https://localhost/a.png\r\n\r\n" }, + .{ "e.com/nowhere", "HTTP/1.1 302 Found\r\n\r\n" }, + .{ "e.com/404", "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n" }, + .{ "e.com/gz", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Encoding: gzip\r\nContent-Length: 1\r\n\r\nx" }, + .{ "e.com/html", "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 1\r\n\r\nx" }, + .{ "e.com/big", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: 11\r\n\r\n01234567890" }, + .{ "e.com/bigchunk", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nTransfer-Encoding: chunked\r\n\r\n6\r\n012345\r\n6\r\n678901\r\n0\r\n\r\n" }, + .{ "e.com/bigeof", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\n\r\n01234567890" }, + .{ "e.com/badlen", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: +5\r\n\r\n12345" }, + .{ "e.com/short", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: 9\r\n\r\n12345" }, + .{ "e.com/junk", "SSH-2.0-OpenSSH\r\n\r\n" }, + } }; + const far = Io.Clock.awake.now(io).addDuration(.fromSeconds(60)); + var f: Failure = .{}; + const one = try fetchVia(a, io, "https://e.com/a.png", 10, far, &image_media, &f, fx); + try std.testing.expectEqualStrings("\x89PNG!", one.data); + try std.testing.expectEqualStrings("image/png", one.media); + try std.testing.expectEqualStrings("GET /a.png HTTP/1.1\r\nHost: e.com\r\nAccept: image/jpeg, image/png, image/webp\r\nAccept-Encoding: identity\r\nUser-Agent: TensorFold-native\r\nConnection: close\r\n\r\n", asked.items); + const ch = try fetchVia(a, io, "https://e.com/chunked", 10, far, &image_media, &f, fx); + try std.testing.expectEqualStrings("\xff\xd8\xffab", ch.data); + try std.testing.expectEqualStrings("image/jpeg", ch.media); + try std.testing.expectEqualStrings("\xff\xd8\xffxyz", (try fetchVia(a, io, "https://e.com/eof", 10, far, &image_media, &f, fx)).data); + // three redirects, each joined and checked again, reach the image; a fourth is refused + asked.clearRetainingCapacity(); + try std.testing.expectEqualStrings("\x89PNG!", (try fetchVia(a, io, "https://e.com/r1", 10, far, &image_media, &f, fx)).data); + try std.testing.expectEqual(@as(usize, 4), std.mem.count(u8, asked.items, "GET ")); + try std.testing.expect(std.mem.indexOf(u8, asked.items, "GET /b/y.png HTTP/1.1\r\nHost: cdn.e.com\r\n") != null); + const refusals = [_]struct { []const u8, []const u8 }{ + .{ "https://e.com/loop", "image download has too many redirects" }, + .{ "https://e.com/plain", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://e.com/inner", "image URLs must use public internet hosts" }, + .{ "https://e.com/nowhere", "image redirect has no destination" }, + .{ "https://e.com/404", "image download returned HTTP 404" }, + .{ "https://e.com/gz", "compressed HTTP image responses are unsupported" }, + .{ "https://e.com/html", "image URL content type must be JPEG, PNG or WebP" }, + .{ "https://e.com/big", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/bigchunk", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/bigeof", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/badlen", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/short", "image download failed or timed out" }, + .{ "https://e.com/junk", "image download failed or timed out" }, + }; + for (refusals) |c| { + try std.testing.expectError(error.Media, fetchVia(a, io, c[0], 10, far, &image_media, &f, fx)); + try std.testing.expectEqualStrings(c[1], f.text); + } + // a deadline already passed refuses before the body + try std.testing.expectError(error.Media, fetchVia(a, io, "https://e.com/a.png", 10, Io.Clock.awake.now(io), &image_media, &f, fx)); + try std.testing.expectEqualStrings("image download timed out", f.text); +} diff --git a/zig/src/server/messages.zig b/zig/src/server/messages.zig index 9559ed784b..21806820bb 100644 --- a/zig/src/server/messages.zig +++ b/zig/src/server/messages.zig @@ -23,6 +23,35 @@ fn withField(cx: *Cx, o: *const json.Object, key: []const u8, value: Value) !*js /// ``normalize_messages`` (text only): leading system and developer text merged, later ones as ``late_system``; a template that needs a user query gains one user turn after a trailing tool run. pub fn normalize(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_after_tool: bool) errors.Refused!Value { + return normalizeWith(cx, messages, late_system, needs_user_after_tool, false); +} + +/// One image part as the template and the image path read it: {"type": "image_url", "image_url": {"url", "detail"?}}. +fn imagePart(cx: *Cx, part: Value) errors.Refused!Value { + const iu = part.get("image_url") orelse return cx.refuse("an image_url content part must contain image_url"); + var url: []const u8 = ""; + var detail: ?Value = null; + if (iu == .string) url = iu.string else if (iu == .object) { + const u = iu.get("url") orelse return cx.refuse("image_url must contain a url string"); + if (u != .string) return cx.refuse("image_url must contain a url string"); + url = u.string; + detail = iu.get("detail"); + if (detail) |d| if (d != .string or !(std.mem.eql(u8, d.string, "auto") or std.mem.eql(u8, d.string, "low") or std.mem.eql(u8, d.string, "high"))) + return cx.refuse("image_url detail must be auto, low or high"); + } else return cx.refuse("image_url must be a url string or an object with one"); + if (url.len == 0) return cx.refuse("image_url must contain a url string"); + for ([_][]const u8{ "audio", "input_audio", "video", "video_url" }) |k| if (json.truthyField(part, k)) return cx.refuse("image_url parts cannot contain other media"); + const inner = try json.newObject(cx.a); + try inner.put(cx.a, "url", .{ .string = url }); + if (detail) |d| try inner.put(cx.a, "detail", d); + const out = try json.newObject(cx.a); + try out.put(cx.a, "type", .{ .string = "image_url" }); + try out.put(cx.a, "image_url", .{ .object = inner }); + return .{ .object = out }; +} + +/// `normalize`, and with `images` a user or tool message's image_url parts kept in order beside its text parts. +pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_after_tool: bool, images: bool) errors.Refused!Value { const list = messages orelse return cx.refuse("messages must be a non-empty list"); if (list != .array or list.array.len == 0) return cx.refuse("messages must be a non-empty list"); var out: std.ArrayList(Value) = .empty; @@ -36,14 +65,29 @@ pub fn normalize(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_ var item: *json.Object = message.object; if (content != null and content.? == .array) { var text: std.ArrayList(u8) = .empty; + var parts: std.ArrayList(Value) = .empty; // with images: text and image parts in order + var has_image = false; for (content.?.array) |part| { - const typed = part == .object and part.get("type") != null and part.get("type").? == .string and std.mem.eql(u8, part.get("type").?.string, "text"); - if (!typed or fields.hasMedia(part)) return cx.refuse("this server accepts text parts only; image, audio and video inputs are unsupported"); + const kind = if (part == .object and part.get("type") != null and part.get("type").? == .string) part.get("type").?.string else ""; + if (images and std.mem.eql(u8, kind, "image_url")) { + // tool results carry screenshots too; the template renders them in its response + if (!std.mem.eql(u8, role.?.string, "user") and !std.mem.eql(u8, role.?.string, "tool")) return cx.refuse("image parts are accepted in user and tool messages only"); + try parts.append(cx.a, try imagePart(cx, part)); + has_image = true; + continue; + } + if (!std.mem.eql(u8, kind, "text") or fields.hasMedia(part)) return cx.refuse(if (images) "content parts must be text or image_url; audio and video inputs are unsupported" else "this server accepts text parts only; image, audio and video inputs are unsupported"); const t = part.get("text") orelse return cx.refuse("a text content part must contain a text string"); if (t != .string) return cx.refuse("a text content part must contain a text string"); try text.appendSlice(cx.a, t.string); + if (images) { + const tp = try json.newObject(cx.a); + try tp.put(cx.a, "type", .{ .string = "text" }); + try tp.put(cx.a, "text", t); + try parts.append(cx.a, .{ .object = tp }); + } } - item = try withField(cx, message.object, "content", .{ .string = text.items }); + item = try withField(cx, message.object, "content", if (has_image) Value{ .array = parts.items } else Value{ .string = text.items }); } else if (content == null or content.? == .null) { item = try withField(cx, message.object, "content", .{ .string = "" }); } else if (content.? != .string) { diff --git a/zig/src/server/model_text.zig b/zig/src/server/model_text.zig index 0b36055a7f..b036ca8342 100644 --- a/zig/src/server/model_text.zig +++ b/zig/src/server/model_text.zig @@ -36,6 +36,8 @@ pub const Text = struct { template_source: *const fn (ctx: *anyopaque) []const u8, /// Whether an id is a special token (an added token flagged special); null: none are known. special: ?*const fn (ctx: *anyopaque, id: u32) bool = null, + /// Ids of ``text`` with no added token matched (a spelled special token is plain text); null: ``encode``. + encode_plain: ?*const fn (ctx: *anyopaque, a: Allocator, text: []const u8) Error![]u32 = null, /// A token's own bytes (a partial UTF-8 sequence kept whole) for logprob rows; null: the tokenizer can't say. token_bytes: ?*const fn (ctx: *anyopaque, a: Allocator, id: u32) Allocator.Error!?[]u8 = null, }; @@ -44,6 +46,11 @@ pub const Text = struct { return t.vtable.encode(t.ctx, a, text, add_special); } + pub fn encodePlain(t: Text, a: Allocator, text: []const u8) Error![]u32 { + const f = t.vtable.encode_plain orelse return t.encode(a, text, false); + return f(t.ctx, a, text); + } + pub fn decode(t: Text, a: Allocator, ids: []const u32) Allocator.Error![]u8 { return t.vtable.decode(t.ctx, a, ids); } diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index b8782aaf96..4dc08b095e 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -127,10 +127,10 @@ fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value) errors.Refused!Plan { if (srv.config.request_log) |path| request_log.append(cx.a, path, body); var input: chat.Input = .{ .fields = undefined }; if (is_chat) { - input.messages = try messages.normalize(cx, body.get("messages"), "system", srv.needs_user_after_tool); + input.messages = try messages.normalizeWith(cx, body.get("messages"), "system", srv.needs_user_after_tool, srv.info.vision != null); input.tools = try tool_specs.active(cx, body.get("tools"), body.get("tool_choice")); } else if (body.get("messages")) |m| if (m == .array and m.array.len > 0) { - input.messages = try messages.normalize(cx, m, "system", srv.needs_user_after_tool); + input.messages = try messages.normalizeWith(cx, m, "system", srv.needs_user_after_tool, srv.info.vision != null); }; if (!is_chat and input.messages.array.len == 0) input.prompt = try legacyPrompt(srv, cx, body.get("prompt")); // ``body.get("max_tokens") or body.get("max_completion_tokens")``: both are ints or None by now diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index e68363bfe7..220013501f 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -1,15 +1,18 @@ //! Prompt ids from a request, as ``prepare_prompt`` and ``render_prompt_ids`` make them. const std = @import("std"); +const api = @import("engine_api"); const json = @import("json.zig"); const errors = @import("errors.zig"); const messages_mod = @import("messages.zig"); const model_text = @import("model_text.zig"); const chat = @import("chat.zig"); +const images = @import("images.zig"); const Server = @import("server.zig").Server; const Value = json.Value; const Cx = errors.Cx; -pub const Rendered = struct { ids: []const u32, history_len: usize = 0, rewind_len: usize = 0 }; +/// With image input, `ids` holds each image's tokens, `images` the images and `cache_key` the prompt the cache matches. +pub const Rendered = struct { ids: []const u32, history_len: usize = 0, rewind_len: usize = 0, images: []const api.Image = &.{}, cache_key: []const u32 = &.{} }; /// Where lessons decide to act on a reply: the row before the generation prompt's ``, else before its last. pub fn decideOf(srv: *const Server, ids: []const u32) u32 { @@ -27,7 +30,7 @@ pub const isTitle = messages_mod.isTitleRequest; /// ``render_prompt_ids``: messages normalized for this template, rendered, and a dangling ```` closed. pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, thinking: bool, effort: ?[]const u8, generation: bool) errors.Refused![]const u32 { - const normalized = try messages_mod.toolArguments(cx, try messages_mod.normalize(cx, messages, srv.late_system, srv.needs_user_after_tool)); + const normalized = try messages_mod.toolArguments(cx, try messages_mod.normalizeWith(cx, messages, srv.late_system, srv.needs_user_after_tool, srv.info.vision != null)); var problem: []const u8 = ""; const options: model_text.RenderOptions = .{ .tools = if (tools.len > 0) Value{ .array = @constCast(tools) } else null, @@ -35,7 +38,7 @@ pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, t .enable_thinking = thinking, .reasoning_effort = if (thinking) effort else null, }; - var ids = srv.text.renderIds(cx.a, normalized, options, &problem) catch |e| switch (e) { + var ids = render(srv, cx.a, normalized, options, &problem) catch |e| switch (e) { error.OutOfMemory => return error.OutOfMemory, error.Template => return cx.fail(.server, "{s}", .{problem}), }; @@ -52,6 +55,14 @@ pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, t return ids; } +/// The template's ids for `messages`; with image input, a marker the text spells is ordinary text (images.zig). +fn render(srv: *Server, a: std.mem.Allocator, messages: Value, options: model_text.RenderOptions, problem: *[]const u8) model_text.Error![]u32 { + const v = srv.info.vision orelse return srv.text.renderIds(a, messages, options, problem); + const markers = try images.markerText(srv.text, a, v); + const text = try srv.text.render(a, try images.shield(a, messages, markers), options, problem); + return images.encodeShielded(srv.text, a, text, markers); +} + /// The template's generation prompt (thinking on or off): what a probe conversation renders past its history. fn generationPrompt(srv: *Server, cx: *Cx, thinking: bool) errors.Refused![]const u32 { const user = try json.newObject(cx.a); @@ -101,6 +112,8 @@ pub fn prepare(srv: *Server, cx: *Cx, input: chat.Input, thinking: bool, effort: var history_len: usize = 0; if (history.len > 0 and history.len < prompt.len and std.mem.eql(u32, prompt[0..history.len], history)) history_len = history.len; if (history_len == 0 and prompt.len > 1 and std.mem.eql(u32, history, prompt)) history_len = prompt.len - 1; // a template with no generation suffix + // --vision: placeholders expanded to image tokens before the window, chunks and cache see it; no rewind kept + if (try images.expand(srv.info.vision, if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, cx, input.messages, prompt, history_len)) |x| return .{ .ids = x.ids, .history_len = x.history_len, .images = x.images, .cache_key = x.cache_key }; const count = if (input.messages == .array) input.messages.array.len else 0; const rewind_len = if (srv.info.prompt_cache) rewindLen(srv, cx, input.messages, count, input.tools, prompt, thinking, effort) else 0; // one more render return .{ .ids = prompt, .history_len = history_len, .rewind_len = rewind_len }; diff --git a/zig/src/server/reply_text.zig b/zig/src/server/reply_text.zig index 648a1d8cd2..991ae959ce 100644 --- a/zig/src/server/reply_text.zig +++ b/zig/src/server/reply_text.zig @@ -292,6 +292,35 @@ pub const Stops = struct { } }; +/// The text a stream has sent: Python's ``streamed = visible``, grown by its delta while it only grows. +pub const Shown = struct { + text: std.ArrayList(u8) = .empty, + chars: usize = 0, + at: ?[*]const u8 = null, // where the last shown text lay; the decode buffer only grows, so that prefix holds + extends: bool = false, + + /// Python's ``now[len(shown):]``; ``stable``: ``now`` lies in the append-only decode buffer. + pub fn after(s: *Shown, now: []const u8, stable: bool) []const u8 { + const sent = s.text.items; + s.extends = (stable and s.at == now.ptr and now.len >= sent.len) or std.mem.startsWith(u8, now, sent); + if (!s.extends) return afterChars(now, s.chars); + if (stable) s.at = now.ptr; // the buffer moved but kept its bytes: the next check is free again + return now[sent.len..]; + } + + pub fn set(s: *Shown, a: Allocator, now: []const u8, delta: []const u8) Allocator.Error!void { + if (s.extends) { + try s.text.appendSlice(a, delta); + s.chars += charCount(delta); + } else { + s.text = .empty; + try s.text.appendSlice(a, now); + s.chars = charCount(now); + } + s.at = now.ptr; + } +}; + /// Decodes only new tokens with the previous chunk as context, so characters split across tokens stay whole. pub const Incremental = struct { tokens: std.ArrayList(u32) = .empty, diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 7630f5217a..61044adf53 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -39,6 +39,8 @@ test { _ = @import("process_memory.zig"); _ = @import("log.zig"); _ = @import("messages.zig"); + _ = @import("images.zig"); + _ = @import("media_fetch.zig"); _ = @import("stream_preflight_test.zig"); _ = @import("stream_dsml_test.zig"); _ = @import("logprobs_test.zig"); diff --git a/zig/src/server/serve.zig b/zig/src/server/serve.zig index da27cb6b0e..7cd93678ad 100644 --- a/zig/src/server/serve.zig +++ b/zig/src/server/serve.zig @@ -116,6 +116,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { .keep_warm_s = args.keep_warm, .default_sampling = s.sampling, .use_drafts = !args.no_drafts, + .vision_urls = args.vision_urls, .seed_salt = salt, .request_log = env(s, "TENSORFOLD_REQUEST_LOG"), .dashboard = args.dashboard, diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 011734ee9a..6fe0ffdcd3 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -46,6 +46,8 @@ pub const Config = struct { /// Sampling when a request names none (generation_config.json and the serve flags), or null for greedy. default_sampling: ?Value = null, use_drafts: bool = true, + /// --vision-urls: image parts may name public HTTPS URLs, fetched before admission (media_fetch.zig). + vision_urls: bool = false, seed_salt: i64 = 0, /// TENSORFOLD_REQUEST_LOG: where chat and completion bodies are appended; null: nowhere. request_log: ?[]const u8 = null, diff --git a/zig/tests/cuda/qwen27/capture.py b/zig/tests/cuda/qwen27/capture.py new file mode 100644 index 0000000000..a21dd828eb --- /dev/null +++ b/zig/tests/cuda/qwen27/capture.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""The 27B's Python CUDA engine as the Zig engine's oracle: Triton launches, per-layer dumps, tokens.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +from pathlib import Path + +TEXTS = { + "story": "Write a short story about a lighthouse keeper who finds a message in a bottle.", + "code": "Write a Python function that merges two sorted lists, with a docstring and three tests.", + "facts": "Explain how a refrigerator moves heat out of its cabinet, step by step.", +} +LONG_BODY = 5000 # tokens of module source in the long prompt: two 4096-row prompt chunks +TEACHER = 32 # teacher-forced decode steps (one row each, from an empty state) +DUMP_STEPS = (0, 1, TEACHER - 1) + + +def chat(user: str) -> str: + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def prompts(model: Path) -> dict[str, list[int]]: + from tokenizers import Tokenizer + import textwrap + + tok = Tokenizer.from_file(str(model / "tokenizer.json")) + out = {name: tok.encode(chat(text), add_special_tokens=False).ids for name, text in TEXTS.items()} + words = Path(textwrap.__file__).read_text() + body = tok.encode(words * (1 + LONG_BODY // max(1, len(words) // 3)), add_special_tokens=False).ids[:LONG_BODY] + head = tok.encode("<|im_start|>user\nReview this module and list its public functions:\n\n", + add_special_tokens=False).ids + tail = tok.encode("<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", add_special_tokens=False).ids + out["long"] = head + body + tail + return out + + +def sha12(tokens: list[int]) -> str: + return hashlib.sha256(json.dumps([int(t) for t in tokens]).encode()).hexdigest()[:12] + + +def digest(t) -> str: + import torch + + raw = t.detach().contiguous() + return hashlib.sha256(raw.view(torch.uint8).cpu().numpy().tobytes()).hexdigest() + + +class Dumps: + """Raw little-endian tensors by name under the current directory; None turns dumping off.""" + + def __init__(self) -> None: + self.dir: Path | None = None + self.i = 0 + + def at(self, d: Path | None) -> None: + self.dir, self.i = d, 0 + if d is not None: + d.mkdir(parents=True, exist_ok=True) + + def save(self, name: str, t) -> None: + import torch + + if self.dir is None: + return + torch.cuda.synchronize() + t.detach().contiguous().view(torch.uint8).cpu().numpy().tofile(self.dir / f"{name}.bin") + + +def hook(dumps: Dumps) -> None: + """Every add_rmsnorm call's (h, y, xs), in call order: two a layer, then the final norm.""" + + from tensorfold.families.qwen3_5.cuda import glue + + norm = glue.add_rmsnorm + + def traced(x, r, w, eps): + h, y, xs = norm(x, r, w, eps) + if dumps.dir is not None: + i = dumps.i + dumps.i += 1 + dumps.save(f"{i:03d}_h", h) + dumps.save(f"{i:03d}_y", y) + dumps.save(f"{i:03d}_xs", xs) + return h, y, xs + + glue.add_rmsnorm = traced + + +def specialization() -> dict: + """Each launched JIT function's parameter names and which ones Triton never specializes.""" + + from triton.runtime.jit import JITFunction + import gc + + out = {} + for fn in gc.get_objects(): + if isinstance(fn, JITFunction): + name = f"{fn.fn.__module__}.{fn.fn.__qualname__}" + out[name] = {"params": [p.name for p in fn.params], + "do_not_specialize": [p.name for p in fn.params if p.do_not_specialize], + "no_align": [p.name for p in fn.params if p.do_not_specialize_on_alignment]} + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="", help="folder of triton_aot_manifest.py: record every Triton launch") + ap.add_argument("--max-tokens", type=int, default=128) + ap.add_argument("--repeats", type=int, default=2) + ap.add_argument("--context", type=int, default=16384) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + + import torch + from contextlib import nullcontext + + def phase(name: str, detail: bool = False): + return rec.scope(name, detail) if rec is not None else nullcontext() + + model = Path(a.model) + ids = prompts(model) + (out / "prompts.json").write_text(json.dumps(ids) + "\n") + dumps = Dumps() + hook(dumps) + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + + t0 = time.perf_counter() + with phase("startup"): + eng = Qwen27Engine(model, None, streams=1, context=a.context, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + info = {"startup_s": round(time.perf_counter() - t0, 2), "context": eng.context_window, "eos": list(eng.eos), + "prompt_rows": eng.w.prompt_rows, "torch": torch.__version__, "gpu": torch.cuda.get_device_name(0)} + print(json.dumps(info), flush=True) + + results: dict[str, dict] = {} + for name, prompt in ids.items(): + runs = [] + for _ in range(a.repeats): + toks: list[int] = [] + with phase(f"serial-{name}"): + torch.cuda.synchronize() + start = time.perf_counter() + stats = eng.generate(prompt, a.max_tokens, None, lambda new: toks.extend(map(int, new)) and False, + draft=False, stop_eos=True) + torch.cuda.synchronize() + wall = time.perf_counter() - start + runs.append({"tokens": toks, "sha": sha12(toks), "wall_s": round(wall, 4), **stats}) + last = runs[-1] + same = all(r["tokens"] == last["tokens"] for r in runs) + step = last.get("decode_s", 0.0) / max(1, len(last["tokens"]) - 1) * 1e3 + results[name] = {**last, "repeats_same": same, "ms_per_token": round(step, 4)} + print(f"serial {name}: {len(last['tokens'])} tokens sha {last['sha']} prefill {last.get('prefill_s'):.3f}s " + f"{step:.3f} ms/token same {same}", flush=True) + + from tensorfold.families.qwen3_5.cuda.decode import prefill + from tensorfold.families.qwen3_5.cuda.forward import State, commit, tree_forward + + w = eng.w + tf = ids["code"][:TEACHER] + sampled, logit_sha = [], [] + st = State(w) + with phase("teacher", detail=True): + for i, t in enumerate(tf): + dumps.at(out / "teacher" / f"step{i:03d}" if i in DUMP_STEPS else None) + logits, record = tree_forward(w, torch.tensor([t], dtype=torch.int32, device="cuda"), [-1], st) + dumps.save("logits", logits) + sampled.append(int(logits.argmax(dim=-1)[0])) + logit_sha.append(digest(logits)) + commit(st, record, [0]) + dumps.at(None) + pre_out = {} + for name in ("code", "long"): + dumps.at(out / "prefill" / name if name == "code" else None) + with phase(f"prefill-{name}", detail=name == "code"): + _, pending = prefill(w, ids[name], None, limit=a.context) + dumps.at(None) + pre_out[name] = {"pending": pending} + (out / "teacher.json").write_text(json.dumps({"tokens": tf, "sampled": sampled, "logits_sha256": logit_sha, + "dump_steps": list(DUMP_STEPS), "prefill": pre_out}) + "\n") + (out / "results.json").write_text(json.dumps({"info": info, "results": results}, indent=1) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + (out / "jit.json").write_text(json.dumps(specialization(), indent=1, sort_keys=True) + "\n") + print("done", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/tests/cuda/qwen27/capture_draft.py b/zig/tests/cuda/qwen27/capture_draft.py new file mode 100644 index 0000000000..b5aa457ebc --- /dev/null +++ b/zig/tests/cuda/qwen27/capture_draft.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""The 27B's DFlash2 drafting as the Zig engine's oracle: drafted replies (equal to serial), rounds, Triton launches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +from pathlib import Path + + +def sha12(tokens: list[int]) -> str: + return hashlib.sha256(json.dumps([int(t) for t in tokens]).encode()).hexdigest()[:12] + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--draft", required=True) + ap.add_argument("--prompts", required=True, help="capture.py's prompts.json") + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="") + ap.add_argument("--max-tokens", type=int, default=128) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + import torch + + from tensorfold.families.qwen3_5.cuda.decode import draft_decode, prefill + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + + eng = Qwen27Engine(Path(a.model), Path(a.draft), streams=1, context=16384, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + prompts = json.loads(Path(a.prompts).read_text()) + results = {} + for name, ids in prompts.items(): + for _ in range(2): # the second run is the timed one + drafter = eng.draft + drafter.restore(([None] * drafter.layers, [None] * drafter.layers, 0, 0)) + torch.cuda.synchronize() + t0 = time.perf_counter() + st, pending = prefill(eng.w, ids, None, drafter, limit=16384) + trace: list = [] + r = draft_decode(eng.w, st, ids, pending, a.max_tokens, None, drafter, max_rows=eng.max_rows, + tree_rows=eng.tree_rows, allow_copy=True, stop_eos=True, trace=trace, inplace=True) + torch.cuda.synchronize() + wall = time.perf_counter() - t0 + results[name] = {"tokens": r.tokens, "sha": sha12(r.tokens), "rounds": r.rounds, "drafted": r.drafted_rows, + "accepted": r.accepted_drafts, "decode_s": round(r.seconds, 4), "wall_s": round(wall, 4), + "widths": r.widths, "paths": [len(t.get("path", [])) for t in trace]} + print(f"{name}: {len(r.tokens)} tokens sha {sha12(r.tokens)} rounds {r.rounds} accepted {r.accepted_drafts} " + f"{len(r.tokens) / r.seconds:.1f} tok/s", flush=True) + (out / "draft.json").write_text(json.dumps({"max_rows": eng.max_rows, "results": results}) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + print("done", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/tests/cuda/qwen27/capture_multi.py b/zig/tests/cuda/qwen27/capture_multi.py new file mode 100644 index 0000000000..6d18232073 --- /dev/null +++ b/zig/tests/cuda/qwen27/capture_multi.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""The 27B's drafted shared rounds as the Zig engine's oracle: MultiDecoder's windows each round, and every reply.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from pathlib import Path + +TOPICS = ["lighthouses", "volcanoes", "bread", "rivers", "chess", "glaciers", "owls", "trains"] +CODE = '''def fibonacci(n): + """Return the nth Fibonacci number.""" + if n < 2: + return n + a, b = 0, 1 + for _ in range(n - 1): + a, b = b, a + b + return b +''' + + +def chat(user: str) -> str: + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def sha12(tokens: list[int]) -> str: + return hashlib.sha256(json.dumps([int(t) for t in tokens]).encode()).hexdigest()[:12] + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--draft", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="") + ap.add_argument("--streams", type=int, default=6) + ap.add_argument("--max-tokens", type=int, default=96) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + from tokenizers import Tokenizer + + from tensorfold.cuda.streams import Stream + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + from tensorfold.families.qwen3_5.cuda.multi import MultiDecoder + + model = Path(a.model) + tok = Tokenizer.from_file(str(model / "tokenizer.json")) + users = [f"Rewrite this function with a docstring that explains each step, keeping the code the same:\n\n{CODE}"] + users += [f"Write four sentences about {t}." for t in TOPICS] + prompts = [tok.encode(chat(u), add_special_tokens=False).ids for u in users[:a.streams]] + eng = Qwen27Engine(model, Path(a.draft), streams=1, context=8192, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + # GB10's planning: no measured costs (every tree node verified), the drafter's block 16 rows a stream + md = MultiDecoder(eng.w, eng.draft, allow_copy=True, context=8192, keep=1) + md.depth = False + rounds: list[list[dict]] = [] + windows = md._windows + + def logged(plan, copied, blocks): + wins = windows(plan, copied, blocks) + rounds.append([{"stream": sid, "mode": ["copy", "tree", "one"][mode], "tokens": t, "parents": p} + for (sid, mode, _, _), (t, p) in zip(plan, wins)]) + return wins + + md._windows = logged + scores: list[list[float]] = [] # each tree's path scores, in finish order + finish = md.draft.finish_tree + + def scored(*args, **kw): + t = finish(*args, **kw) + scores.append([float(x) for x in t[2]]) + return t + + md.draft.finish_tree = scored + streams = [Stream(list(p), a.max_tokens, None, draft=True, stop_eos=True) for p in prompts] + for s in streams: + md.admit(s) + while any(not s.done for s in streams): + md.finish(md.round()) + results = [{"tokens": s.out, "sha": sha12(s.out), "rounds": s.rounds, "drafted": s.drafted, + "accepted": s.accepted} for s in streams] + for k, r in enumerate(results): + print(f"stream {k}: {len(r['tokens'])} tokens sha {r['sha']} rounds {r['rounds']} accepted {r['accepted']}", + flush=True) + (out / "multi.json").write_text(json.dumps({"prompts": prompts, "max_tokens": a.max_tokens, "results": results, + "rounds": rounds, "scores": scores}) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + print(f"{len(rounds)} rounds", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/tests/cuda/qwen27/capture_windows.py b/zig/tests/cuda/qwen27/capture_windows.py new file mode 100644 index 0000000000..78b7558951 --- /dev/null +++ b/zig/tests/cuda/qwen27/capture_windows.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""The 27B's verify windows as the Zig engine's oracle: chains of 1-16 rows and shared forwards, each row hashed.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from pathlib import Path + +TOPICS = ["lighthouses", "volcanoes", "bread", "rivers", "chess", "glaciers", "owls", "trains", + "deserts", "bees", "clocks", "ferns", "kites", "salt", "comets", "violins"] +REPLY = 24 # serial tokens each stream decodes first: the chain windows' tokens + + +def chat(user: str) -> str: + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def sha(t) -> str: + import torch + + return hashlib.sha256(t.detach().contiguous().view(torch.uint8).cpu().numpy().tobytes()).hexdigest() + + +def rows(logits) -> list[dict]: + return [{"sha": sha(logits[r]), "argmax": int(logits[r].argmax())} for r in range(logits.shape[0])] + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="") + ap.add_argument("--wide", action="store_true", help="also rounds past 16 rows") + ap.add_argument("--sweep", action="store_true", help="also every alignment of a shared round's packed inputs") + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + import torch + from tokenizers import Tokenizer + + from tensorfold.families.qwen3_5.cuda.decode import clone_state, prefill, serial_decode + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + from tensorfold.families.qwen3_5.cuda.forward import commit_streams, multi_tree_forward, tree_forward + + model = Path(a.model) + tok = Tokenizer.from_file(str(model / "tokenizer.json")) + prompts = [tok.encode(chat(f"Write four sentences about {t}."), add_special_tokens=False).ids for t in TOPICS] + eng = Qwen27Engine(model, None, streams=1, context=4096, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + w = eng.w + states, replies = [], [] + for p in prompts: + st, pending = prefill(w, p, None, limit=4096) + states.append(st) + replies.append(serial_decode(w, st, pending, REPLY, None, stop_eos=False).tokens) + dev = w.norm.device + cases = [] + + def tokens(ids): + return torch.tensor(ids, dtype=torch.int32, device=dev) + + # chains of one stream: the serial reply's first W tokens, each row's draw the next serial token + for width in range(1, 17): + st = clone_state(states[0]) + logits, _ = tree_forward(w, tokens(replies[0][:width]), list(range(-1, width - 1)), st) + cases.append({"kind": "chain", "streams": [{"stream": 0, "tokens": replies[0][:width]}], "rows": rows(logits)}) + # shared forwards: each stream its own chain from its own state, rows in stream order + layouts = [[1, 1], [1] * 4, [1] * 8, [1] * 16, [4, 4, 4, 4], [2, 5, 1, 8], [3] * 5, [16]] + if a.wide: # rounds past 16 rows: the wider matmul tiles (to 32, 64, more) + layouts += [[16, 16], [5, 16, 3], [16] * 4, [9, 16, 2, 16, 7, 16, 1, 5], [12] * 8, [16] * 16] + if a.sweep: # the packed copy's pointer alignments: rows and streams mod 4, 16-row multiples + for n in range(2, 6): + for total in (16 * n, 16 * n - 12, 16 * n - 11, 16 * n - 10, 16 * n - 9): + layouts.append([total // n + (i < total % n) for i in range(n)]) + for layout in layouts: + sts = [clone_state(states[s]) for s in range(len(layout))] + wins = [(replies[s][:n], list(range(-1, n - 1)), sts[s]) for s, n in enumerate(layout)] + logits, record, _, starts = multi_tree_forward(w, wins) + case = {"kind": "shared", "streams": [{"stream": s, "tokens": replies[s][:n]} for s, n in enumerate(layout)], + "rows": rows(logits)} + # each stream keeps a prefix of its rows (as multi._commit names them: window rows), then one more row each + keep = [list(range(max(1, n - 1))) for n in layout] + commit_streams(sts, record, [[starts[s] + r for r in k] for s, k in enumerate(keep)]) + nxt = [([replies[s][len(k)]], [-1], sts[s]) for s, k in enumerate(keep)] + after, _, _, _ = multi_tree_forward(w, nxt) + case["keep"] = [len(k) for k in keep] + case["after"] = rows(after) + cases.append(case) + # trees: each stream's serial reply as the main chain, with other tokens hung beside it + def tree(stream: int, shape: str): + r = replies[stream] + alt = lambda t: (t + 7919) % w.config.vocab # noqa: E731 + if shape == "fork": # 0 r0; 1 r1 (0); 2 alt (0); 3 r2 (1); 4 alt (1); 5 r3 (3); 6 alt (2) + return [r[0], r[1], alt(r[1]), r[2], alt(r[2]), r[3], alt(r[3])], [-1, 0, 0, 1, 1, 3, 2] + if shape == "fan": # the root's six children (r1 first), then r2 under r1 + return [r[0], r[1]] + [alt(r[1] + j) for j in range(5)] + [r[2]], [-1, 0, 0, 0, 0, 0, 0, 1] + raise ValueError(shape) + + tree_cases = [([(0, "fork")], [[0, 1, 3, 5]]), ([(1, "fan")], [[0, 1, 7]]), + ([(2, "fork"), (3, "fork")], [[0, 1, 3, 5], [0, 2, 6]])] + if a.wide: # every stream a tree in one round, 120 rows + tree_cases.append(([(s, "fork" if s % 2 else "fan") for s in range(16)], + [[0, 1, 3, 5] if s % 2 else [0, 1, 7] for s in range(16)])) + for spec, paths in tree_cases: + sts = [clone_state(states[s]) for s, _ in spec] + wins = [(*tree(s, shape), st) for (s, shape), st in zip(spec, sts)] + if len(spec) == 1: + logits, record = tree_forward(w, tokens(wins[0][0]), wins[0][1], sts[0]) + starts = [0, len(wins[0][0])] + else: + logits, record, _, starts = multi_tree_forward(w, [(t, p, st) for t, p, st in wins]) + case = {"kind": "tree", "streams": [{"stream": s, "tokens": t, "parents": p} for (s, _), (t, p, _) in + zip(spec, wins)], "rows": rows(logits), "paths": paths} + nxt = [int(logits[starts[k] + path[-1]].argmax()) for k, path in enumerate(paths)] + commit_streams(sts, record, [[starts[k] + r for r in path] for k, path in enumerate(paths)]) + after, _, _, _ = multi_tree_forward(w, [([t], [-1], st) for t, st in zip(nxt, sts)]) + case["next"] = nxt + case["after"] = rows(after) + cases.append(case) + torch.cuda.synchronize() + (out / "windows.json").write_text(json.dumps({"prompts": prompts, "replies": replies, "cases": cases}) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + print(f"{len(cases)} cases", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/tests/glm_vision.zig b/zig/tests/glm_vision.zig new file mode 100644 index 0000000000..7df41b512c --- /dev/null +++ b/zig/tests/glm_vision.zig @@ -0,0 +1,148 @@ +//! GLM-5.3-Flash's image tower against a reference dump (tools/zig/glm_vision_fixtures.py: mlx-vlm's tower). +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const vision = tf.glm.vision; + +const usage = + \\tf-glm-vision MODEL_DIR REF_DIR [STAGE] [IMAGE] + \\REF_DIR holds meta.json (grid_thw), patches.f32 and the stage's reference: embed.f32 (STAGE embed, after the patch + \\projection), block0.f32 (STAGE block0, after the first block), blocks.f32 (STAGE blocks, after the last) or + \\features.f32 (STAGE features, the default: the tower's output rows). Writes native_STAGE.f32 there and prints the + \\largest and mean absolute differences, the reference's mean magnitude and the rows' cosine similarity. + \\IMAGE: prepare the patches from this file natively (decode, resize, pad, normalize), compare them with + \\patches.f32 value by value, and run the tower on them instead (meta.json's max_tokens is the budget). +; + +fn readFile(a: std.mem.Allocator, dir: []const u8, name: []const u8) ![]u8 { + const path = try std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ dir, name }, 0); + const f = try mtl.MappedFile.open(path); + defer f.deinit(); + return a.dupe(u8, f.bytes[0..f.size]); +} + +fn bf16ToF32(x: u16) f32 { + return @bitCast(@as(u32, x) << 16); +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const args = try init.minimal.args.toSlice(a); + if (args.len < 3) { + std.debug.print("{s}\n", .{usage}); + return error.Usage; + } + const dir = args[1]; + const ref = args[2]; + const stage = if (args.len > 3) args[3] else "features"; + const stop: ?u32 = if (std.mem.eql(u8, stage, "embed")) 0 else if (std.mem.eql(u8, stage, "block0")) 1 else if (std.mem.eql(u8, stage, "blocks")) vision.depth else if (std.mem.eql(u8, stage, "features")) null else return error.Usage; + + const meta = try std.json.parseFromSliceLeaky(std.json.Value, a, try readFile(a, ref, "meta.json"), .{}); + const grid = meta.object.get("grid_thw").?.array.items; + const gh: u32 = @intCast(grid[1].integer); + const gw: u32 = @intCast(grid[2].integer); + const raw = try readFile(a, ref, "patches.f32"); + var pixels = try a.alloc(f32, raw.len / 4); + @memcpy(std.mem.sliceAsBytes(pixels), raw[0 .. pixels.len * 4]); + const P = gh * gw; + const T = P / vision.patches_per_token; + + const device = try mtl.Device.init(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const queue = try device.queue(); + const cfg_text = try readFile(a, dir, "config.json"); + const proc_text = readFile(a, dir, "processor_config.json") catch null; + const c = (try vision.Config.parse(a, cfg_text, proc_text)) orelse return error.NoVisionConfig; + if (args.len > 4) { + const img_path = try std.fmt.allocPrintSentinel(a, "{s}", .{args[4]}, 0); + const f = try mtl.MappedFile.open(img_path); + defer f.deinit(); + const max_tokens: u32 = @intCast(meta.object.get("max_tokens").?.integer); + const t0i = std.Io.Clock.awake.now(init.io).toNanoseconds(); + const prep = try tf.glm.image.prepare(a, f.bytes[0..f.size], c, max_tokens); + const t1i = std.Io.Clock.awake.now(init.io).toNanoseconds(); + std.debug.print("prepared {s}: grid {d}x{d}, {d} tokens in {d:.1} ms\n", .{ args[4], prep.gh, prep.gw, prep.tokens, @as(f64, @floatFromInt(t1i - t0i)) / 1e6 }); + if (prep.gh != gh or prep.gw != gw) { + std.debug.print("grid differs from the reference's {d}x{d}\n", .{ gh, gw }); + return error.GridMismatch; + } + var differ: usize = 0; + var max_p: f32 = 0; + for (prep.pixels, pixels) |x, y| { + if (x != y) differ += 1; + max_p = @max(max_p, @abs(x - y)); + } + std.debug.print("patches: {d} of {d} values differ from the reference (largest {d:.6})\n", .{ differ, pixels.len, max_p }); + pixels = prep.pixels; + } + var t0 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + const v = try vision.Vision.load(std.heap.page_allocator, device, dir, c, @max(T, 1024)); + defer v.deinit(); + var t1 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + std.debug.print("tower loaded in {d:.2} s ({d:.2} GiB with scratch for {d} patches, attention chunks of {d} rows)\n", .{ @as(f64, @floatFromInt(t1 - t0)) / 1e9, @as(f64, @floatFromInt(v.bytes)) / (1 << 30), v.max_patches, v.chunk }); + const out_buf = try device.buffer(@as(usize, T) * vision.out_hidden * 2, mtl.ResourceOptions.shared); + defer out_buf.deinit(); + + for (0..2) |run| { // the second run is the timed one (the first compiles pipelines' state on the GPU) + const cb = queue.commandBuffer(); + const enc = cb.compute(.serial); + t0 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + try v.encode(enc, pixels, gh, gw, .{ .buf = out_buf }, stop); + enc.end(); + cb.commit(); + cb.wait(); + t1 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + if (cb.failure()) |msg| { + std.debug.print("command buffer failed: {s}\n", .{msg}); + return error.GpuFailed; + } + if (run == 1) std.debug.print("encode: {d} patches -> {d} tokens in {d:.1} ms\n", .{ P, T, @as(f64, @floatFromInt(t1 - t0)) / 1e6 }); + } + // the stage's rows: the residual stream for a stop, else the output rows + const width: usize = if (stop != null) vision.hidden else vision.out_hidden; + const rows: usize = if (stop != null) P else T; + const src: [*]const u16 = if (stop != null) @ptrCast(@alignCast(v.x.addr())) else @ptrCast(@alignCast(out_buf.contents())); + const got = try a.alloc(f32, rows * width); + for (got, 0..) |*g, i| g.* = bf16ToF32(src[i]); + const name = try std.fmt.allocPrint(a, "native_{s}.f32", .{stage}); + { + const path = try std.fmt.allocPrint(a, "{s}/{s}", .{ ref, name }); + const f = try std.Io.Dir.cwd().createFile(init.io, path, .{}); + defer f.close(init.io); + try f.writeStreamingAll(init.io, std.mem.sliceAsBytes(got)); + } + const want_raw = try readFile(a, ref, try std.fmt.allocPrint(a, "{s}.f32", .{stage})); + const want = try a.alloc(f32, want_raw.len / 4); + @memcpy(std.mem.sliceAsBytes(want), want_raw[0 .. want.len * 4]); + if (want.len != got.len) { + std.debug.print("size: native {d} values, reference {d}\n", .{ got.len, want.len }); + return error.SizeMismatch; + } + var max_d: f64 = 0; + var sum_d: f64 = 0; + var sum_m: f64 = 0; + var worst_cos: f64 = 1; + var mean_cos: f64 = 0; + for (0..rows) |r| { + var dot: f64 = 0; + var ng: f64 = 0; + var nw: f64 = 0; + for (0..width) |j| { + const g: f64 = got[r * width + j]; + const w: f64 = want[r * width + j]; + const d = @abs(g - w); + max_d = @max(max_d, d); + sum_d += d; + sum_m += @abs(w); + dot += g * w; + ng += g * g; + nw += w * w; + } + const cs = dot / (@sqrt(ng * nw) + 1e-30); + worst_cos = @min(worst_cos, cs); + mean_cos += cs; + } + const n: f64 = @floatFromInt(got.len); + std.debug.print("{s}: max |d| {d:.4}, mean |d| {d:.5}, mean |ref| {d:.4}, cosine mean {d:.6} worst {d:.6} ({d} rows of {d})\n", .{ stage, max_d, sum_d / n, sum_m / n, mean_cos / @as(f64, @floatFromInt(rows)), worst_cos, rows, width }); +} diff --git a/zig/vendor/stb/COMMIT b/zig/vendor/stb/COMMIT new file mode 100644 index 0000000000..7b40c30ab3 --- /dev/null +++ b/zig/vendor/stb/COMMIT @@ -0,0 +1 @@ +2c980bb59875b0d32144a71867fbdebb2f77cd20 diff --git a/zig/vendor/stb/stb_image.c b/zig/vendor/stb/stb_image.c new file mode 100644 index 0000000000..488630f836 --- /dev/null +++ b/zig/vendor/stb/stb_image.c @@ -0,0 +1,9 @@ +// stb_image (v2.30, public domain or MIT; the commit in COMMIT): PNG and JPEG from memory, for the Linux image path. +#define STB_IMAGE_IMPLEMENTATION +#define STBI_ONLY_PNG +#define STBI_ONLY_JPEG +#define STBI_NO_STDIO +#define STBI_NO_LINEAR +#define STBI_NO_HDR +#define STBI_MAX_DIMENSIONS 8192 +#include "stb_image.h" diff --git a/zig/vendor/stb/stb_image.h b/zig/vendor/stb/stb_image.h new file mode 100644 index 0000000000..9eedabedc4 --- /dev/null +++ b/zig/vendor/stb/stb_image.h @@ -0,0 +1,7988 @@ +/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.30 (2024-05-31) avoid erroneous gcc warning + 2.29 (2023-05-xx) optimizations + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE + + Jacko Dirks + + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data); +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// on most compilers (and ALL modern mainstream compilers) this is threadsafe +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif + + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + int ch; + fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user) || ferror((FILE *) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pnm_is16(stbi__context *s); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two ints fits in a signed short, 0 on overflow. +static int stbi__mul2shorts_valid(int a, int b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) + return 0; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context *s, int n) +{ + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) { + for (j=0; j < count[i]; ++j) { + h->size[k++] = (stbi_uc) (i+1); + if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); + } + } + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if(c < 0 || c >= 256) // symbol id out of bounds! + return -1; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & (sgn - 1)); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; + + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * (1 << j->succ_low)); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * (1 << shift)); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i=0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + stbi_uc x = stbi__get8(j->s); + while (x == 0xff) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + j->marker = stbi__skip_jpeg_junk_at_end(j); + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); + } else { + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); + } + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + int hit_zeof_once; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + return stbi__zeof(z) ? 0 : *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + if (!a->hit_zeof_once) { + // This is the first time we hit eof, insert 16 extra padding btis + // to allow us to keep going; if we actually consume any of them + // though, that is invalid data. This is caught later. + a->hit_zeof_once = 1; + a->num_bits += 16; // add 16 implicit zero bits + } else { + // We already inserted our extra 16 padding bits and are again + // out, this stream is actually prematurely terminated. + return -1; + } + } else { + stbi__fill_bits(a); + } + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + if (a->hit_zeof_once && a->num_bits < 16) { + // The first time we hit zeof, we inserted 16 extra zero bits into our bit + // buffer so the decoder can just do its speculative decoding. But if we + // actually consumed any of those bits (which is the case when num_bits < 16), + // the stream actually read past the end so it is malformed. + return stbi__err("unexpected end","Corrupt PNG"); + } + return 1; + } + if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (len > a->zout_end - zout) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + a->hit_zeof_once = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filter used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub +}; + +static int stbi__paeth(int a, int b, int c) +{ + // This formulation looks very different from the reference in the PNG spec, but is + // actually equivalent and has favorable data dependencies and admits straightforward + // generation of branch-free code, which helps performance significantly. + int thresh = c*3 - (a + b); + int lo = a < b ? a : b; + int hi = a < b ? b : a; + int t0 = (hi <= thresh) ? lo : c; + int t1 = (thresh <= lo) ? hi : t0; + return t1; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// adds an extra all-255 alpha channel +// dest == src is legal +// img_n must be 1 or 3 +static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n) +{ + int i; + // must process data backwards since we allow dest==src + if (img_n == 1) { + for (i=x-1; i >= 0; --i) { + dest[i*2+1] = 255; + dest[i*2+0] = src[i]; + } + } else { + STBI_ASSERT(img_n == 3); + for (i=x-1; i >= 0; --i) { + dest[i*4+3] = 255; + dest[i*4+2] = src[i*3+2]; + dest[i*4+1] = src[i*3+1]; + dest[i*4+0] = src[i*3+0]; + } + } +} + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16 ? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + stbi_uc *filter_buf; + int all_ok = 1; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + // note: error exits here don't need to clean up a->out individually, + // stbi__do_png always does on error. + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG"); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + // Allocate two scan lines worth of filter workspace buffer. + filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0); + if (!filter_buf) return stbi__err("outofmem", "Out of memory"); + + // Filtering for low-bit-depth images + if (depth < 8) { + filter_bytes = 1; + width = img_width_bytes; + } + + for (j=0; j < y; ++j) { + // cur/prior filter buffers alternate + stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes; + stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes; + stbi_uc *dest = a->out + stride*j; + int nk = width * filter_bytes; + int filter = *raw++; + + // check filter type + if (filter > 4) { + all_ok = stbi__err("invalid filter","Corrupt PNG"); + break; + } + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // perform actual filtering + switch (filter) { + case STBI__F_none: + memcpy(cur, raw, nk); + break; + case STBI__F_sub: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); + break; + case STBI__F_up: + for (k = 0; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); + break; + case STBI__F_avg: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); + break; + case STBI__F_paeth: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes])); + break; + case STBI__F_avg_first: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); + break; + } + + raw += nk; + + // expand decoded bits in cur to dest, also adding an extra alpha channel if desired + if (depth < 8) { + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + stbi_uc *in = cur; + stbi_uc *out = dest; + stbi_uc inb = 0; + stbi__uint32 nsmp = x*img_n; + + // expand bits to bytes first + if (depth == 4) { + for (i=0; i < nsmp; ++i) { + if ((i & 1) == 0) inb = *in++; + *out++ = scale * (inb >> 4); + inb <<= 4; + } + } else if (depth == 2) { + for (i=0; i < nsmp; ++i) { + if ((i & 3) == 0) inb = *in++; + *out++ = scale * (inb >> 6); + inb <<= 2; + } + } else { + STBI_ASSERT(depth == 1); + for (i=0; i < nsmp; ++i) { + if ((i & 7) == 0) inb = *in++; + *out++ = scale * (inb >> 7); + inb <<= 1; + } + } + + // insert alpha=255 values if desired + if (img_n != out_n) + stbi__create_png_alpha_expand8(dest, dest, x, img_n); + } else if (depth == 8) { + if (img_n == out_n) + memcpy(dest, cur, x*img_n); + else + stbi__create_png_alpha_expand8(dest, cur, x, img_n); + } else if (depth == 16) { + // convert the image data from big-endian to platform-native + stbi__uint16 *dest16 = (stbi__uint16*)dest; + stbi__uint32 nsmp = x*img_n; + + if (img_n == out_n) { + for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) + *dest16 = (cur[0] << 8) | cur[1]; + } else { + STBI_ASSERT(img_n+1 == out_n); + if (img_n == 1) { + for (i = 0; i < x; ++i, dest16 += 2, cur += 2) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = 0xffff; + } + } else { + STBI_ASSERT(img_n == 3); + for (i = 0; i < x; ++i, dest16 += 4, cur += 6) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = (cur[2] << 8) | cur[3]; + dest16[2] = (cur[4] << 8) | cur[5]; + dest16[3] = 0xffff; + } + } + } + } + } + + STBI_FREE(filter_buf); + if (!all_ok) return 0; + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_global = flag_true_if_should_convert; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + } + // even with SCAN_header, have to scan to see if we have a tRNS + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning + tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n && k < 3; ++k) + tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + stbi__bmp_set_mask_defaults(info, compress); + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind( s ); + return 0; + } + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); + if (ri->bits_per_channel == 0) + return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } + + if (req_comp && req_comp != s->img_n) { + if (ri->bits_per_channel == 16) { + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + if((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + if(*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; + else + return 8; +} + +static int stbi__pnm_is16(stbi__context *s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; + #endif + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/