[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-109352":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":14,"stars7d":15,"stars30d":16,"stars90d":14,"forks30d":14,"starsTrendScore":14,"compositeScore":17,"rankGlobal":9,"rankLanguage":9,"license":18,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":21,"hasPages":19,"topics":22,"createdAt":9,"pushedAt":23,"updatedAt":24,"readmeContent":25,"aiSummary":26,"trendingCount":14,"starSnapshotCount":14,"syncStatus":27,"lastSyncTime":28,"discoverSource":29},109352,"KohakuGBC","KohakuBlueleaf\u002FKohakuGBC","KohakuBlueleaf","Graph-Based Captioning as one KIR program on the Togeari dataflow machine, with its engines",null,"Python",82,4,66,0,3,17,45.3,"Apache License 2.0",false,"main",true,[],"2026-11-07 18:12:51","2026-11-20 06:45:16","# KohakuGBC\n\n[![arXiv](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FarXiv-2407.06723-b31b1b.svg)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2407.06723)\n[![ml-gbc](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Foriginal-apple%2Fml--gbc-181717.svg?logo=github)](https:\u002F\u002Fgithub.com\u002Fapple\u002Fml-gbc)\n\n![One image's GBC graph: the image with the box of every entity, the graph of its vertices, and captions linked phrase to vertex](docs\u002Fassets\u002Fteaser.jpg)\n\nGraph-Based Captioning ([GBC](https:\u002F\u002Farxiv.org\u002Fabs\u002F2407.06723)) as one\n[KIR](https:\u002F\u002Fgithub.com\u002FKohakuBlueleaf\u002FKohakuNodeIR) program on the\n[Togeari](https:\u002F\u002Fgithub.com\u002FKohakuBlueleaf\u002FTogeari) dataflow machine, with the engines that run\nit: a VLM over any OpenAI-compatible or Anthropic API, vLLM in-process or a specialised Qwen3.5\nengine; OWLv2 or SAM 3 for detection; EmbeddingGemma for names; on one GPU, many GPUs or other\nnodes.\n\nProducing one GBC graph is a branching process: ask the VLM, detect what it named, describe each\nregion, detect its parts, merge regions that are the same object, ask relational questions. Its\ncontrol flow differs per image and cannot be batched across images by hand. KohakuGBC writes\nthat process once, as a sequential KIR program; Togeari runs many images at once, overlaps every\ncall the sequential run cannot tell apart, and turns their model calls into batched engine calls.\n\n![KohakuGBC: images admitted as jobs of the one GBC program, whose steps call four lanes that batch across images onto engine units; each job ends as a GBC graph](docs\u002Fassets\u002Farchitecture.jpg)\n\n**Contents:** [Highlights](#highlights) · [Install](#install) · [Quick start](#quick-start) ·\n[How it works](#how-it-works) · [Configuration](#configuration) · [Output](#output) ·\n[Faithful to GBC](#faithful-to-gbc) · [Measured](#measured) ·\n[Repository layout](#repository-layout) · [Documentation](#documentation) · [Checks](#checks)\n\n## Highlights\n\n- **2.06 images\u002Fs on one RTX 5090, 8.17 on four.** Qwen3.5-4B, SAM 3 and EmbeddingGemma on each\n  card, about 15 vertices and 27 captions per graph; each image is 41 s in the machine at the\n  median, however long the source runs. Four cards give 3.96x one card\n  ([measured](#measured)).\n- **Engines in their own processes.** Every card's engines run in an engine host process; the\n  machine's process holds connectors and the dispatcher only, over shared memory. That is +9%\n  over the same engines in the machine's process, and the same connector reaches engines on\n  other nodes.\n- **vLLM 3.1x faster on this workload.** [KohakuvLLM](https:\u002F\u002Fgithub.com\u002FKohakuBlueleaf\u002FKohakuvLLM)\n  (a drop-in vLLM plugin) takes `vllm serve` from 11.4 to 35.0 requests\u002Fs on one RTX 5090: FP8\n  GDN projections, a bf16 or INT8 GDN state, a Rust JSON grammar, and a phased scheduler. Every\n  reply is schema-valid.\n- **GBC at scale, with the models you choose.** Thousands to millions of images through a hosted\n  API, your own vLLM or SGLang servers, or engines on your GPUs; engines on other nodes join the\n  same lanes.\n- **Exactly the sequential procedure.** Every job can be recorded and replayed through KIR's\n  reference interpreter. On recorded runs of GBC's proof of concept, every graph equals the\n  PoC's to the digest.\n- **The procedure as data.** The root (an image query, existing captions, tags), the node budget,\n  the fan-out and the relational questions are per-image `controls`; the detector is one setting.\n- **One engine contract.** Every engine, from an HTTP server to the qwen35 engine written for this\n  workload, sits behind Togeari's contract and is checked against it.\n\n## Install\n\n```\npip install kohakugbc-data            # graphs and datasets only: no machine, no GPU stack\npip install kohakugbc                 # program, machine, API and replay engines\npip install \"kohakugbc[torch]\"        # detector (OWLv2, SAM 3) and embedder on torch\npip install \"kohakugbc[vllm]\"         # the VLM in-process through vLLM (Linux)\npip install \"kohakuvllm @ git+https:\u002F\u002Fgithub.com\u002FKohakuBlueleaf\u002FKohakuvLLM\"   # our vLLM parts\npip install \"kohakugbc[qwen35]\"       # the qwen35 VLM engine (Windows and Linux)\n```\n\nTwo packages from this repo:\n\n- `kohakugbc-data` (`packages\u002Fkohakugbc-data`, on PyPI): the GBC graph (store, resolution,\n  prompt rendering) and the GBC dataset format, with its Rust extension; depends on numpy,\n  pillow, pyarrow and kohakuvault only. Training code and dataset tools use this alone.\n- `kohakugbc` (pure Python): the program, machine and engines, on top of `kohakugbc-data`.\n\nFrom a clone, with a Rust toolchain:\n\n```\ngit clone https:\u002F\u002Fgithub.com\u002FKohakuBlueleaf\u002FKohakuGBC && cd KohakuGBC\nuv venv -p 3.13\nuv pip install -e packages\u002Fkohakugbc-data -e \".[torch,qwen35,dev]\"   # torch: the index matching your driver\ngbc doctor\n```\n\n`gbc doctor` prints versions, devices with their free memory, every entry per slot and, given\nconfiguration layers, their placement plan and whether it fits.\n\n## Quick start\n\n**On one GPU**, the VLM, the detector and the embedder in this process (`configs\u002Fmachine\u002F\nqwen35_local.py`: Qwen3.5-4B on the qwen35 engine, OWLv2, EmbeddingGemma on the CPU; 24 GiB):\n\n```\nGBC_IMAGES=path\u002Fto\u002Fimages gbc run configs\u002Fmachine\u002Fqwen35_local.py\n# SAM 3 as the detector (illustrations):\nGBC_IMAGES=path\u002Fto\u002Fimages gbc run configs\u002Fmachine\u002Fqwen35_local.py configs\u002Fmachine\u002Fqwen35_sam3_local.py\n```\n\nOne graph per image lands in `runs\u002Fmachine\u002Fqwen35_local\u002Fgraphs.jsonl`; the teaser above is the\ngraph of its image (29 vertices, the figure shows 20; 51 edges, 48 captions), drawn by\n`scripts\u002Fdocs\u002Fteaser.py`:\n\n```\n{\"vertices\":[{\"vertex_id\":\"\",\"bbox\":{\"left\":0.0,\"top\":0.0,\"right\":1.0,\"bottom\":1.0,\"confidence\"\n:null},\"label\":\"image\",\"descs\":[{\"text\":\"An anime-style illustration depicts a young girl with\nblonde hair and fox-like ears sitting on a weathered wooden window sil ...\n```\n\n**Over an API**, the VLM on a server (vLLM, SGLang, llama.cpp, OpenAI, OpenRouter, Anthropic),\nthe vision models here:\n\n```python\n# my_run.py\nengines = {\n    \"vlm\": {\n        \"entry\": \"api\",\n        \"protocol\": \"openai\",\n        \"flavour\": \"vllm\",\n        \"model\": \"Qwen\u002FQwen3.5-4B\",\n        \"endpoints\": [{\"base_url\": \"http:\u002F\u002F10.0.0.5:8000\u002Fv1\", \"max_inflight\": 64}],\n        \"metrics\": \"vllm\",\n    },\n    \"detect\": {\"entry\": \"torch\", \"model\": \"facebook\u002Fsam3\", \"dtype\": \"bfloat16\"},\n    \"embed\": {\"entry\": \"torch\", \"devices\": [\"cpu\"]},\n}\nsource = {\"kind\": \"folder\", \"path\": \"images\"}\nsink = {\"kind\": \"graphs\", \"path\": \"runs\u002Fmy_run\u002Fgraphs.jsonl\"}\nmachine = {\"report\": \"runs\u002Fmy_run\u002Freport\"}\n```\n\n```\ngbc check my_run.py      # build the machine without starting a unit; every problem at once\ngbc run my_run.py\n```\n\n**Without models**, the recorded PoC runs replayed: the program and the machine on pseudo\nengines, every graph equal to the PoC's.\n\n```\ngbc run configs\u002Fmachine\u002Freplay_text.py\n```\n\n**From Python**:\n\n```python\nfrom kohakugbc.machine import build\n\nmachine, source, sink = build(\n    \"configs\u002Fmachine\u002Fqwen35_local.py\", {\"source\": {\"kind\": \"folder\", \"path\": \"images\"}}\n)\nwith machine:\n    machine.run(source, sink)\n```\n\n| Command | Does |\n|---|---|\n| `gbc run CONFIG [CONFIG ...]` | builds the machine from configuration layers and runs its source into its sink |\n| `gbc check CONFIG ...` | builds and checks the machine without starting any unit |\n| `gbc host CONFIG ... --slot S --listen HOST:PORT` | serves slot S's units to machines on other nodes |\n| `gbc doctor [CONFIG ...]` | versions, devices, entries; a configuration's placement plan |\n\n## How it works\n\n| Layer | Package | Holds |\n|---|---|---|\n| GBC program | `kohakugbc.program`, `kohakugbc.nodes`, `kohakugbc.graph` | `gbc.kir` (one image job), the node library `gbc`, controls, records and graph resolution (Python reference; Rust in `kohakugbc-data`, equal by digest) |\n| GBC machine | `kohakugbc.machine`, `kohakugbc.io` | the program on Togeari: one lane per engine slot, bindings, admission, sources, sinks, configuration layers |\n| GBC engines | `kohakugbc.engines`, `kohakugbc_models` | entries per slot, the placement plan, engines on other nodes, replay engines for runs without models |\n\n### The GBC graph\n\nA GBC graph describes one image as a DAG. The image vertex carries a short and a detailed\ncaption; the objects those captions name are entity vertices with their own captions and boxes;\ntheir parts hang below them; composition vertices arrange several instances of one object;\nrelation vertices describe how objects relate. Every edge is grounded three ways: it is a graph\nedge, its label is a phrase of the parent's caption, and the child's box lies inside the parent's.\n\n### The program: one image job\n\n![GBC on one image: the root names objects and finds them; their regions wait in a frontier; a round runs every region as its own job (seen before? describe, find parts) and the parts join the frontier; a decision runs another round, asks for objects not covered yet, or ends; relation questions run over groups of nodes; the graph](docs\u002Fassets\u002Fworkflow.jpg)\n\nThe root describes the image and finds the objects it names; a round runs every waiting region\nas its own job (seen before? describe it, find its parts), and the parts it finds wait for the\nnext round. A decision then runs another round one level deeper, asks the VLM what the image\nstill holds and adds those objects, or ends with the relation questions. Every step marked ×?\nspawns as many jobs as its reply names, and the decision how many rounds run, so each image\ngrows its own workflow while it runs: from 3 VLM requests on one image to more than 30 on\nanother. That work cannot be batched stage by stage across images without waiting for the\nslowest one; the machine instead runs every job as soon as its inputs exist and batches whatever\ncalls are ready, across images (`scripts\u002Fdocs\u002Fworkflow.py`).\n\n`gbc.kir` is a plain sequential program; this is its top level:\n\n```\n@def (image, captions = None, tags = None, controls = None)gbc(graph, stats):\n    (image, captions, tags, controls)root(records, found)      # the image vertex, what it names\n    ...\n    decide:\n        (records, frontier, rounds, breadth, stop, controls)next_step(step)\n        (step)switch(\"depth\"=>`depth`, \"breadth\"=>`widen`, _=>`done`)\n        widen:                                                 # one more root sentence\n            (image, records, controls)coverage(records, found, grew)\n        depth:                                                 # one round of regions\n            (image, frontier, records, seen, controls)depth_round(frontier, records, seen)\n        done:\n    (image, records, controls)relate(records)                  # relations, compositions\n    (image, records, controls)to_gbc(graph, stats)             # records to the GBC graph\n```\n\n| `@def` | Does |\n|---|---|\n| `root` | the image vertex: GBC's image query, or existing captions (text, image and text, tags) |\n| `detect` | the regions detection finds for the named entities in a parent's box, one level down |\n| `expand` | one region: it joins a vertex seen before (same object by name embedding and box overlap), or it is described and its parts detected |\n| `wave`, `depth_round` | one round: the frontier as it was when the round began, in waves that take what the node budget still needs; a wave's regions run side by side |\n| `coverage` | one more root sentence naming objects not covered yet |\n| `relate` | relation and composition questions over the graph |\n| `ask` | a VLM request; a failed one answers with an empty reply, as GBC reads one |\n\nModel calls are transport-only nodes (`chat`, `detector`, `embedder`); requests are built and\nreplies parsed by plain nodes, so the same requests and parsing run on every engine.\n\n### GBC-Nest: the second program\n\n![GBC-Nest on one image: a grounded root (every listed element, probes for text, panels and people, one box per head noun); GBC's rounds with joins by head noun and mention-first parts; relations among the root's elements; then the graph shaped: one question per group (separate or pieces), identities merged, one question per proposed nesting, parents from containment](docs\u002Fassets\u002Fworkflow_nest.jpg)\n\nIn GBC the call tree is the graph: a region's parent is whichever crop's question named it.\n`gbc_nest.kir` keeps GBC's rounds for what to describe and takes the hierarchy from the boxes:\nits root keeps every element the image query lists and also looks for text, logos, comic panels\nand people where nothing named is; names sharing a head noun get one box each; a region joins a\nvertex seen before by head noun and overlap, never an ancestor; parts are what a person would\nmention first. A last stage asks one yes\u002Fno question per group (separate things, or pieces of one\narea) and per proposed nesting (the holder's and the child's boxes drawn), and sets parents\nfrom containment where the answer is not no, so a vertex may hang from several holders. A\nmachine runs it with the layer `configs\u002Fprograms\u002Fgbc_nest.py`\n([docs\u002Finternals\u002Fprogram.md](docs\u002Finternals\u002Fprogram.md#gbc-nest),\n`scripts\u002Fdocs\u002Fworkflow_nest.py`).\n\n### Controls\n\nOne job input holds every choice about what the graph contains; a configuration's `controls`\nare the defaults under each job's own.\n\n| Control | Default | |\n|---|---|---|\n| `root` | `query` | `query` (the VLM describes the image), `text` \u002F `image_text` (from existing captions), `tags` (from tags) |\n| `min_nodes`, `max_nodes`, `max_rounds` | 8, 20, 4 | node budget on image and entity vertices; rounds stop at the maximum, breadth rounds run below the minimum |\n| `max_top_level`, `max_features_per_entity`, `max_instances_per_text`, `max_depth` | 6, 4, 6, 3 | fan-out caps and depth |\n| `box_score`, `nms_iou`, `nms_iou_single`, `drop_containers` | 0.1, 0.2, 0.05, True | detection selection: score cut, NMS IoU (multiple \u002F single objects), a box containing another dropped; the PoC's, tuned for OWLv2 |\n| `round_size`, `priority`, `max_breadth_rounds`, `coverage_max_new` | None, `area_depth`, 1, 4 | regions per round and their order; coverage rounds |\n| `entity_batch`, `leaf_caption` | 1, `query` | regions per VLM request; leaves captioned by their own request or by the parent's reply |\n| `relational`, `relate` | `both`, `end` | which relational questions; asked once at the end or after every round |\n| `relation_vertices`, `prompts` | `all`, None | relation questions on every vertex or the image vertex only; the prompt set (`json`, `json_leafcap`, `json_nest`) |\n| `probes`, `probe_score`, `probe_gap`, `small_area`, `single_tie`, `head_overlap`, `group_check`, `nest_check` | GBC-Nest's | GBC-Nest only ([docs\u002Finternals\u002Fprogram.md](docs\u002Finternals\u002Fprogram.md#gbc-nest)); its own defaults over these (`kohakugbc.program.controls.PROGRAM_DEFAULTS`) |\n| `tag_select`, `tag_min_tags`, `tag_max_regions`, `tag_local_margin` | `top`, 3, 6, 0.2 | with `regions` tagging: the top-level vertices, or the important ones (GBC-Nest; `configs\u002Fcontrols\u002Ftags_important.py`, [docs\u002Finternals\u002Fprogram.md](docs\u002Finternals\u002Fprogram.md#gbc-nest)) |\n| `max_side` | 1568 | pictures sent to the VLM: the longer side scaled down to this |\n| `same_threshold`, `overlap_threshold` | 0.725, 0.85 | same-object check: name-embedding similarity and box overlap |\n| `tag_threshold`, `tag_hint` | 0.35, False | tags as elements of a seeded root; tags in the element prompt |\n\nControl presets are configuration layers in `configs\u002Fcontrols\u002F`: `small`, `mid`, `large` (graph\nsize), and `sam3` (SAM 3's selection: `box_score` 0.3, `nms_iou` 0.7; the PoC's 0.2 removes\noverlapping objects, two people embracing at IoU 0.5), stacked after a machine configuration\n(`configs\u002Fmachine\u002F\u003Cm>.py configs\u002Fcontrols\u002Fmid.py configs\u002Fcontrols\u002Fsam3.py`). On the 30 PoC\nimages with SAM 3 (Qwen3.5-4B FP8 on vLLM, one RTX 4090, 64 VLM requests in flight):\n\n| Preset | 30 images | Vertices | Entities | Captions |\n|---|---|---|---|---|\n| small + sam3 | 42.9 s | 10.7 | 6.2 | 18.2 |\n| mid + sam3 | 62.0 s | 14.7 | 8.8 | 26.8 |\n| large + sam3 | 92.8 s | 21.6 | 14.0 | 40.8 |\n| the PoC's graphs (OWLv2) | | 15.2 | 9.4 | 26.3 |\n\n### The machine\n\n```mermaid\nflowchart LR\n    subgraph proc[\"machine process\"]\n        direction LR\n        src[(\"source\")] --> adm[\"admission\"] --> jobs[\"image jobs\u003Cbr\u002F>gbc.kir, out of order\"]\n        jobs \u003C-->|\"calls\"| lanes[\"lanes\u003Cbr\u002F>vlm · detect · embed · cpu\"]\n        lanes \u003C--> conn[\"connectors\u003Cbr\u002F>remote units · API units\"]\n        jobs --> sink[(\"graphs.jsonl\")]\n    end\n    conn \u003C-->|\"shm \u002F inband\"| h0[\"gbc host, card 0\u003Cbr\u002F>vLLM · SAM 3 · EmbeddingGemma\"]\n    conn \u003C-->|\"shm \u002F inband\"| h1[\"gbc host, card N\"]\n    conn \u003C-->|\"TCP\"| far[\"gbc host on another node\"]\n    conn \u003C-->|\"HTTP\"| api[\"OpenAI-compatible or Anthropic API\"]\n```\n\nTogeari runs each image job like a thread on an out-of-order CPU core: statements issue as soon\nas their inputs exist, a branch still being decided parks while the code after it runs ahead, a\n`parallel` or `each` fans out, and a window retires everything in program order, so a job's\nresult is exactly the sequential run's. Across jobs, every model call of one kind joins one\nlane: the detect lane batches crops from many images into one forward, the VLM lane keeps its\nunits' queues full.\n\nEach lane's units are connectors. `configs\u002Fmachine\u002Fqwen35_card.py` starts one `gbc host` per card\nrunning that card's engines, and the lane holds a remote unit for each. The dispatcher has its\nprocess's GIL to itself: it does not share it with a VLM's frontend or SAM 3's preparation. Images\nand tensors travel in shared-memory blocks, everything else as small messages, and capacity and\nload are reported back at least every 0.2 s ([engine hosts](docs\u002Finternals\u002Fengine-host.md)).\n\n![The GBC machine on one RTX 5090: 240 images, every engine call per image over time, calls in flight per lane, and one image's overlapping calls](docs\u002Fassets\u002Fmachine.jpg)\n\nOne run of the machine from its event log (`scripts\u002Fdocs\u002Fmachine_view.py`). It is 240 COCO\nimages on one RTX 5090 with the defaults of `configs\u002Fmachine\u002Fqwen35_card.py` (engines in a host\nprocess, 96 resident images), taking 126 s for 19,849 engine calls (1.91 img\u002Fs, loading\nexcluded). Left, each image is a row and each engine call a bar in its lane's colour. The first\n96 images are admitted at once, and each later image enters as one finishes, so images overlap\non the shared engines. Right, the VLM lane fills to its 384 lanes as the first images fan out,\nthen holds 100–300 requests in flight as images come and go. A single image keeps up to 10 of\nits own VLM requests in flight at once.\n\n| Slot | Node | Lane | Entries |\n|---|---|---|---|\n| `vlm` | `chat` | stream units | `api`, `vllm`, `qwen35` (the `qwen35` extra), `replay`, `remote` |\n| `detect` | `detector` | batch units | `torch` (OWLv2 or SAM 3), `replay`, `remote` |\n| `embed` | `embedder` | batch units | `torch` (EmbeddingGemma), `replay`, `remote` |\n| `cpu` | crops, pictures, parsing, resolution | worker pool | `python` (threads or processes), `remote` |\n\nAdmission keeps the VLM lane at its target load (`vlm_waiting`): an image is admitted while the\nlane's queue and its units' waiting counts are below it, every other lane in `waiting` is below\nits limit, and fewer than `max_jobs` images are resident. `max_jobs` bounds an image's time in the\nmachine (about `max_jobs` \u002F throughput) however long the source runs. Each slot's entry is\nselected once; the placement plan adds up what every engine holds on every device and refuses a\nconfiguration that does not fit before any weight loads.\n\n### Engines\n\n| Entry | Slot | Runs | Notes |\n|---|---|---|---|\n| `api` | vlm | any OpenAI-compatible server or Anthropic's Messages API, one unit per endpoint | `flavour` places the JSON schema and turns Qwen3.5's thinking off per server kind; rate limits, health checks, `X-GBC-Request` digests |\n| `vllm` | vlm | vLLM's `AsyncLLM` in this process, one unit per device group | tensor parallel over a unit's devices; its reservation in the placement plan |\n| `qwen35` | vlm | a Qwen3.5 engine written for this workload ([kohakugbc_models\u002Fvlm\u002Fqwen35](src\u002Fkohakugbc_models\u002Fvlm\u002Fqwen35\u002FREADME.md)) | packed mixed steps over state slots and paged KV, prefix snapshots, Triton kernels raced against references, decode CUDA graphs, xgrammar masks with forced-token jumps, a vision stage of its own |\n| `torch` | detect | OWLv2 (`google\u002Fowlv2-base-patch16-ensemble`, the PoC's) or SAM 3 (`facebook\u002Fsam3`: GBC's own model, [kohakugbc_models.detect](src\u002Fkohakugbc_models\u002Fdetect)) | one unit per device; OWLv2 in float16 at batch 1 reproduces the PoC's boxes exactly; SAM 3 with fused kernels per arch, CUDA graphs, optional fp8, a measured memory plan |\n| `torch` | embed | EmbeddingGemma (GBC's own model, [kohakugbc_models.embed](src\u002Fkohakugbc_models\u002Fembed)) | a batch packed into one token stream, varlen attention, CUDA graphs; equal to sentence-transformers' vectors in float32 |\n| `python` | cpu | Togeari's Python workers | threads or processes |\n| `remote` | any | units served by `gbc host` on another node | the lane sees them as local units |\n| `replay` | any | answers from a recorded trace with its recorded latencies | for running the program and the machine without models |\n\n**Detection on illustrations.** On an anime-style portrait, OWLv2 (the PoC's detector) gives its\nbest \"girl\" box (0.415) to her legs alone, and the GBC rule for a single object keeps it; her\nparts are then asked of that crop, where her tail is the only \"hair\" in sight. SAM 3 boxes the\nwhole girl (0.89), her hair (0.94) and her tail (0.91) apart. The detector is one setting:\n\n```python\nengines = {\"detect\": {\"entry\": \"torch\", \"model\": \"facebook\u002Fsam3\", \"dtype\": \"bfloat16\"}}\n```\n\n**Engines on other nodes.** `gbc host` serves a slot's units; the machine names them as a\n`remote` entry, and its lane batches, retries and fails over as for local units\n([engine host](docs\u002Finternals\u002Fengine-host.md)):\n\n```\nKOHAKUGBC_HOST_KEY=... gbc host my_vlm.py --slot vlm --listen 0.0.0.0:7501\n```\n\n```python\nengines = {\"vlm\": {\"entry\": \"remote\", \"hosts\": [\"10.0.0.5:7501\u002Fqwen35-0\"], \"runs\": {...}}}\n```\n\n## Configuration\n\nConfiguration files are Python files (or dicts); their lower-case module-level names form one\nlayer, and later layers merge over earlier ones key by key, so a run is usually a base file plus\na small file of overrides.\n\n| Name | Holds |\n|---|---|\n| `engines` | per slot: `entry` and the entry's settings |\n| `machine` | `vlm_waiting`, `waiting` (`{lane: items}`), `max_jobs`, `window`, `start_timeout_s`, `record` (the fraction of jobs recorded for conformance), `store`, `report` (a run-report folder), `knobs` (any Togeari knob) |\n| `source` | `{\"kind\": \"folder\" \\| \"jsonl\" \\| \"trace\", \"path\": ...}`: images, or jobs with `key`, `captions`, `tags` and `controls` per image; `\"shard\": [rank, world]` takes one machine's share; a `jsonl` source's `\"skip\": [vault, ...]` leaves out the keys those vaults hold |\n| `sink` | `{\"kind\": \"graphs\", \"path\": ...}` (graphs, failures, per-job counts), `{\"kind\": \"vault\", \"path\": ...}` (the same in one KohakuVault file, indexed by job key) or `{\"kind\": \"memory\"}` |\n| `controls` | defaults under every job's own controls |\n\nEvery engine entry, with all its settings: [docs\u002Fguides\u002Fengines.md](docs\u002Fguides\u002Fengines.md).\n\n## Output\n\n`graphs.jsonl` holds one GBC graph per line, the JSON ml-gbc writes (`vertices` with\n`vertex_id`, `bbox`, `label` image \u002F entity \u002F composition \u002F relation, `descs` with their kind,\n`in_edges` and `out_edges` labelled by their grounding phrase). Beside it, `graphs.failures.jsonl`\n(one line per failed job: key, kind, message) and `graphs.stats.jsonl` (per job: vertices by\nkind, edges, captions, depth, leaves). The `vault` sink (`kohakugbc.io.vault`) keeps the same\nthree in one KohakuVault file, by job key: `graphs` (the graph JSON, zlib), `stats`, `failures`;\n`read_vault` reads them back, and `scripts\u002Fdata\u002Findex_jobs.py` makes jobs keyed `set\u002Fkey` from\n`set\u003CTAB>key\u003CTAB>path` index files, so a graph and its image find each other. A run report\n(`machine.report`) holds the configuration, the environment, per-second metrics of every lane and unit, events, recorded jobs and a summary.\n\nCaptioned images ship as a GBC dataset (`kohakugbc_data.dataset`, in `kohakugbc-data`): sharded\nfolders of KohakuClip image shards, graphs and per-image metadata in KohakuVault, joined by key\n([dataset format](docs\u002Fguides\u002Fdataset.md)).\n\n## Faithful to GBC\n\nThe node library ports GBC's proof of concept (its round engine, JSON reply layer and seeded\nroot) and ml-gbc's parsers, detection post-processing, same-object merge and relational queries.\nSix PoC arms (text, image and text, tags and image-query roots; entity batch 4; leaf captions\nfrom the parent; 30 images each) were recorded as traces of every request and reply.\n\n| Check | Result |\n|---|---|\n| graph resolution, Python and Rust, against ml-gbc's conversion | equal on all 462 PoC records; Rust 0.21 ms per graph, Python 1.27 ms |\n| the program under KIR's reference interpreter, replaying the six arms | 180 \u002F 180 graphs equal to the PoC's by digest; every request one the PoC made |\n| the machine on replay engines | 1320 jobs, every graph equal to the PoC's, every recorded job conforms |\n| the machine on real engines | every job finishes and conforms; graph statistics beside the PoC's ([measured](#measured)) |\n\nWhere the program differs from the PoC (prompt files read as UTF-8, seeded draws where the PoC's\nwere unseeded, relational questions asked once at the end by default), each difference and why:\n[docs\u002Finternals\u002Fprogram.md](docs\u002Finternals\u002Fprogram.md).\n\n## Measured\n\nFull tables and methods: [docs\u002Fperformance](docs\u002Fperformance\u002FREADME.md).\n\n### The machine on RTX 5090s\n\nA Linux box with four RTX 5090s; `configs\u002Fmachine\u002Fqwen35_card.py` with the `mid` and `sam3`\ncontrol presets on COCO val2017. Qwen3.5-4B (FP8, FP8 GDN projections) runs through vLLM 0.32\nwith KohakuvLLM's PhasedScheduler, grammar and INT8 GDN state, at 384 lanes and a 12 GiB KV\ncache. GBC's SAM 3 and EmbeddingGemma share the card. 96 images are resident per card, and job\nseconds are each image's time from admission to its graph\n([flagship](docs\u002Fperformance\u002Fflagship.md)):\n\n| Engines | Cards | Images | img\u002Fs | Job s p50 \u002F p90 \u002F p99 | GPU busy |\n|---|---|---|---|---|---|\n| in the machine's process | 1 | 1200 | 1.886 | 44 \u002F 58 \u002F 71 | 97.2% |\n| **one engine host per card** (the default) | 1 | 1200 | **2.061** | 41 \u002F 71 \u002F 87 | 98.1% |\n| **one engine host per card** (the default) | 4 | 4800 | **8.165** | 42 \u002F 67 \u002F 84 | 96.2-97.8% |\n\nBoth one-card runs make the same engine calls: 16.5k VLM, 11.1k detector and 12.1k embedder.\nThe card is power-bound at 98% busy. With the engines in a host, the dispatcher keeps its GIL\nand the detector's queue drains (61 to 14 requests waiting). One machine over four cards gives\n3.96x one card with its job times unchanged. Throughput and job time hold however long the\nsource runs, because admission bounds the resident images.\n\n**The VLM behind `vllm serve`**, one RTX 5090, the same workload's 1724 recorded requests\n(about 1000 prompt tokens, 100 reply tokens, one image and one JSON schema each), 512 in flight,\nmean of four cards ([KohakuvLLM](https:\u002F\u002Fgithub.com\u002FKohakuBlueleaf\u002FKohakuvLLM)):\n\n| Step (`*`: KohakuvLLM) | req\u002Fs | Gain |\n|---|---|---|\n| stock vLLM (0.55 of the card, 256 seqs, xgrammar) | 11.4 | |\n| + 0.90 of the card, 384 seqs | 11.7 | +2% |\n| + FP8 GDN projections * | 12.9 | +11% |\n| + bf16 GDN state * | 26.7 | +107% |\n| + our grammar, replacing xgrammar * | 28.8 | +8% |\n| + INT8 GDN state * | 30.1 | +5% |\n| + PhasedScheduler * | **35.0** | **+16%** |\n\nIn the machine, the grammar is also the fastest way to get structured replies: 1.589 img\u002Fs,\nagainst 1.539 for prompt + one retry, 1.426 for guidance and 1.226 for xgrammar. On RTX 3090s\n(SmoothQuant INT8, 6 GiB KV cache, the same configuration), the machine gives 0.630 img\u002Fs per\ncard.\n\n### On one RTX 4090 desktop\n\nAn RTX 4090 (24 GiB) on Windows 11, Python 3.13, torch 2.14.\n\n**The machine on pseudo engines** (`scripts\u002Fbench\u002Fpseudo_machine.py`: 120 recorded jobs per\nconfiguration, replayed latencies divided by 4). The VLM lane is the limit; the machine keeps it\n85–94% of the way to its floor (every VLM latency over the lane's capacity):\n\n| Configuration | Wall s | Floor s | Efficiency | VLM in flight |\n|---|---|---|---|---|\n| text root, VLM capacity 32 | 35.25 | 33.03 | 0.937 | 0.933 |\n| text root, VLM capacity 64 | 19.34 | 16.52 | 0.854 | 0.845 |\n| text root, no run-ahead | 38.85 | 33.03 | 0.850 | 0.868 |\n| image query root | 48.53 | 44.12 | 0.909 | 0.909 |\n| tags root | 32.42 | 30.35 | 0.936 | 0.907 |\n| entity batch 4 | 32.14 | 28.31 | 0.881 | 0.868 |\n\n**The machine on real engines** (`scripts\u002Fbench\u002Freal_machine.py configs\u002Fmachine\u002Fqwen35_local.py`:\nthe recorded jobs of two PoC arms, 30 images each; the qwen35 VLM, OWLv2 and EmbeddingGemma on\nthe one GPU; wall time includes loading the models):\n\n| Arm | Jobs ok | Conform | Wall | Vertices (ours \u002F PoC) | Edges (ours \u002F PoC) |\n|---|---|---|---|---|---|\n| text root | 30 \u002F 30 | 30 \u002F 30 | 89.0 s | 15.97 \u002F 15.17 | 28.43 \u002F 26.07 |\n| image query root | 30 \u002F 30 | 30 \u002F 30 | 102.1 s | 16.03 \u002F 17.13 | 27.40 \u002F 29.63 |\n\nOne portrait image on the same GPU: 34 s with OWLv2, 79 s with transformers' SAM 3 (the device\nfills with SAM 3 beside the VLM).\n\n**The VLM alone** (`scripts\u002Fbench\u002Fvlm_units.py`: the 425 VLM requests of the text arm, 409\nmeasured, 64 in flight, Qwen3.5-4B, stock vLLM):\n\n| Engine | Requests\u002Fs | Reply tokens\u002Fs | Latency p50 \u002F p95 |\n|---|---|---|---|\n| `qwen35` (float32 states) | 7.48 | 828 | 7.51 s \u002F 11.85 s |\n| vLLM 0.32 in WSL | 10.21 | 1101 | 6.18 s \u002F 9.76 s |\n\n### The detector and the embedder\n\nGBC's own SAM 3 and EmbeddingGemma against their reference libraries: 45 recorded detector\nrequests through the detect engine and 925 names\n([six GPUs and the CPU](docs\u002Fperformance\u002Fdetector.md)):\n\n| GPU | SAM 3, GBC's \u002F transformers' | EmbeddingGemma fp32, GBC's \u002F sentence-transformers' |\n|---|---|---|\n| RTX 4090 (bf16) | 2.41 s \u002F 5.48 s | 6004 \u002F 1472 texts\u002Fs |\n| RTX 5090 (bf16) | 1.50 s \u002F 3.44 s | 7307 \u002F 1726 texts\u002Fs |\n\n## Repository layout\n\n```mermaid\nflowchart LR\n    cli[\"cli\"] --> machine[\"machine\"] --> program[\"program\"] --> nodes[\"nodes\"] --> gbcgraph[\"graph (Python, Rust)\"]\n    machine --> togeari[\"Togeari\"]\n    machine --> engines[\"engines\u003Cbr\u002F>vlm · torch · host · replay\"] --> models[\"kohakugbc_models\u003Cbr\u002F>detect · embed · vlm · kernels\"]\n    engines --> kvllm[\"KohakuvLLM\"]\n    program --> kir[\"KohakuNodeIR\"]\n```\n\n```\nsrc\u002Fkohakugbc\u002F\n  program\u002F        gbc.kir, controls, the reference run\n  nodes\u002F          the node library gbc: root, regions, relations, specs (chat, detect, parse)\n  graph\u002F          records, resolution to GBC graphs, digests\n  machine\u002F        build, configuration layers, the machine module\n  engines\u002F        registry, placement, adapters, vlm\u002F (api, vLLM in-process, qwen35), torch\u002F,\n                  host\u002F, replay\u002F\n  io\u002F             sources (folder, jsonl, trace), sinks (graphs, memory)\n  cli\u002F            gbc\nsrc\u002Fkohakugbc_models\u002F     the models GBC runs itself, standalone of the program and machine\n  detect\u002F         GBC's own SAM 3 (vision, fusion, masks, memory plan), mask boxes\n  embed\u002F          GBC's own EmbeddingGemma over packed token streams\n  vlm\u002Fqwen35\u002F     the Qwen3.5 engine: forward, ops (Triton, FLA), pools, grammar, graphs, loop\n  kernels\u002F        op registry, per-card tuning, CUDA graphs, fp8; backends eager \u002F compile \u002F\n                  triton \u002F tilelang (attention, varlen, box bias, mask box, fp8 producers)\n  numerics\u002F       error profiles against an fp64 ruler\npackages\u002Fkohakugbc-data\u002F  the data package (PyPI kohakugbc-data)\n  rust\u002F           kohakugbc_data._rs: graph resolution, the graph store, prompts\n  src\u002Fkohakugbc_data\u002F     prompt\u002F (renderers), dataset\u002F (the GBC dataset format)\nconfigs\u002F              machine and engine configurations\nscripts\u002F              trace recording, benchmarks, docs figures; ci\u002F (versions, release notes)\ndocs\u002F                 concepts, guides, internals, performance\ntests\u002F                data and format checks: program, graph, engines; fixtures: recorded PoC traces\n```\n\n## Documentation\n\n| Where | Read it for |\n|---|---|\n| [docs\u002Fconcepts](docs\u002Fconcepts\u002FREADME.md) | what a GBC graph is, the program, the machine, the engines |\n| [docs\u002Fguides](docs\u002Fguides\u002FREADME.md) | configuring every engine entry, running on one GPU, over an API, on other nodes; scoring predicted graphs |\n| [docs\u002Finternals](docs\u002Finternals\u002FREADME.md) | the machine, the placement plan, engines on other nodes, the program and its differences from the PoC, traces, graph resolution |\n| [docs\u002Fperformance](docs\u002Fperformance\u002FREADME.md) | the machine on pseudo engines, on real engines, the VLM engines alone, the detector and the embedder on six GPUs and the CPU |\n| [docs\u002Finternals\u002Fkernels.md](docs\u002Finternals\u002Fkernels.md) | the kernel package: registry, tuning, graphs, fp8, every op per arch |\n| [kohakugbc_models\u002Fvlm\u002Fqwen35](src\u002Fkohakugbc_models\u002Fvlm\u002Fqwen35\u002FREADME.md) | the Qwen3.5 engine: settings, design, measuring |\n\n## Checks\n\n```\npython -m pytest tests -q                             # data and format checks, CPU only\npython scripts\u002Fbench\u002Fpseudo_machine.py                # the machine on pseudo engines\nscripts\u002Fbench\u002Fmachine\u002Fcard.sh CARD TAG                # one machine per card, every metric on disk\npython scripts\u002Fbench\u002Freal_machine.py configs\u002Fmachine\u002Fqwen35_local.py --name local   # real engines\npython scripts\u002Fbench\u002Fvlm_units.py --trace runs\u002Ftraces\u002Fpoc30\u002Ftext --name qwen35 --engine '{\"entry\": \"qwen35\", \"model\": \"...\"}'\n```\n\nGBC is a compute project: the tests check data and formats only, and everything else is checked\nby runs on the cards. `tests\u002Fprogram` replays recorded jobs of every fixture arm through the\nreference interpreter and compares graphs by digest; `tests\u002Fgraph` holds both resolutions to\nml-gbc's; `tests\u002Fengines` checks the API entry's request shapes, the batch formers and SAM 3's\nmask boxes. Engines, kernels and the machine are measured by the benches above, every metric on\ndisk ([performance](docs\u002Fperformance\u002FREADME.md)). CI checks the code's form (lint, import\nboundary, rustfmt, clippy).\n\n## Contributing\n\nOpen an issue first for a feature. Conventions: black and ruff at line length 100, no imports\ninside functions, nested folders, comments that say what the code does, docs that describe what\nexists, and every check able to fail on a broken implementation. Run the checks above before a\npull request.\n\n## Original implementation\n\n[apple\u002Fml-gbc](https:\u002F\u002Fgithub.com\u002Fapple\u002Fml-gbc).\n\n## License\n\nApache-2.0.\n","KohakuGBC 是一个基于图结构的图像描述生成系统，将 Graph-Based Captioning（GBC）建模为可在 Togeari 数据流机器上运行的统一 KIR 程序。其核心功能是动态构建图像语义图：通过多阶段协同（视觉语言模型理解、区域检测、细粒度描述、部件识别、关系推理），自适应生成带实体节点与描述边的 GBC 图。技术特点包括跨图像自动批处理调用、引擎进程隔离设计、支持 vLLM\u002FSAM3\u002FOWLv2\u002FQwen3.5\u002FEmbeddingGemma 等异构模型即插即用，以及单卡至多卡\u002F分布式部署能力。适用于需高精度、可解释性图像语义解析的大规模图文理解、无障碍图像描述生成及视觉知识图谱构建等场景。",2,"2026-11-24 04:36:35","CREATED_QUERY"]