Example

Swap runtime adapters under one generation contract

Run a toy adapter, inspect its capability matrix, and make a stricter adapter refuse a feature the model does not provide.

A model architecture decides which computations exist: attention shape, KV layout, expert routing, positional scheme. A runtime decides how those computations are scheduled, batched, cached, compiled and exposed. The two are not the same axis, and a service that conflates them ends up claiming a model feature because its runtime has a flag for it.

This example puts two adapters behind one generate contract. ToyAdapter reports what it supports: greedy and sampling yes, CUDA and streaming no. StrictAdapter calls require("streaming") and fails with the reason. The generation result hixxx is deliberately trivial; the lesson is the capability boundary, not the text. A runtime must ask the adapter what it can do before admitting a request that needs it.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch24/adapters.py --json

Python 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.

Implementation

CapabilityMatrix.supports is the single query point. ToyAdapter.generate checks greedy support, then appends max_new_tokens copies of x. StrictAdapter asks for streaming first, so the unsupported feature is reported by name and reason rather than silently ignored.

class CapabilityMatrix:
    backend: str
    capabilities: List[Capability]

    def supports(self, feature: str) -> bool:
        for cap in self.capabilities:
            if cap.feature == feature:
                return cap.supported
        return False

    def to_dict(self) -> dict:
        return asdict(self)


class ModelContract(Protocol):
    def generate(self, prompt: str, max_new_tokens: int) -> str: ...


class ToyAdapter:
    def __init__(self) -> None:
        self.matrix = CapabilityMatrix(
            backend="toy",
            capabilities=[
                Capability("greedy", True),
                Capability("sampling", True),
                Capability("cuda", False, "CPU only"),
                Capability("streaming", False, "Not implemented"),
            ],
        )

    def generate(self, prompt: str, max_new_tokens: int) -> str:
        if not self.matrix.supports("greedy"):
            raise RuntimeError("greedy unsupported")
        return prompt + ("x" * max_new_tokens)

    def require(self, feature: str) -> None:
        if not self.matrix.supports(feature):
            cap = next(c for c in self.matrix.capabilities if c.feature == feature)
            raise RuntimeError(f"{feature} unsupported: {cap.reason}")


class StrictAdapter(ToyAdapter):
    def generate(self, prompt: str, max_new_tokens: int) -> str:
        self.require("streaming")  # will fail
        return super().generate(prompt, max_new_tokens)

Expected outcome

Observed with the command above (exit 0):

{
  "toy_result": "hixxx",
  "toy_capabilities": {
    "backend": "toy",
    "capabilities": [
      {
        "feature": "greedy",
        "supported": true,
        "reason": ""
      },
      {
        "feature": "sampling",
        "supported": true,
        "reason": ""
      },
      {
        "feature": "cuda",
        "supported": false,
        "reason": "CPU only"
      },
      {
        "feature": "streaming",
        "supported": false,
        "reason": "Not implemented"
      }
    ]
  },
  "unsupported_report": "streaming unsupported: Not implemented"
}

The toy adapter generated hi plus three x characters. The strict adapter raised before generating, and the exception text names the feature and the adapter’s reason. The capability matrix is the part a service should consult before accepting a streaming request.

Mechanism and limitations

Documented: supports returns false for an unknown feature. ToyAdapter checks greedy support and appends one character per requested token. StrictAdapter requires streaming and therefore raises. run captures the exception into unsupported_report. The tests check generation, capability queries, the unsupported feature, the run result and JSON serialisation.

Observed: the command exited 0 with the matrix and unsupported report above. The targeted tests.test_ch24_adapters is part of the canonical suite; no independent test count is claimed here.

Not shown: a real model backend, CUDA, streaming, batching, equivalence between adapters, or a runtime scheduler. The toy output is not text quality evidence. A capability matrix can also be wrong: the adapter’s claim is only as good as its implementation and tests.

Challenge this result

Change the toy matrix so greedy is false and run ToyAdapter.generate. Predict whether the method returns text or raises, then explain why the capability check must happen before any work. Add a streaming implementation that yields three chunks and update the matrix; state which tests would now fail if the matrix still said false.

Source and verification

Canonical source: examples/ch24/adapters.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch24_adapters.py . Chapter: Model Architecture Versus Runtime Architecture . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it uses a toy adapter, not a model.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.