For now, I tried a quick run on Colab:
I looked at the three areas you mentioned: multilingual vocabularies, grammar size, and additional output shapes. The part I found most useful is the distinction between defining an allowed vocabulary once, enforcing it during generation, and explaining the result afterward. That seems directly connected to the reason for keeping WordlistSpec at the center of smallwords.
My short answers:
- Multilingual vocabularies: Explicit Unicode literals already worked through the native GBNF path in my small test: Gemma 4 emitted both
café and 東京 under one-literal grammars. The more actionable boundary was input-word extraction and diagnostics. At the pinned smallwords revision, allow_input_words extracted caf from café and nothing from 東京; an explicitly allowed café could also be valid=True while the diagnostic still reported caf as out of vocabulary. I would start by making the language/segmentation policy for those helpers explicit, without requiring a full multilingual morphology system.
- Grammar size: Your runnable example already narrows the vocabulary for a particular task; I would keep that as the default path. On my Colab T4, grammars with 15–18 permitted surface forms completed short rewrites in roughly 1–2 seconds. Two corresponding attempts with approximately 1,075 forms each hit a 115-second worker timeout without a completed output. CUDA offload was verified; those timeouts are not completed generation timings. This is one backend-specific observation, not evidence that
smallwords itself is intrinsically slow; it suggests separating grammar construction, native grammar initialization, and per-token constraint costs before changing the architecture.
- Additional shapes: The existing short-text and single-key JSON outputs seem a good starting point. An optional array of individually constrained strings or a small named-field object would be useful when a UI/API consumes separate items. I would not make either the default, or build a general schema language, without such a consumer. Each content field should still derive its lexical policy from the same specification.
The default route I would suggest is modest: keep the existing WordlistSpec and focused-subset workflow, add a handful of positive/negative cross-surface tests, and treat non-English text extraction as a separately declared policy. For rewriting tasks, add one application-level question before making a vocabulary very small: does it still contain a way to express the facts that must survive?
That last point came from an intentionally small comparison. These are my own test sentences, separate from your missile example:
| Source idea |
Without grammar |
With a tiny task-focused vocabulary |
Observation |
| Cross a river without getting wet |
A bridge allows people to cross a river without getting wet. |
A bridge is a bridge to getting people to a river to be wet. |
Vocabulary/shape validation passed, but the negated outcome was lost or effectively reversed. |
| Lamp off because switch off |
The lamp is not on because its switch is off. |
The lamp is not on because the switch is off. |
Validation passed and the negation and cause survived. |
Crucial qualification: I had omitted without and not from the Bridge subset, whereas the Lamp subset included not and because. So the first example is not evidence that grammar-constrained decoding necessarily ruins meaning. The tiny wordlist I selected removed an obvious way to state the important condition. The useful next experiment is to add one critical expression back and compare under otherwise identical conditions. That is a vocabulary-design/expressibility check, separate from whether the generator obeyed the contract.
The run used pinned smallwords source, Gemma 4 E2B-it GGUF (UD-Q4_K_XL), and a JamePeng CUDA 12.6 wheel on Colab T4. The runtime reported 36/36 layers offloaded to CUDA0. These single-setting examples are not quality statistics or portable latency benchmarks.
Details and optional follow-ups are below.
1. Reproduction scope and the exact T4 observations
Environment and controls
| Item |
Recorded value |
smallwords |
v0.2.0 source snapshot, commit 59e36e5b5fdead0f6bdb45274ea959447cd8e832 |
| GGUF |
unsloth/gemma-4-E2B-it-GGUF, gemma-4-E2B-it-UD-Q4_K_XL.gguf |
| Model revision |
0314792d7f1f7e229411f620751375812bb9faf2 |
| Model SHA-256 |
b52f438017efaec5debf1c0d8be690571e212a07c312f1102bbce927258cfc32 |
| Model file size |
3,184,496,736 bytes |
| Inference binding |
JamePeng llama-cpp-python 0.4.3+cu126 |
| Runtime |
Colab T4, Linux, Python 3.13.15 |
| Backend evidence |
CUDA0 registered; 36/36 layers offloaded; about 1,915 MiB increase in observed GPU-memory use |
| Rewriting controls |
Seed 42, temperature=0, top_p=1, up to 96 output tokens |
| Isolation |
Fresh subprocess and model context for each case |
The English tests requested a single short sentence preserving the source facts, including negation and causal relations. The four source sentences were:
Bridge: A bridge lets people cross a river without getting wet.
Soap: Washing hands with soap and water removes dirt before eating.
Steam: When sunlight heats water, some water changes into steam.
Lamp: The lamp is not on because its switch is off.
There were 12 jobs in the corrected T4 run: four unconstrained rewrites, four tiny focused-grammar rewrites, two single-literal Unicode probes, and two broad-grammar attempts. Ten completed, while the two broad-grammar workers timed out. Every completed focused English rewrite passed smallwords’ full output validation. Neither timeout was counted as a semantic success or failure.
The prompt and tiny wordlists were designed for this probe, not copied from your focused missile example. These subsets are not complete bundled presets.
Successful timings cover create_chat_completion after the grammar object was built. They exclude downloads, model loading, GBNF construction and grammar-object parsing, but include prompt processing and token sampling. Output lengths differ.
| Case |
Unconstrained |
Focused grammar |
Focused validation |
| Bridge |
0.865 s, 12 tokens |
1.894 s, 17 tokens |
valid=True |
| Soap |
0.333 s, 12 tokens |
1.869 s, 17 tokens |
valid=True |
| Steam |
0.362 s, 12 tokens |
1.093 s, 9 tokens |
valid=True |
| Lamp |
0.358 s, 11 tokens |
1.298 s, 11 tokens |
valid=True |
An earlier small-model CPU probe capped timing requests at one generated token, so its measurements cannot be combined into this run’s throughput figures. The first Gemma 4 attempt also fell back to CPU due to CUDA library search paths; the corrected run verified real offload. This does not imply that every buffer lived on the GPU.
Limits: one seed, four chosen sentences, unequal output lengths, fresh workers, and censored timeouts do not establish a speed curve or general semantic-preservation rate. The examples quoted here match the archived raw outputs.
2. Multilingual behavior: literals, extraction, normalization, and diagnostics
What worked
The Gemma 4 CUDA run emitted the exact literals below under very small native GBNF grammars:
café
東京
Both complete outputs were valid=True under their corresponding explicit literal policies. These were one-literal smoke tests, not Japanese-language rewriting or general multilingual generation. They demonstrate that this specific GBNF/runtime/tokenizer path can emit those Unicode terminals. This is compatible with the llama.cpp GBNF guide, which describes Unicode character terminals.
What did not line up
The inspected validation implementation uses:
WORD_RE = re.compile(r"[A-Za-z']+")
That is a simple convention for English-oriented text, not a multilingual word segmenter. The input-word helper relies on the same extraction approach. In the pinned source, I observed:
| Input or output |
Extraction / diagnostic behavior |
Input café to allow_input_words |
The extracted word was caf |
Input 東京 to allow_input_words |
No word was extracted |
Explicitly allowed output café |
valid=True, but out_of_vocab=('caf',) and an OOV issue |
Explicitly allowed output 東京 |
valid=True, no OOV item |
The last two results highlight the separation between an acceptance verdict and a diagnostic explanation. Direct whole-output pattern matching admitted the authored literal café, while diagnostic tokenization described a different unit (caf). A user seeing valid=True alongside an OOV issue could reasonably be confused even though whole-output acceptance and its diagnostic helper are checking different units.
I would therefore separate at least three meanings of “multilingual support”:
- Literal whitelist: A caller supplies the exact permitted Unicode strings. This can be viable without any text segmentation, and the native literal smoke test already gives a positive result.
- Automatic task-word extraction: The library reads a prompt or document and tries to add its words. That needs an explicit extraction convention, including what counts as a word. It is not proved by a literal GBNF test.
- Natural-language word families and sentence generation: Inflection, case, conjugation, compounds, segmentation and fluency are further language-specific decisions. They should be separate optional scope, not silently inferred from the first two.
One relatively low-cost path would be to keep today’s English extraction as the default and allow an optional lexical policy for non-English use. For a Latin-script whitelist, retaining complete accented words and making diagnostics agree with declared forms may suffice. For languages without spaces between many lexical units, there is a genuine segmentation choice: the Unicode word-boundary standard, UAX #29, provides useful terms and tailoring guidance, but it does not automatically supply task-specific Japanese morphology.
Normalization is another declared choice: precomposed and decomposed accented strings may look identical but have different code points. Exact matching or Unicode canonical equivalence can both be reasonable, provided grammar, schema, validation and diagnostics agree. I did not test decomposed accents on GPU.
The narrowest useful regression fixture is to allow café literally and check both report.valid and report.out_of_vocab. A second fixture can contrast explicit 東京 with task-word extraction from 東京. A full multilingual roadmap is unnecessary to make those behaviors inspectable.
3. Grammar-size results and a way to localize the cost
Your existing runnable example already derives focused wordlists from larger presets. That seems important: a source-backed policy can be broad without requiring every prompt to expose the full set of alternatives to the decoder.
Two tasks in my run had both focused and expanded grammar attempts. The form counts below come from spec.allowed_words(); the generated GBNF can also include capitalized alternatives:
| Case |
Lane |
Allowed surface forms |
GBNF bytes |
Observed generation status |
| Bridge |
No grammar |
N/A |
N/A |
Completed in 0.865 s |
| Bridge |
Focused |
18 |
590 |
Completed in 1.894 s |
| Bridge |
Expanded |
1,075 |
26,720 |
No completed text before 115 s timeout |
| Soap |
No grammar |
N/A |
N/A |
Completed in 0.333 s |
| Soap |
Focused |
15 |
522 |
Completed in 1.869 s |
| Soap |
Expanded |
1,077 |
26,766 |
No completed text before 115 s timeout |
What the comparison does establish: the focused grammars were much smaller as serialized text, all focused rewrites completed under the tested runtime, and these two expanded-grammar calls did not finish within the configured worker deadline despite actual GPU model offload. This makes grammar/runtime interaction worth examining if someone needs full-wordlist decoding.
What it does not establish: that a 1,075-form grammar is generally unusable, that the cost scales with byte size, that native parsing alone is responsible, or that another model, quantization, grammar or backend would behave the same way. Both broad workers entered the generation path, but no completed output or phase-level timing was recorded. The 115-second limit is a censored worker wall-time observation, not a measured successful generation latency.
build_gbnf serializes alternatives; the native parser initializes grammar state; the sampler filters viable tokens; and the model runs its forward pass. These stages have different costs. GBNF byte size alone does not identify the slow one.
The official llama.cpp GBNF guide documents grammar performance pitfalls, and issue #4218 discusses grammar-sampling optimization. They are related context, not a confirmed root cause for this particular JamePeng/Gemma run. A separate issue about large JSON Schema enums concerns schema-to-grammar conversion in another path; my slow requests used smallwords’ directly generated GBNF instead. I would avoid equating those two entry points.
A small measurement ladder could answer where additional engineering matters:
- No model: time
spec.allowed_words() and build_gbnf, then record the number of forms, bytes, rules, and alternatives.
- Native grammar parser: time the grammar object’s construction (
LlamaGrammar.from_string in bindings exposing that API). Note that one accepted grammar may still cost more to initialize than another.
- One fixed model: measure time to the first generated token with a short output cap. This checks setup/first-token work, not steady-state token throughput.
- Several complete outputs: measure prompt processing, generation count, per-token latency and wall time separately, with controlled output shape and identical prompt where feasible.
- Only if needed: compare alternative grammar constructions or a second runtime while keeping the permitted output language and tokenizer constant as far as possible.
Intermediate vocabulary sizes, repetitions, controlled token counts and exact backend versions are needed before inferring a performance curve. No WordlistSpec redesign is required to start measuring.
The practical default remains task-focused subsets, broadened only when the task needs additional expressive vocabulary.
4. Vocabulary validity versus preservation of the source meaning
All four focused English completions were valid under their chosen vocabulary and output shape. The important distinction is that valid is not the same as faithful to the input. The latter was not a guarantee made by smallwords; it is an application-level question that becomes especially visible when a user selects a tiny task-focused vocabulary.
Here are the actual focused results and the relevant information to preserve:
| Task |
Focused generated sentence |
Reading of this one example |
| Bridge |
A bridge is a bridge to getting people to a river to be wet. |
The original said the bridge permits crossing without getting wet. This distinction is lost or reversed. |
| Soap |
Wash hands with soap and water to clean dirt before you and before you. |
Some cleaning content survives; the before eating condition is missing and the sentence repeats itself. |
| Steam |
Sun light heat makes some water turn steam. |
Awkward English, but the heating/change relationship is approximately recoverable. |
| Lamp |
The lamp is not on because the switch is off. |
Both negation and the causal relation are retained. |
The original Soap sentence was Washing hands with soap and water removes dirt before eating. Its focused wordlist omitted eat and eating. Bridge’s list omitted without and not. The Steam list did have the necessary heat/water/steam concepts, and Lamp’s list included not and because. That contrast suggests a more informative first diagnosis than simply “the constrained model failed”: does the allowed vocabulary contain some way of expressing every required source fact?
For short rewriting tasks, the minimum fact check can be informal and transparent. Look for negation; who or what acts; causal relationships; time order; quantities; named entities; and relationships that could change truth conditions. Not every source word must be retained, and a synonym can be sufficient. But if neither the original term nor any sensible permitted paraphrase exists, the model is working under an underexpressive contract even when the sampler follows it perfectly.
The cheapest follow-up here would be two matched interventions:
Bridge: retain the original focused set, add a permitted way to negate wetness
(for example, "not" or "without").
Soap: retain the original focused set, add a way to name eating
(for example, "eat" or "eating").
Then keep the source sentence, task instruction, output shape, model, quantization and decoding settings fixed, apart from the deliberately updated wordlist and any prompt section generated from it. If the facts survive after adding the critical words, the earlier omission becomes a plausible contributing factor, not a proven sole cause: the allowed choices and the sampler both changed. If the facts remain absent despite being expressible, generation behavior becomes a stronger separate hypothesis. I have not run these patched-vocabulary conditions, so this is a proposed discriminating test, not a claim of improvement.
For meaning-sensitive applications, report vocabulary/shape compliance, preservation of required facts, and linguistic clarity separately. A few explicit source predicates can be more revealing than a single lexical-overlap score.
I would keep semantic evaluation outside the core lexical guarantee unless users ask for it as a distinct feature. A shared wordlist is precisely testable; whether a paraphrase preserves every important implication is less determinate and task-specific. Keeping those responsibilities separate supports rather than weakens the idea of an inspectable contract.
5. JSON Schema, additional shapes, and cross-validator agreement
The present project already combines OutputShape with WordlistSpec, supports constrained line counts, optional punctuation, line prefixes and fixed wrappers such as PLAN/FINAL, and emits a strict one-property JSON Schema. I would not describe arrays or multi-field output as necessary to make the current design useful. Their value depends on a downstream consumer.
A reasonable conditional set of choices is:
| Consumer need |
Minimal output decision |
| One short human-readable answer |
Keep the current text contract |
| One string inside a structured response |
Keep the existing single-key JSON object |
| A list of independently displayed or retried sentences |
Consider an optional bounded string array, validating each element |
| Named pieces such as summary and explanation |
Consider a small fixed object, with each field bound to the same or an explicitly selected wordlist |
| Arbitrarily nested records |
Treat as a separate structured-output use case, not an automatic extension |
For arrays, validate each string element; let serialization rules handle brackets and item counts. If fields have different wordlists, declare that explicitly rather than implicitly combining them.
A real cross-engine boundary from an earlier, separate test
The single-contract goal also raises a practical question: do consumers of the generated contract agree? In an earlier offline test with the pinned source and Python jsonschema 4.26.0, this minimal case differed:
Input text: "go\n" (one allowed word followed by an unexpected final newline)
Python jsonschema using the generated ^...$ pattern: accepted
smallwords complete-output validator: rejected
ECMAScript regex control: rejected
This is from a separate offline validator comparison, not the Gemma 4 GPU run. The difference follows from regex-anchor semantics: under certain Python matching operations, $ matches just before a final newline, while a full-string check rejects the extra character. The JSON Schema ECMA-262 test cases cover this type of portability issue, and the JSON Schema regex guidance discusses cross-engine assumptions.
A second small case concerned digit classes. The direct GBNF path uses ASCII [0-9]+, while the generated regular-expression pattern can use \d+. Python regex matching may accept non-ASCII decimal digits for \d, even when the native grammar and complete validator use ASCII-only semantics. In our earlier checks, this produced a Python JSON Schema versus complete-validator disagreement for full-width digits. Whether that is a bug depends on the intended number policy; the unintended difference is the useful finding.
These observations concern specific validator engines. A shared compiler reduces rule-authoring drift, while downstream regex engines can still disagree about acceptance.
A small cross-surface acceptance matrix would be especially aligned with the project’s original aim. Pick a specific WordlistSpec and OutputShape, declare what each string should mean, then compare:
- expanded permitted surface forms;
- the direct native GBNF generation/acceptance path;
- the generated JSON Schema under a named validator and version;
- the complete
validate_output verdict and its OOV diagnostics.
The highest-value fixtures are small: a legal word, forbidden punctuation, terminal newline, case variant, explicit café, explicit 東京, ordinary ASCII digits, and non-ASCII decimal digits if numbers are enabled. Normalization and Japanese segmentation tests can remain optional until their desired semantics have been chosen. A positive test alone is insufficient; include a few strings that must be rejected. Ideally, a valid literal should not simultaneously appear in the same report as an OOV error unless the API explicitly defines those as independent statuses.
Tiny source-level fixture
For example, the pinned public API supports a minimal contract like this:
from smallwords import OutputResources, OutputShape, WordlistSpec
spec = WordlistSpec(
name="tiny",
words=("go", "now"),
variant_mode="surface_only",
allow_capitalized_words=False,
allow_newlines=False,
allowed_punctuation=(".",),
)
shape = OutputShape(min_words_per_line=2, max_words_per_line=2, max_lines=1)
resources = OutputResources.from_wordlist(spec, shape=shape)
for text in ("go now.", "go now?", "go now.\n", "Go now."):
result = resources.validate(text)
print(repr(text), result.valid, result.out_of_vocab, result.issues)
schema = resources.json_schema()
grammar = resources.gbnf
This is an illustrative fixture composed against the pinned API, not a claim that this exact snippet was included in the GPU run. Its value is in specifying the intended pass/fail outcomes first, then exercising those outcomes in each relevant consumer. If the schema is only advisory, documenting an engine limitation may suffice. If a downstream service uses that schema as its final acceptance gate, tighter parity testing is more important.
These small tests do not require a universal adapter. Any engine-specific workaround can still derive from the shared policy.
6. A conditional troubleshooting map for future users
The appropriate next check depends on the failure:
A non-English output is not working:
A directly specified Unicode literal cannot be generated:
Inspect the emitted GBNF, native parser, tokenizer and backend version.
A literal generates, but task words were not added:
Inspect extraction and any chosen normalization or segmentation policy.
The literal is valid, but OOV diagnostics disagree:
Align diagnostic tokenization with the declared permitted surface forms.
These all work, but natural-language quality is poor:
Test vocabulary expressibility and the model's generation separately.
A large wordlist is slow:
build_gbnf itself is slow:
Profile word-family expansion and serialization, offline.
Native grammar-object creation is slow:
Profile parse/init, grammar structure and runtime revision.
First token stalls:
Isolate initial viable-token calculation and model-prefill time.
Every generated token is slow:
Inspect repeated token-mask cost and grammar state progression.
Only one backend is affected:
Compare the same grammar and model/tokenizer on another backend.
A consumer requests another output format:
It only needs one answer:
Keep the simple text or single-key JSON default.
It needs separate sentences or fixed named fields:
Consider an opt-in shape with per-value contract validation.
It needs arbitrary nested data:
Treat that as an explicit larger scope decision.
A reusable minimal reproduction can record the package revision, WordlistSpec, OutputShape, generated resource, input or candidate output, expected and observed result, and validation-engine identity. A runtime performance report needs model/GGUF revision and hash, actual GPU/backend logs, token counts, grammar size, elapsed phase timings and timeout behavior. It is useful to distinguish no completed answer before the timeout from a model-generated empty answer.
This is also why a literal-only Unicode smoke test is different from testing fluent Japanese, and why a one-token startup check is different from a meaningful decode-throughput comparison. The small cheap tests establish their own contracts before anyone needs a large-model environment.
7. Related projects and reference links
For follow-up work, these sources have different roles:
These references are pointers for independent checks, not claims that similar reports share a root cause. Pin the relevant version and preserve the smallest working or failing input before comparing implementations.
None of these observations requires turning smallwords into a multilingual NLP framework, a universal schema generator, or a semantic evaluator. The one-spec approach remains the useful organizing boundary. The most economical follow-ups would be one Unicode diagnostic regression test, a small cross-validator acceptance table, and, if larger vocabularies matter to users, a phase-separated grammar timing check. For meaning-sensitive rewrites, a separate expressibility check before shrinking the allowed words is likely more useful than treating every contract-valid sentence as a faithful paraphrase.