Skip to content

dots: serve dots.mocr's images on CUDA with --vision - #2771

Merged
ashhart merged 15 commits into
ashhart:mainfrom
laudney:pr-dots-e
Nov 19, 2026
Merged

ashhart merged 15 commits into
ashhart:mainfrom
laudney:pr-dots-e

Conversation

@laudney

@laudney laudney commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor
Before (#2673) After
dots.mocr images on native CUDA refused by name (--vision) served on a GB10 with --vision: the tower, its 2×2 merger, image rows spliced into prompt chunks
Our own two pages in one prompt (4,186 prompt ids) — 1,323 native reply ids, every one exact under HF's teacher-forced logits (0 one step, 0 fail)
The model card's demo page (5,096 prompt ids, 4,634 reply ids) — every native id exact under HF's teacher-forced logits
Drafted = --no-drafts, concurrent = solo (8 lanes), repeat, seeded, cancel mid-image, chunk cuts through images — equal byte for byte
tf-cuda-test dots-text (3 prompts of our own, up to 64 greedy ids each) — PASS: each reply's sha256 equals its pin
dots.mocr text replies; Qwen3.8-27B MLX on CUDA — unchanged

What this changes

#2673 serves dots.mocr's text decoder on the shared CUDA dense engine and refuses images. With this piece the recipe declares the tower (pieces b to d), so --vision serves images.

  • zig/src/families/dots_mocr/cuda_recipe.zig: pub const Tower. The engine's tower variant then gives the host dots.mocr's vision limits, marks, words and bytes (the tower's weight and open bytes join the vision bytes).
  • The tower counts its encodes, and the dots module exports its config, for the GB10 runner.
  • Runner (zig/tests/cuda/dots_tests.zig):
    • dots-invariants MODEL IMAGE [N] [IDS]: serves the engine with --vision and runs a small image, the full image (the oracle's prompt ids when given) and two images, each under cuts that the run proves landed off the 1,024-row grid, against the uncut run. The KV rows, the last-row logits, the greedy ids and one encode an image must all be equal.
    • dots-text MODEL: three chat-templated prompts of our own (18, 578 and 2,537 ids, fixtures/own-prompts.json) each generate up to 64 greedy ids through the served engine; the sha256 of each reply's ids (u32, little-endian) must equal its pin. A decoder drift fails without the Python oracle.
  • Host tests pin the recipe's tower, the vision declarations and bytes, the engine's words for the tower's refusals, and the own-prompts fixture (lengths, vocabulary range, turn marks).

Serving the publisher's original BF16 weights is what makes these results comparable with other engines and lets every reply be checked against the model card's own Transformers model.

  • Model licence: dots-studio/dots.mocr is published under the dots.mocr License Agreement (Xingyin Information Technology (Shanghai) Co., Ltd., on MIT terms; the model card reads license: mit). TensorFold redistributes no weights; serving reads the publisher's files.
  • Issue: Refs Native OCR models on HIP: dots.mocr, GLM-OCR, LightOnOCR-3 and Nemotron Parse, CUDA to follow (tracker) #1927 (item 11). Remaining after this stack: Nemotron Parse and GLM-OCR on this engine.
  • Stacked on: dots: the image tower on CUDA, with its GB10 runner checks #2770 (piece 4, da27cc0fe). This PR's commits: ad77d3d59 feat(dots): serve dots.mocr's image tower with --vision; e903ef5d1 test(dots): pin dots.mocr's greedy text replies on the GB10; f8edb0c02 test(cuda): dots-text pins its replies without --vision too; 731f8a72e docs(dots): say how own-prompts.json was made. Piece 5 of 7.
  • Conflicts: a local test merge of the stack's top cd1cb0baa into main 6b739dd5e is clean (git merge-tree).

Checks on this head

  • Head commit: 731f8a72e
  • Review fixes (Ash's 21:08 points) are new commits on this piece, listed above. On this head (Linux x86_64): zig build test-cuda-host, check-native-cuda-host 7/7, test-kernel-contract, zig fmt --check and git diff --check pass; lean 386 / 386, 0 new against piece d. On the GB10 at the stack's head cd1cb0baa: dots-image and dots-text (with --vision and text only) equal their pins; the projection check passes 24 of 24 and fails a planted value two BF16 steps off. The checks below ran on the earlier heads, whose code equals this head's but for these fixes.
  • Lean checker, python3 tools/zig/lean_check.py, on the base (cuda: a shared engine for dense decoders, with dots.mocr's text decoder on it #2673's head 05e5e5fdd) and on this head: 386 / 386, 0 new (also 0 new against piece d).
  • Tests run (Linux x86_64, no GPU):
    • zig build test-cuda-host: 378/378 steps, 0 failed (the test binaries this piece changes re-ran; the others are the parent's and passed there).
    • zig build test-cuda-dense-host: 33/33 passed, uncached. zig build test-dots-mocr-cuda-host: 24/24 passed, uncached.
    • zig build check-native-cuda-host: 7/7 steps. zig build test-kernel-contract: 32/32 steps, 0 failed. zig build compile-cuda-tests (the GB10 runner compiles): 10/10 steps.
    • zig fmt --check build.zig zig, git diff --check: pass.
  • CI: pending on this head.
  • zig build test test-golden (Linux x86_64) on the stack's top 6bb38b3a1: 662/665 steps, 8,692/8,760 tests passed, 67 skipped; the one failure is cuda_disk_test, whose write deadline fails on the base too under load.
  • Not run, and why: the GB10 device checks are in the receipt, not in this host list.

Receipt

  • Environment: the stack's head on cuda: a shared engine for dense decoders, with dots.mocr's text decoder on it #2673 05e5e5fdd, whose tree equals these heads except one moved comment; NVIDIA GB10 (sm_121), nvcc 13.4, Zig 0.17.0, 128 GB unified memory. Checkpoint dots-studio/dots.mocr@e539fbb52280393adc081b289ec597430a0f9031. HF: the pinned oracle on the same GB10, Torch 2.14.1+cu130, Transformers 4.57.6, Pillow 12.2.0, qwen-vl-utils 0.0.10, the tower on SDPA.
  • Paths and platforms: --vision on the dense engine, drafted and --no-drafts, 1 to 8 lanes; the text path with and without --vision. GB10 (sm_121) only; not run: sm_80, sm_86, sm_89 and sm_120 devices.

Gate 1: HF agreement with images (greedy)

Prompt Prompt ids Reply ids Against HF's teacher-forced logits
our own two pages in one prompt, the receipt then the invoice: receipt.png (eb0216df…, grid 92×52) and invoice.png (64e479ee…, grid 126×88) 4,186 = 4,186 native 1,323 1,323 exact, 0 one step, 0 fail. HF's own 1,259 greedy ids, scored the same way: 1,256 exact, 2 one step, 1 fail
the model card's demo page (the publisher's own example image) 5,096 = 5,096 4,634 = 4,634 4,634 exact, 0 one step, 0 fail

The two pages are ours: a deterministic Pillow script draws them with text we wrote, Pillow's bundled default font and a fixed seed (2732), and saves them as PNG. The receipt is 720×1280 (a shop name, eight item lines with prices, the subtotal, the tax and the total); the invoice is 1240×1754 (a header block, a five-row table of hours, rates and amounts, the subtotal, VAT and the total due).

The page generator (make_pages.py)
"""Two deterministic test pages for the dots.mocr gates: a receipt and an invoice, text and layout ours, PNG out."""
import hashlib
import random
import sys
from pathlib import Path

import PIL
from PIL import Image, ImageDraw, ImageFont, features

SEED = 2732
INK, PAPER = (24, 24, 24), (250, 249, 245)


def font(size):
    """Pillow's bundled default font at `size` (FreeType); the same Pillow gives the same glyphs."""
    if not features.check("freetype2"):
        raise SystemExit("this Pillow has no FreeType: the default font cannot be sized")
    return ImageFont.load_default(size=size)


def receipt(rng):
    items = [("Oat milk 1L", 2), ("Rye bread", 1), ("Green apples", 6), ("Coffee beans 500g", 1),
             ("Dish soap", 1), ("Basmati rice 2kg", 1), ("Tomatoes", 4), ("Notebook A5", 3)]
    page = Image.new("RGB", (720, 1280), PAPER)
    d = ImageDraw.Draw(page)
    big, body = font(40), font(26)
    d.text((360, 60), "NORTHFIELD GROCERY", font=big, fill=INK, anchor="mm")
    d.text((360, 110), "14 Harbour Lane, Unit 3", font=body, fill=INK, anchor="mm")
    d.text((360, 145), "Receipt 000417   2026-11-10 09:42", font=body, fill=INK, anchor="mm")
    d.line((40, 185, 680, 185), fill=INK, width=2)
    y, total = 215, 0
    for name, qty in items:
        cents = rng.randrange(89, 1899)
        total += qty * cents
        d.text((50, y), f"{qty} x {name}", font=body, fill=INK)
        d.text((670, y), f"{qty * cents / 100:.2f}", font=body, fill=INK, anchor="ra")
        y += 48
    d.line((40, y + 10, 680, y + 10), fill=INK, width=2)
    tax = round(total * 0.08)
    for label, cents in [("Subtotal", total), ("Tax 8%", tax), ("TOTAL", total + tax)]:
        y += 52
        d.text((50, y), label, font=big if label == "TOTAL" else body, fill=INK)
        d.text((670, y), f"{cents / 100:.2f}", font=big if label == "TOTAL" else body, fill=INK, anchor="ra")
    d.text((360, y + 120), "Paid by card ending 0042", font=body, fill=INK, anchor="mm")
    d.text((360, y + 160), "Thank you for shopping with us", font=body, fill=INK, anchor="mm")
    return page


def invoice(rng):
    rows = [("Kernel review, attention path", 6), ("Fixture recording, GB10", 3), ("Tower stage comparison", 4),
            ("Documentation pass", 2), ("Release checks", 5)]
    page = Image.new("RGB", (1240, 1754), PAPER)
    d = ImageDraw.Draw(page)
    big, body, small = font(56), font(30), font(24)
    d.text((80, 80), "INVOICE", font=big, fill=INK)
    d.text((80, 170), "Larkspur Engineering Ltd", font=body, fill=INK)
    d.text((80, 210), "7 Quarry Road, Westbrook", font=small, fill=INK)
    for i, (k, v) in enumerate([("Invoice no.", "INV-2026-0731"), ("Date", "10 November 2026"), ("Due", "10 December 2026")]):
        d.text((760, 90 + 44 * i), k, font=small, fill=INK)
        d.text((1160, 90 + 44 * i), v, font=small, fill=INK, anchor="ra")
    d.text((80, 300), "Bill to: Meridian Documents Co., 22 Elm Street", font=body, fill=INK)
    top = 400
    d.rectangle((80, top, 1160, top + 60), outline=INK, width=2)
    for x, head in [(100, "Description"), (720, "Hours"), (860, "Rate"), (1140, "Amount")]:
        d.text((x, top + 14), head, font=body, fill=INK, anchor="ra" if x == 1140 else "la")
    y, total = top + 80, 0
    for text, hours in rows:
        rate = rng.choice([85, 95, 110, 120])
        total += hours * rate
        d.text((100, y), text, font=small, fill=INK)
        d.text((720, y), str(hours), font=small, fill=INK)
        d.text((860, y), f"{rate:.2f}", font=small, fill=INK)
        d.text((1140, y), f"{hours * rate:,.2f}", font=small, fill=INK, anchor="ra")
        d.line((80, y + 46, 1160, y + 46), fill=(170, 170, 170), width=1)
        y += 64
    vat = total * 0.2
    for label, value in [("Subtotal", total), ("VAT 20%", vat), ("Total due", total + vat)]:
        y += 56
        d.text((860, y), label, font=body, fill=INK)
        d.text((1140, y), f"{value:,.2f}", font=body, fill=INK, anchor="ra")
    d.text((80, y + 140), "Payment by bank transfer within 30 days. Reference the invoice number.", font=small, fill=INK)
    return page


def main():
    out = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    out.mkdir(parents=True, exist_ok=True)
    rng = random.Random(SEED)
    for name, make in [("receipt.png", receipt), ("invoice.png", invoice)]:
        path = out / name
        make(rng).save(path, format="PNG", optimize=False, compress_level=9)
        print(f"{path} {hashlib.sha256(path.read_bytes()).hexdigest()} pillow {PIL.__version__}")


if __name__ == "__main__":
    main()

python3 -I make_pages.py OUT_DIR prints each page's path and sha256. Pillow changes the glyphs between versions, so the hashes above are from Pillow 12.2.0, the oracle's pin.

Gate 2: invariants with images (reply-id sha256, 8 lanes)

Check Result
solo = repeat = 2 × concurrent (8 in flight), our two pages and the demo page equal in every case; the demo page 725385cf
drafted (--parallel 8) against --no-drafts the same hashes in every case
seeded (T 0.7, seed 11), both pages, twice 3fe6ad3b both times
a stream dropped mid-image, then the same request fresh 725385cf, as the uncut request
chunk cuts (dots-invariants): a small image cut at its first row, inside it, at its last row and at all three; the full image cut inside off the 1,024-row grid; two images with the grid line through the first and one more cut in each KV pages, last-row logits and 64 greedy ids equal the uncut runs; each image encoded once

Gate 3: text and served checkpoints unchanged

main × 2 this stack × 2
token sha / output sha (fibonacci, chat) 2b28aa21 aafe5ed4, a06fab34 d9498b28 identical in both runs
decode tok/s (fibonacci / chat) 14.90, 15.06 / 15.38, 15.40 15.07, 15.04 / 15.41, 15.39
prompt tok/s 2k / 8k / 32k / 64k 1357, 1355 / 1357, 1353 / 1243, 1243 / 1125, 1125 1353, 1354 / 1353, 1353 / 1243, 1243 / 1125, 1125
cold 32k TTFT 26.38 s, 26.33 s 26.36 s, 26.36 s

Gate 4: named refusals

Request Words
an image to a server without --vision this server accepts text parts only; image, audio and video inputs are unsupported
video content parts must be text or image_url; audio and video inputs are unsupported
bytes that are no image image 1 is not PNG, JPEG or WebP; send one of those
three demo pages in one request served: the 14,400-token budget is divided across the images, as on HIP
an image span the prompt does not hold, an image past the budget, a fixed lane count whose feature rows do not fit host tests (DenseImageSpan, DotsImageBudget naming --vision-image-tokens, the planner's per-lane bytes); on the GB10, --parallel 64 at a 131,072-token context fits
  • New switch: n/a; --vision and --vision-image-tokens are the host's existing flags.
  • Licence of new weights or drafter: n/a; the publisher's checkpoint is read as published (licence above).

Checklist

  • The title and description match the head commit, including the receipt and the stack.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.
  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.
  • Drafted output equals "draft": false, and concurrent equals solo. A resumed prompt equals a fresh one: n/a, the engine keeps no prompt states.
  • No precision traded for speed. If the bits change, the description says which sums change and why.
  • Decode and prompt processing are no slower than main at one stream and the widest admitted; with --drafter, no slower than without it, greedy and sampled: --drafter is refused for dots.mocr; Qwen3.8-27B above.

@ashhart

ashhart commented Nov 10, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney, this is a careful piece. The image limits hold end to end: the request's count and token budget, the engine's span re-check, image rows charged per lane, and the tower's bytes counted before load. Text-only requests skip the image path entirely. Two small things:

  • dots-text pins the replies only with --vision on. Since the description claims the text path with and without --vision, could the runner also run the three prompts without --vision against the same pins? Or say in the description which run shows "unchanged against cuda: a shared engine for dense decoders, with dots.mocr's text decoder on it #2673".

  • A short note on how own-prompts.json was made (the source text and the template used) would let someone else regenerate it.

  • Synthena (Ash's Agent)

@laudney

laudney commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, both are in:

@ashhart

ashhart commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney, both are in. Two optional thoughts, neither blocking:

  • On another GPU, dots-text could still require the --vision and text-only replies to match each other, since that holds on any device.
  • Committing ownprompts.py next to the fixture would keep its source in the tree.

Ready from our side.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 13, 2026

Copy link
Copy Markdown
Owner

@laudney main landed dots changes of its own under this stack (fix(dots): read with our own prompt and hash-only fixtures and the dots licence docs), so the series conflicted in zig/src/families/dots_mocr/fixtures/README.md and tools/zig/dots_mocr_reference.py and the landing train left it out. To save you a round trip we rebased the whole stack (#2770 → #2771 → #2772 → #2773) onto current main and pushed each PR to its branch: main's own prompt file, hash-only fixtures and licence names are kept, and your CUDA image tower, serving and checks are unchanged. The dots host steps pass on each PR of the stack, as do the serving-pin check and our privacy gate. They go back in the landing queue in order once CI is green. No other asks.

  • Synthena (Ash's Agent)

@ashhart ashhart mentioned this pull request Nov 13, 2026
4 tasks done
@ashhart

ashhart commented Nov 14, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney. The rebased serving increment keeps main's own-prompt and hash-only fixtures while declaring the tower through the shared dense engine. The chunk-cut check verifies the cuts were actually taken and compares KV rows, final logits, reply ids and one encode per image. The text runner covers startup with and without --vision. No new author changes requested; ready after #2770 once current-head CI is green.

  • Synthena (Ash's Agent)

@ashhart

ashhart commented Nov 19, 2026

Copy link
Copy Markdown
Owner

Thank you @laudney. The serving increment and checks are unchanged from the version we rebased, and there is no further change we need from you.

We will redo the rebase on current main and get CI green before landing this in order after #2770.

  • Synthena

@ashhart

ashhart commented Nov 19, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney. To get this moving, we rebased it onto current main ourselves, keeping every one of your commits as it was (author and message) and fitting it to the code main has gained since; no behaviour changes. It is in the landing queue now, and if anything else is needed from you we will say so here.

  • Synthena

@ashhart
ashhart force-pushed the pr-dots-e branch 2 times, most recently from c37e821 to c66215b Compare November 19, 2026 19:32
The tower's tensors load as plain BF16 [n, k] matrices for cuBLASLt:
fc1 and fc3 stacked into one gate|up projection, and the patch weight
flattened to 588 columns and zero-padded to 592 so its rows meet the
library's alignment. Every vision_tower tensor is consumed, the device
bytes count the padding, and a failed load drains its uploads before
any buffer is freed.
--
2.54.0 (Apple Git-157)
--
2.43.0
laudney and others added 14 commits November 19, 2026 21:36
The drain test called settle directly, so dropping the errdefer in
load, or registering it before the tower's own errdefer, would stay
green. A host test now runs load on a sparse checkpoint against a
fake device whose first upload's wait fails: the buffers must go only
after the context proved the copies done. The sparse checkpoint
helper moves to its own test file so the tower's tests can share it.
--
2.54.0 (Apple Git-157)
--
2.43.0
The dense engine's Tower contract gets its first real tower:
dots.mocr's 42-block image tower, which turns merge-ordered patches
into the decoder's rows at the rounding points of the HIP port and
of Transformers. The tower reuses the shared vit GEMMs, attention,
LayerNorm and linears, the engine's norms and SwiGLU, and the new
vision rotary and patch bias launches. It holds one call's scratch
at the processor's 57,600 patches and taps every stage for the
oracle's comparison. Host tests pin the contract, the exact weight,
scratch and open bytes against a sparse checkpoint, the rotary
inv_freq fixture, the refusals' words (the budget's naming
--vision-image-tokens, the flag the CLI accepts), the grid checks
and the patch rows; the recipe declares the tower in its own change.
The tower needs device checks that the host suite cannot run, so
tf-cuda-test gains two dots commands behind one dispatch line and a
dots-help that prints their usage. dots-stages encodes one image with
a tap that writes every stage's rows as BF16 .npy files for the
oracle's stages mode. dots-image encodes a generated page (the
processor fixture's pixel pattern, no file read) and an optional
image twice each, requires equal bytes, prints the merged rows' hash
and the time, and fails unless the page's hash equals its anchor, so
a tower drift fails without the Python oracle. The runner imports
the served dots module and its engine.
The vision-merged pin is a GB10 value, so another GPU's rows would
read as a tower drift. dots-image still encodes twice and requires
equal bytes everywhere, but on a device other than sm_121 it skips
the pin comparison and names that device's SM.
Two trailing comments ran past 120 columns (the dots runner import in
the CUDA build and a control line in the tower test); each now sits
above its line. The tower test also takes the sparse checkpoint dir
from the shared test helper instead of keeping its own copy.
The recipe now declares the tower, so the dense engine's tower
variant serves dots.mocr: --vision opens it, the host reads its
limits, marks and words, and its weight and open bytes join the
vision bytes. The tower counts its encodes, and the dots module
exports its config for the GB10 runner, whose new dots-invariants
serves the engine with --vision and runs a small image, the full
image (the oracle's prompt ids when given) and two images, each
under cuts that the run proves landed off the 1,024-row grid,
against the uncut run: the KV rows, the last-row logits, the greedy
ids and one encode an image must all be equal. Host tests pin the
recipe's tower, the vision decls and bytes, and the engine's words.
ashhart#2732's runner gains dots-text, so a decoder drift fails without the
Python oracle: three chat-templated prompts of our own (18, 578 and
2,537 ids, committed as fixtures/own-prompts.json) each generate up
to 64 greedy reply ids through the served dense engine (EOS can end
one sooner), and the sha256 of those ids as little-endian u32 must
equal its pinned constant. The constants wait for the GB10 run, so
the command prints each measured hash and fails until they are
filled in. A host test pins the fixture's prompt lengths, its
vocabulary range and its turn marks.
The description claims the text path with and without --vision, but
dots-text served the engine only with --vision. It now serves the
three own prompts twice, with --vision and without it, against the
same pins, and like dots-image it names another SM instead of
comparing GB10 pins there.
The fixture's ids could not be regenerated from the tree. The
fixtures README now names their source text, our own ownprompts.py,
and how each prompt became ids: one user turn rendered with the
checkpoint's chat template and tokenized by the pinned oracle.
@ashhart
ashhart merged commit 144964f into ashhart:main Nov 19, 2026
10 of 11 checks passed
@ashhart

ashhart commented Nov 19, 2026

Copy link
Copy Markdown
Owner

Thank you @laudney. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants