Skip to content

examples: pure-Python and pure-C++20 manifest consumers - #154

Merged
xiaguan merged 1 commit into
masterfrom
kern-py/pure-python-executor
Nov 19, 2026
Merged

xiaguan merged 1 commit into
masterfrom
kern-py/pure-python-executor

Conversation

@xiaguan

@xiaguan xiaguan commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds standalone, Rust-free reference consumers of a kern v7 manifest side by side under examples/, keeping crates/kern-py focused on the compiled kern-llm wheel:

  • examples/python/
    • manifest.py: zero-dependency v7 manifest parser, constant expansion (preserving identifier/reference fields), scalar expression evaluator (ceil_div, mul, add, clamp), and serving Protocol projection.
    • executor.py: single-GPU pure-Python executor over cuda-python, PyTorch (CUDA graphs, BF16 GEMM externs), and safetensors.
    • run.py / server.py: minimal model-agnostic CLI runner and stdlib continuous-batching OpenAI HTTP/SSE server over Protocol.
    • test_manifest.py: pure-CPU unit tests.
  • examples/cpp/
    • json.hpp / manifest.hpp: zero-dependency C++20 RFC 8259 JSON parser, v7 manifest reader, constant expansion, expression evaluator, and Protocol projection.
    • cuda_api.hpp / executor.hpp: dlopen bindings for libcuda.so.1 and libcublasLt.so (no compile-time CUDA toolkit required), built-in SHA-256 cubin verification, mmap safetensors loading, TMA tensormaps, cuBLASLt BF16 GEMM, and CUDA Graphs.
    • run.cpp: token-ID CLI runner (kern-run) driving prefill + decode / speculative rounds through Protocol.
    • test_manifest.cpp / Makefile: pure-CPU unit tests and build.
  • CI (.github/workflows/ci.yml)
    • Wires both examples/python/test_manifest.py and make -C examples/cpp test into the tools job.

Verification

  • python3 -m unittest discover -s examples/python -p test_manifest.py -v (5/5 passed)
  • make -C examples/cpp test (g++ -std=c++20 -O2 -Wall -Wextra -Wpedantic, 0 warnings, 6/6 passed)
  • python3 -m unittest discover -s tools -p test_kern_manifest.py -v (1/1 passed)

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T18:02:59.250619Z caaa1d9 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: caaa1d90e2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread examples/python/run.py
Comment on lines +39 to +40
while pos < len(prompt_ids):
chunk = prompt_ids[pos : pos + p.rows_max]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Leave the final prompt token for decode when prefill emits nothing

For manifests whose chunk forward does not emit a token, this loop processes the entire prompt, then the first decode call feeds the last prompt token again at position len(prompt_ids). This duplicates that token in the context and shifts subsequent positions, corrupting generation. The existing driver explicitly handles this case in crates/kern-run/src/lib.rs::prefill_len by prefilling only prompt - 1 tokens. Apply that distinction here and in Engine._prefill, which has the same problem.

Useful? React with 👍 / 👎.

Comment on lines +229 to +230
if kind in ("input", "inout"):
inputs[fill] = f

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve token inputs on both row and group axes

When a manifest declares both a per-row token input and a per-group anchor-token input, inputs[fill] silently overwrites one with the other. This combination is explicitly supported by the existing Rust protocol and exercised in crates/kern-manifest/tests/protocol.rs. Since Executor.stage iterates only the retained entries, one required input remains zero or stale, causing incorrect prefill or speculative-round results. Preserve inputs by both role and axis, or retain all matching buffers.

Useful? React with 👍 / 👎.

Comment thread examples/python/server.py
Comment on lines +104 to +106
self.max_seqs = min(max_seqs, self.p.groups_max)
self.chunk_fwd = self.p.chunk_forward()
self.step_rows = int(self.p.step_forward(rows=rows, groups=1).rows)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound admission by the selected forward's group capacity

