Skip to content

Allow new lines during JSON generation - #1277

Merged
merrymercy merged 4 commits into
sgl-project:mainfrom
qeternity:json-fixes
Sep 1, 2024
Merged

merrymercy merged 4 commits into
sgl-project:mainfrom
qeternity:json-fixes

Conversation

@qeternity

Copy link
Copy Markdown
Contributor

Motivation

By default, Outlines does not permit new lines and whitespace formatting during constrained JSON generation. Their rationale is that smaller models have a tendency to enter infinite generation loops otherwise. I have not observed this behavior with any recent smaller models (Llama 3.1 8B and Mistral 7B v3) rather we instead find material quality degradation, even with larger models (Llama 3.1 70B and Mistral Large 2) particularly when the JSON property is a list, and the number of elements is variable.

If you observe the natural generation behavior of these models, they emit syntactically formatted JSON and it strikes me a as a better default to permit such behavior.

Modifications

Modify the default Outlines whitespace regex to permit newlines and additional whitespace.

@max99x

max99x commented Aug 31, 2024

Copy link
Copy Markdown
Contributor

While this change doesn't impact the issue, one thing to note is that with non-constant whitespace like the regexes generated from schemas or pydantic models, the jump-ahead optimization ends up doing nothing. Having predefined spacing (pretty-printed or compressed) will run much faster. If that reduces quality/accuracy, instructing or fine-tuning models to produce either standard pretty-printed or compressed formatting can help.

@qeternity

qeternity commented Aug 31, 2024 •

Copy link
Copy Markdown
Contributor Author

Is it truly the case that it would do nothing? It definitely seems that it would increase the number of inter-jump-ahead tokens but ultimately once the model has completed whitespace generation, it would still kick in? I have not dug into the implementation, and we are just now starting to evaluate the performance impact. Will report back with empirical results.

That said, I can strongly attest to the fact that restricted whitespace generation greatly reduces quality of larger SOTA models (we have tested basically everything short of L3 405). Ideally of course the jump-ahead would be pretty print aware, but at the very least is seems reasonable to expose a quality vs performance tradeoff to users. The alternative is to make this a per-request parameter, which seemed less desirable to us at first glance.

@max99x

max99x commented Aug 31, 2024

Copy link
Copy Markdown
Contributor

It's true that jump-ahead will still kick in for field names, etc., but it is common for whitespace to account for a large chunk of the generated tokens. I'm a user, not an sglang developer, so they may have more insight, but in our usage we've seen 30%+ speed increase from using fixed spacing in JSON regexes.

FWIW, for our use case we ended up ditching JSON generation and instead use a free-text user/assistant chat structure that asks for the relevant fields (sometimes in parallel forks) and composing the JSON from the output ourselves, and at least for smaller models we've gotten much better quality output that way.

@qeternity

Copy link
Copy Markdown
Contributor Author

Yes, this very much I agree with and it's been well studied that JSON generation reduces overall quality (observed on 4o and 3.5 Sonnet). Constrained generation is still very much a trade off, but what we have found is that prompting to "build a list" to elicit data extraction followed by a constrained generation phase is the happy medium.

@merrymercy
merrymercy merged commit 32a4141 into sgl-project:main Sep 1, 2024
qeternity added a commit to qeternity/sglang that referenced this pull request Sep 1, 2024
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 9, 2026
… the plan's PIECES, not on whole storage

Operator ruling 2026-09-09 (SECTION 1af / sgl-project#1277): the exchange's unit under
P=PP3 / D=TP3 was never 'the same tensors on the same card' -- it is the
SUB-TENSOR OVERLAP. The layer resident WHOLE on card n in P CONTAINS
D-rank-n's TP shard of that layer, and sgl-project#1277 measured exactly that as the
diagonal: 10.285 GiB on-card (35.7 %) against 18.560 GiB cross-card, byte-exact.

So card_geometry_digest (name:tag:rows x cols x itemsize over WHOLE storage) is
the wrong predicate for asymmetric placement -- it MUST differ between a
stage-holder and a shard-holder. Boot weg2shadowE measured it doing so (six
distinct card_digests, no co-located pair agreeing) and refusing all 12 legs of
a lane that has real bytes to compare.

THE GATE NOW COMPARES THE ON-CARD PIECE SET. oncard_piece_digest() hashes the
pieces the PLAN assigns to a card's pair -- keyed on XchgDesc.key(), the
pointer-free identity (tag, name, src/dst rank, kind, bytes, rows, run,
pitches, OFFSETS, pieces) the plan id itself is built from, sorted so two
processes building the list in different orders still agree. Reusing that key
is the upstream-minimal choice: one identity for a piece, not a second one.

RANK-UNIFORMITY, pinned: the set comes from LegPlan.descs and the card index --
the group-uniform derivation -- never from a rank-local tensor walk. That is
precisely what lets a stage-holder and a shard-holder produce the SAME number
for the same card while their storage digests differ.

The row layout is UNCHANGED (still <9Q); the ninth slot's NAME and CONTENT
change from card_digest to piece_digest. The whole-storage digest survives as
an INFORMATIONAL field on the plan line and is never gated again.

NO OVERLAP IS NOW NAMED: a pair the plan assigns no on-card pieces gets
reason=no-oncard-pieces via rank_local_skip_message, never a silent
pieces=0 ran=no. W64 keeps its job under field=piece_digest and carries a hint
naming this side's first planned piece (only this side's list is in-process;
the peer publishes a digest, so a real diff is not available and is not faked).

THE CHEAP EVIDENCE, added as asked: WEG2-XCHG-SHADOW PARAM-CENSUS logs
group/rank/param-count/first/last name ONCE PER PROCESS at the first hook, so
the pp/tp asymmetry is read off the boot log instead of off launcher.py.

Tests: red-first in the same commit (the ruling's fixture, with the OLD
predicate asserted as the explicit can-fail); 26 pre-existing callers carried
onto the renamed kwarg. 1707 (+5), NEW 0 vs 52de4e3 on cachyllama.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 10, 2026
…d bounded by the WIDEST layer

USER LAW 2026-09-11, verbatim: "notfalls wird das layer auf einem (vertretbar
kleinen) hostpuffer vollstaendig zusammengesetzt und jede karte nimmt sich von
dem was er braucht (oder ihn komplett). die 27gb (oder so aehnlich) an
layerbytes muessen nicht mehr dauerhaft im systemram gehalten werden. das ist
das ziel." Design note: WEG2_REUSE_SPEC_0908.md section 10.

WHAT THIS REPLACES, and it is an acceptance change before it is a code change:
the slice was carrying `agreed_count > 0` -- a COUNT. The law names a SIZE. The
quantity is the ledger's own `RUN MOMENT = the host weights term`, measured
42.96 GiB on boot weg2xsn8 (f03e405): a region preallocated at Sigma H that
the legs copy THROUGH, charged once and never shrinking for the life of the
boot. That is the permanent residency the law forbids, and the slice is done
when it reads 0.00 with a bounded buffer in its place -- not when Sigma H is
merely smaller.

NEW MODULE `weg2/xchg_bounce.py`, pure: no allocation, no device, no env.

    buffer  = widest_layer_bytes * depth
    staging = pairs * SLOTS_PER_PAIR * slot_bytes
    bounce  = buffer + staging

THE BOUND IS THE WIDEST LAYER, NEVER THE MEAN, and that is the danger direction
of the whole slice. `bytes_per_direction / n_layers` is the right term for
sizing the steady STREAM and the wrong one for the REFUSAL: a boot sized on the
mean dies on whichever layer is above it. Both are carried; only the max sizes
the buffer. An ABSENT `widest_layer_bytes` raises rather than falling back to
the mean -- "absent" must not silently un-bound the bound.

NEVER PINNED. Every term is read from the boot and the derivation is PRINTED
(`BounceTerms.expression()`), because a total alone is indistinguishable from a
constant. This rig's instance, from the plan's own halves
(oncard 10.28 + cross 16.84 = 27.12 GiB -- which IS the user's "27gb an
layerbytes") over 64 layers at --pp-stage-ratio 32,18,14:

    one layer group-wide    433.9 MiB
    buffer, depth 2         867.8 MiB
    staging 6x2x64 MiB      768   MiB
    bounce total           1.60 GiB   against Sigma H 42.96 -> 41.37 released, 26.9x

THE THREE OPERATOR JUDGEMENTS, carried with their reasons so they survive:
* SLOT_BYTES 32 -> 64 MiB: sgl-project#1277 measured 64 MiB DOUBLE-buffered at 99 % of the
  link ceiling. E2's "32/64/128 indistinguishable" was measured on the SINGLE-
  buffered form, so quoting it here would be an instrument reused outside the
  arm it was measured on.
* depth 2, not 3: depth 2 buys the assemble/copy-out overlap; a third layer
  buys nothing once the x4 link saturates and costs another whole layer.
* the refusal bound is the widest layer, above.

REFUSALS: `Weg2XchgBounceUnderCovered` + `under_coverage_refusal()` in W71's
CODE and shape -- it is "the residency this arm needs is not arm-able", which
W71 already names, so no new code is taken. It fires at ARM time, before either
group starts, for W71's own reason: a refusal that arrives mid-flip arrives
after VRAM has been mutated. The other two are the existing paths, unchanged:
W20 for a buffer the ledger cannot fund (the `xchg_bounce_host_bytes` hull has
been on the branch since 2afbecf and is pinned here as CHARGED, not merely
accepted), W74 for a destination slice the assembled layer does not cover.

ARM LINE now carries BOTH residencies in ONE grep: `host_weights=` beside
`xchg_bounce=`. Sigma H is also on the TERMS line, but that is a different line
and a reader comparing two lines can mismatch two boots. They are never folded
into one figure -- a single number carrying both would make the transition this
slice exists to prove unobservable.

RED-FIRST, proven in a clean worktree at f03e405: collection ERROR, the
module does not exist. GREEN here 11/11.
FIVE MUTANTS, all red, baseline green after each:
  M1  buffer sized on the MEAN                       3 failed
  M2  depth default raised to 3 unpriced             2 failed
  M2b coverage grades the WHOLE buffer, not a slot   1 failed
  M3  the bounce not added to the total (unbooked)   3 failed
  M4  slot reverts to 32 MiB (E2's arm, wrong lane)  2 failed
M2b IS A TEST GAP I FOUND AND CLOSED, not a mutant that merely passed: at
`buffer = widest * depth` the per-slot and whole-buffer comparisons AGREE, so
the first cut of this file could not tell them apart. The discriminating case
is a buffer big enough in total and too small per slot -- which is exactly what
an assembly writes into.
Local, hermetic, CVD="" throughout; box verified free first (1 MiB x3, no
launch_server). ruff clean.

STEPS 3-6 ARE NOT IN THIS COMMIT: no transport, no assembly, no streaming
order. Path (b) is deliberately NOT half-wired -- see section 10's HANDOVER
block for the exact boundary.
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.

3 participants