If the groups variable permits more sequences than the selected fixed-row forward, the engine admits a batch that it cannot execute. For example, with groups_max=16 and a decode forward declaring groups=1, two concurrent requests reach _step_batch, where step_forward(..., groups=2) raises an uncaught ValueError. That terminates the sole scheduler thread and leaves current and future HTTP requests waiting indefinitely. Clamp admission to the selected forward's groups bound, not just the variable maximum.

Useful? React with 👍 / 👎.

Comment thread examples/python/server.py
Comment on lines +204 to +207
req = self._pending[0]
alloc = self.pool.alloc(len(req.prompt_ids) + self.step_rows)
if alloc is None:
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject requests that can never fit in the pool

When a prompt plus the initial step requires more pages than the entire pool contains, alloc always returns None, but the request remains at the head of _pending. Once there are no active requests, the outer loop neither waits nor removes that request, so it busy-spins permanently and prevents every later request from being admitted. Detect permanently oversized requests and return an error rather than treating them as temporarily blocked allocations.

Useful? React with 👍 / 👎.

Comment thread examples/python/server.py
Comment on lines +237 to +239
def _format_chat(messages: list[dict[str, Any]]) -> str:
parts = [f"<|im_start|>{m['role']}\n{m.get('content', '')}<|im_end|>\n" for m in messages]
return "".join(parts) + "<|im_start|>assistant\n"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Render chat with the checkpoint's template instead of ChatML

For any checkpoint whose chat template is not this exact ChatML format, /v1/chat/completions supplies incorrect conversation delimiters and an incorrect assistant prefix, degrading or invalidating responses despite valid weights and a valid manifest. Unlike crates/kern-run/src/chat.rs::Renderer, this path never consults the checkpoint's renderer or template. Load the checkpoint's chat formatting rather than embedding a model-family-specific format in crates/; the root guidance explicitly requires model-specific knowledge to remain outside that directory.

AGENTS.md reference: AGENTS.md:L3-L9

Useful? React with 👍 / 👎.

@xiaguan
xiaguan force-pushed the kern-py/pure-python-executor branch from caaa1d9 to ffdf5d9 Compare November 19, 2026 18:07
@xiaguan xiaguan changed the title kern-py: pure-Python manifest reader, executor, runner and server examples: pure-Python manifest reader, executor, runner and server Nov 19, 2026
Adds standalone, Rust-free reference consumers of a kern v7 manifest side by
side under `examples/`:

- `examples/python/`: zero-dependency manifest/protocol reader (`manifest.py`),
  single-GPU executor over cuda-python + PyTorch (`executor.py`), CLI runner
  (`run.py`), minimal stdlib continuous-batching OpenAI server (`server.py`),
  and pure-CPU unit tests (`test_manifest.py`).
- `examples/cpp/`: zero-dependency C++20 manifest/protocol reader
  (`json.hpp`, `manifest.hpp`), `dlopen` CUDA Driver + cuBLASLt bindings
  (`cuda_api.hpp`), single-GPU executor with built-in SHA-256 and `mmap`
  safetensors loading (`executor.hpp`), token-ID CLI runner (`run.cpp`),
  `Makefile`, and pure-CPU unit tests (`test_manifest.cpp`).
- `.github/workflows/ci.yml`: runs both Python and C++20 manifest/protocol
  unit tests in the `tools` CI job.
@xiaguan
xiaguan force-pushed the kern-py/pure-python-executor branch from ffdf5d9 to 3acc216 Compare November 19, 2026 18:19
@xiaguan xiaguan changed the title examples: pure-Python manifest reader, executor, runner and server examples: pure-Python and pure-C++20 manifest consumers Nov 19, 2026
@xiaguan
xiaguan merged commit 39256e0 into master Nov 19, 2026
5 checks passed
@xiaguan
xiaguan deleted the kern-py/pure-python-executor branch November 19, 2026 18:28
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.

1 participant