Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 52 additions & 49 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,68 @@

## [0.3.4] — 2026-11-18 (stable)

Two decoding-side fixes land on the shared_first serving path, measured on the
shipped 50M en-zh SFT checkpoint and on four matched 30-min 15M arms (base,
plain depth-1, `per_iteration` KV, aux-losses-off). No kernel code, no
retraining, no behaviour change for callers that leave `repetition_penalty=1.0`.
One decoding-side fix lands on the shared_first serving path. Default
behaviour is unchanged when callers leave `repetition_penalty=1.0`.

### Fixed
- `chronos.runtime.speculative.speculative_generate` now accepts
`repetition_penalty: float = 1.0`, applied CTRL-style on the raw logits
before every draft and verify step. Because both distributions see the same
penalty on the same `seen` set, speculative rejection sampling still draws
exactly from the full-depth target (Leviathan et al. 2023).
(divide a positive logit, multiply a negative one) inside both `pick`
(draft) and the greedy verify step. The seen set is the full emitted
sequence, rebuilt per call because the KV cache is truncated on
rejection. With the same penalty on the same seen set, speculative
rejection sampling still draws exactly from the full-depth target
(Leviathan et al. 2023); greedy draft and greedy verify also stay in
agreement, which they did not under 0.3.4 as first published.
- `chronos.serving.runtime.generate_stream` and
`chronos.serving.adapter.ChronosServingAdapter.generate` pick the kwarg up
from OpenAI (`repetition_penalty`) and Ollama (`repeat_penalty` under
`options`, falling back to `repetition_penalty` at either nesting). The
default stays 1.0.
- On the shipped 50M en-zh SFT checkpoint, greedy decoding with
`repetition_penalty=1.15` lifts 60-token `unique_ratio` from 0.129 to 0.553
and cuts `max_4gram` from 8.83 to 3.42. Combined with the auto-depth fix
below, `unique_ratio` reaches 0.692 and `max_4gram` falls to 2.33.
`chronos.serving.adapter.ChronosServingAdapter.generate` pick the kwarg
up from OpenAI (`repetition_penalty`) and Ollama (`options.repeat_penalty`
or `repetition_penalty` at either nesting). Default 1.0.

### Added
- `chronos.serving.runtime.auto_select_inference_depth`. At load time, if the
checkpoint carries a trained `dt` schedule and `max_inference_depth` is not
set, the runtime picks the largest depth `d` whose cumulative Euler step
`sum(dt[:d]) ≤ 1.15`. This keeps the iterated map inside the Lipschitz
region `L ≤ 1` where the recurrent core contracts. Measured on the 50M CPT
checkpoint (trained `dt_sum = 1.825`), the selector picks `d = 3`
(`cum_dt = 1.108`), which was the measured sweet spot in a four-step depth
sweep.
- `chronos.model.config.ChronosConfig.auto_inference_depth` (default `True`)
to opt out per checkpoint. Environment variable
`CHRONOS_AUTO_INFERENCE_DEPTH=0` is the same opt-out at process scope.
- `max_inference_depth` added to `INFERENCE_OVERRIDE_KEYS`; an explicit
override wins over the auto-pick. The chosen value is logged under
`inference_overrides.auto_inference_depth = {chosen, trained_dt_sum,
cum_dt_at_chosen, limit}`.
- `max_inference_depth` added to `INFERENCE_OVERRIDE_KEYS`, so a caller
can run the recurrent loop at a shallower depth than the one the model
was trained with. This is a manual override: pass
`inference_overrides={"max_inference_depth": d}` to `load_model`.

### Experiments
- `experiments/loop_depth_15m/results_abc/` — five 30-minute 15M arms
(base, A_dtcap, B_plain, C_periter, obj_lm), each with its `.pth`,
`metrics.jsonl`, probe JSON, and a final findings file. Headline numbers:
base valid_ce 4.735, B_plain 4.528 (depth 1 wins per-second at this budget),
C_periter 4.727 with max_4gram 10.7 (cleanest decoding but 4× KV memory
and no inference-time depth override), obj_lm 4.533 (every non-structural
auxiliary loss zeroed: large CE win but `dt_sum` drifts to 1.858, at the
Lipschitz edge, confirming that `stability` and `distill` coefficients
anchor the schedule).
### Measured — 30M bilingual CPT checkpoint (step 3559, `latest.state.pkl`)
Greedy decoding, 60 new tokens, 12 EN/ZH prompts, averaged.

| config | unique_ratio | max_run | max_4gram |
|---|---:|---:|---:|
| as-trained d=4, no penalty | 0.129 | 1.25 | 8.83 |
| manual `max_inference_depth=3`, no penalty | 0.220 | 6.25 | 9.58 |
| d=4 with `repetition_penalty=1.15` | 0.553 | 1.58 | 3.42 |
| d=3 with `repetition_penalty=1.15` | 0.692 | 1.17 | 2.33 |

These figures are from the 30M CPT run described in `run_spec.json` on the
author's local machine; the shipped 50M en-zh SFT demo model is a
different checkpoint and is not measured here.

### Known not-fixed
- Factual recall quality on the shipped 50M SFT checkpoint is not changed by
these decoding fixes. 60-token greedy with `repetition_penalty=1.15` still
produces "Paris is the capital of the United States" and "水的沸点是水中水".
The remedy is more data and more tokens, not a kernel knob.

### Internal
- `/tmp/chronos_scripts/probe_arm.py`, `probe_depth_sweep.py`,
`probe_sampling.py`, `probe_repetition.py`, `compare_arms.py` — probes used
for the ABC runs; kept out of the shipped package.
- Factual recall is not affected by these decoding changes. On the 30M
CPT checkpoint at d=4 the model continues "Paris is the capital of"
with "the United States"; with `repetition_penalty=1.15` at d=3 it no
longer loops but instead produces a different unrelated completion.
The remedy is more data and more tokens, not a decoding knob.
- 0.3.4 first-publish regression: an earlier draft of this release added
an `auto_select_inference_depth` helper that read `step_sizes` from
`ChronosConfig`, where it is not stored (the trained schedule lives on
`recurrent_controller.step_sizes` in the state dict). That helper
no-opped on every real load and has been removed in this release.
The companion `kernel.auto_inference_depth` flag is likewise removed.

### Experiments
- `experiments/loop_depth_15m/results_abc/` — five 30-minute 15M arms
(base, A_dtcap, B_plain, C_periter, obj_lm) that motivated the fix.
Headline numbers from the arms' own `arm_<label>.json`:
base valid_ce 4.735, A_dtcap 4.768 (dt_max=0.5 under-steps the
recurrence), B_plain 4.528 (depth 1 wins per-second at this budget),
C_periter 4.727 with greedy `max_4gram` 10.67 (cleanest decoding, but
the per_iteration KV layout costs 4× KV memory and disables both
inference-time depth override and speculative decoding), obj_lm 4.533
(every non-structural auxiliary loss zeroed: large CE win on this
recipe; the measured depth-4 `dt` schedule is higher than base's).

## [0.3.3] — 2026-11-14 (stable)

Expand Down
5 changes: 0 additions & 5 deletions chronos/model/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,6 @@ def __init__(self, **kwargs):
"recurrent_gradient_checkpoint_groups", False
)
self.max_inference_depth = kwargs.pop("max_inference_depth", None)
# 0.3.4: at load time the runtime picks ``max_inference_depth`` from the
# trained ``dt`` schedule so the iterated map stays inside ``L≤1`` (see
# ``chronos.serving.runtime.auto_select_inference_depth``). Set to
# False on a checkpoint whose trained ``dt`` was intended to overshoot.
self.auto_inference_depth: bool = bool(kwargs.pop("auto_inference_depth", True))
# 5-D [B,S,K,L,E] prediction is enabled by v2 presets. Keeping the
# switch explicit lets depth=1 legacy checkpoints retain their public
# 4-D output contract until migrated.
Expand Down
7 changes: 6 additions & 1 deletion chronos/runtime/speculative.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,12 @@ def emit(tok):
for i in range(1, len(draft)):
row, tok = logits[i - 1], draft[i]
if not do_sample:
target = int(torch.argmax(row))
# Compare under the same rule the draft used: argmax after the
# CTRL penalty on the tokens emitted up to this verify position.
# Without this, penalty > 1 would make draft and verify disagree
# on every seen token and acceptance would collapse.
penalized = _apply_rep_penalty(row, _seen_vec(), penalty) if penalty != 1.0 else row
target = int(torch.argmax(penalized))
ok = target == tok
correction = target
else:
Expand Down
79 changes: 3 additions & 76 deletions chronos/serving/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,68 +54,13 @@ def _pick_device(requested: str | None) -> str:

# Inference-only options a server may override on a loaded checkpoint.
# None of them changes the trained weights; all are validated by ChronosConfig.
# ``max_inference_depth`` is exposed so a caller can run the recurrent loop at
# a shallower depth than it was trained with (useful on checkpoints whose
# trained ``dt`` drifted, where a manual depth drop reduces repetition).
INFERENCE_OVERRIDE_KEYS = ("kv_cache_dtype", "kv_quant_group_size", "mla_decode", "mla_cache_rope",
"router_scope", "max_resident_experts", "ram_budget_mb",
"max_inference_depth")

# Cumulative Euler-step budget for the auto depth selector.
# Repetition minimises at cum_dt ≈ 1 on both the 15M arms and the live 50M
# CPT checkpoint; 1.15 is the shoulder — beyond it the iterated map starts to
# amplify (measured regression at 1.8). See experiments/loop_depth_15m/results_abc.
AUTO_DEPTH_DT_LIMIT = 1.15


def _effective_dt(config) -> list[float] | None:
"""Return per-group effective ``dt`` after the sigmoid, if the checkpoint
exposes a trained schedule. ``None`` means "no data; skip auto-depth".
"""
sizes = getattr(config, "step_sizes", None) or getattr(config, "trained_step_sizes", None)
if not sizes:
return None
try:
dt_min = float(getattr(config, "recurrent_dt_min", 0.0) or 0.0)
dt_max = float(getattr(config, "recurrent_dt_max", 1.0) or 1.0)
except (TypeError, ValueError):
return None
mode = str(getattr(config, "recurrent_dt_param", "sigmoid") or "sigmoid").lower()
out: list[float] = []
import math
for raw in sizes:
try:
r = float(raw)
except (TypeError, ValueError):
return None
if mode == "sigmoid":
s = 1.0 / (1.0 + math.exp(-r))
out.append(dt_min + (dt_max - dt_min) * s)
else: # ``clamp`` or unknown: treat as already in [dt_min, dt_max]
out.append(min(dt_max, max(dt_min, r)))
return out


def auto_select_inference_depth(config) -> int | None:
"""Pick the largest ``d`` with cumulative trained ``dt[:d] ≤ AUTO_DEPTH_DT_LIMIT``.

Returns the chosen depth, or ``None`` if the checkpoint does not carry a
usable schedule (unsniffable or not recurrent). The caller writes the
choice onto ``config.max_inference_depth`` and records it for logging.
"""
depth = int(getattr(config, "recurrent_depth", 1) or 1)
if depth <= 1 or not bool(getattr(config, "recurrent_enabled", True)):
return None
dts = _effective_dt(config)
if not dts or len(dts) < depth:
return None
cum = 0.0
chosen = 1
for i in range(depth):
cum += float(dts[i])
if cum <= AUTO_DEPTH_DT_LIMIT:
chosen = i + 1
else:
break
return chosen


def apply_inference_overrides(config, overrides: dict | None) -> dict:
"""Set validated inference options on ``config``; return what was applied."""
Expand Down Expand Up @@ -173,24 +118,6 @@ def load_model(path: str, *, name: str | None = None, device: str | None = "auto
meta_full = json.load(open(cfg_path, encoding="utf-8"))
config, _sources = chronos_config_from_checkpoint(path)
applied = apply_inference_overrides(config, inference_overrides)
# Auto-pick max_inference_depth from the trained dt schedule if the user
# did not force one and the opt-out is not set. Opt-out: ``kernel.auto_
# inference_depth=False`` on the checkpoint config, or env
# ``CHRONOS_AUTO_INFERENCE_DEPTH=0``.
env_off = str(os.environ.get("CHRONOS_AUTO_INFERENCE_DEPTH", "")).lower() in ("0", "false", "no")
cfg_on = bool(getattr(config, "auto_inference_depth", True))
if ("max_inference_depth" not in applied) and cfg_on and not env_off:
chosen = auto_select_inference_depth(config)
if chosen is not None and chosen < int(getattr(config, "recurrent_depth", 1)):
config.max_inference_depth = chosen
dts = _effective_dt(config) or []
applied["max_inference_depth"] = chosen
applied["auto_inference_depth"] = {
"chosen": chosen,
"trained_dt_sum": round(sum(dts[: int(config.recurrent_depth)]), 4) if dts else None,
"cum_dt_at_chosen": round(sum(dts[:chosen]), 4) if dts else None,
"limit": AUTO_DEPTH_DT_LIMIT,
}
tok_dir = _find_tokenizer_dir(path, meta_full)
tokenizer = PreTrainedTokenizerFast.from_pretrained(tok_dir)
device = _pick_device(device)
Expand Down
143 changes: 71 additions & 72 deletions tests/test_0_3_4_decoding.py
Original file line number Diff line number Diff line change
@@ -1,81 +1,80 @@
"""0.3.4 decoding-side fixes.

Guards two shipped behaviours:
1. ``repetition_penalty`` threads through speculative_generate / generate_stream
and matches the CTRL rule on the raw logits.
2. ``auto_select_inference_depth`` returns the sweet-spot depth for a trained
schedule, and the runtime does nothing when the schedule is unknown or
the opt-out is set.
"""
"""0.3.4 decoding: repetition_penalty through speculative decoding and serving."""
from __future__ import annotations

import math
import os
import types
import sys

import pytest
import torch


def test_apply_rep_penalty_is_ctrl_rule():
from chronos.runtime.speculative import _apply_rep_penalty
logits = torch.tensor([2.0, -1.0, 0.5, -0.5, 3.0])
seen = torch.tensor([0, 2, 2]) # unique={0,2}
out = _apply_rep_penalty(logits, seen, 2.0)
assert torch.allclose(out, torch.tensor([1.0, -1.0, 0.25, -0.5, 3.0]))
assert torch.allclose(_apply_rep_penalty(logits, seen, 1.0), logits) # no-op
assert torch.allclose(_apply_rep_penalty(logits, torch.tensor([], dtype=torch.long), 2.0), logits)


def test_apply_rep_penalty_negative_rejected():
from chronos.runtime.speculative import speculative_generate
import pytest
# Exercised via speculative_generate's own validation; call directly for speed.
sys.path.insert(0, os.path.dirname(__file__))

from chronos.model.model_chronos import apply_repetition_penalty # noqa: E402
from chronos.runtime.speculative import _apply_rep_penalty, speculative_generate # noqa: E402
from test_speculative import model_for # noqa: E402


def penalized_greedy_reference(model, ids, n, penalty):
"""Plain full-depth greedy decode with the CTRL penalty, token by token."""
out = model(ids, use_cache=True)
cache, seq = out.past_key_values, ids[0].tolist()
for _ in range(n):
row = apply_repetition_penalty(out.logits[:, -1], torch.tensor([seq]), penalty)
nxt = int(row[0].argmax())
seq.append(nxt)
out = model(torch.tensor([[nxt]]), past_key_values=cache, use_cache=True)
cache = out.past_key_values
return seq


def test_apply_rep_penalty_matches_kernel_helper():
torch.manual_seed(0)
logits = torch.randn(96)
seen = torch.tensor([3, 7, 7, 40, 95])
ours = _apply_rep_penalty(logits, seen, 1.3)
ref = apply_repetition_penalty(logits[None], seen[None], 1.3)[0]
assert torch.allclose(ours, ref)
assert torch.equal(_apply_rep_penalty(logits, seen, 1.0), logits)


@pytest.mark.parametrize("gamma,draft_depth", [(1, 1), (4, 1), (3, 2)])
def test_greedy_speculative_with_penalty_equals_penalized_greedy(gamma, draft_depth):
model = model_for("shared_first")
ids = torch.tensor([[5, 9, 2, 17]])
ref = penalized_greedy_reference(model, ids, 24, 1.3)
out, _ = speculative_generate(model, ids, max_new_tokens=24, draft_depth=draft_depth,
gamma=gamma, repetition_penalty=1.3)
assert out[0].tolist() == ref


def test_penalty_changes_greedy_output():
model = model_for("shared_first")
ids = torch.tensor([[5, 9, 2, 17]])
plain, _ = speculative_generate(model, ids, max_new_tokens=24, draft_depth=1)
pen, _ = speculative_generate(model, ids, max_new_tokens=24, draft_depth=1, repetition_penalty=2.0)
assert plain[0].tolist() != pen[0].tolist()


def test_sampled_speculative_with_penalty_runs_and_respects_budget():
model = model_for("shared_first")
ids = torch.tensor([[5, 9, 2, 17]])
gen = torch.Generator().manual_seed(3)
out, stats = speculative_generate(model, ids, max_new_tokens=16, draft_depth=1, do_sample=True,
temperature=0.9, repetition_penalty=1.2, generator=gen)
assert out.shape[1] == ids.shape[1] + 16
assert stats.generated == 16


def test_nonpositive_penalty_rejected():
model = model_for("shared_first")
with pytest.raises(ValueError, match="repetition_penalty must be > 0"):
speculative_generate.__wrapped__( # drop no_grad for a one-shot entry
model=types.SimpleNamespace(config=types.SimpleNamespace(recurrent_depth=1)),
input_ids=torch.zeros((1, 1), dtype=torch.long), repetition_penalty=0.0,
)


def _mk_cfg(sizes, dt_min=0.0, dt_max=1.0, depth=None, mode="sigmoid"):
cfg = types.SimpleNamespace()
cfg.step_sizes = sizes
cfg.recurrent_dt_min = dt_min
cfg.recurrent_dt_max = dt_max
cfg.recurrent_dt_param = mode
cfg.recurrent_depth = depth if depth is not None else len(sizes)
cfg.recurrent_enabled = True
cfg.auto_inference_depth = True
return cfg


def _inv(y): return math.log(y / (1 - y))


def test_auto_depth_picks_sweet_spot():
from chronos.serving.runtime import auto_select_inference_depth
# CPT-50M measured dt schedule
cfg = _mk_cfg([_inv(d) for d in [0.303, 0.414, 0.391, 0.717]])
assert auto_select_inference_depth(cfg) == 3 # cum_dt 1.108 ≤ 1.15


def test_auto_depth_leaves_safe_schedule_alone():
from chronos.serving.runtime import auto_select_inference_depth
cfg = _mk_cfg([_inv(0.14)] * 4) # cum_dt 0.56 at depth 4
assert auto_select_inference_depth(cfg) == 4


def test_auto_depth_handles_depth_one_and_missing_schedule():
from chronos.serving.runtime import auto_select_inference_depth
assert auto_select_inference_depth(_mk_cfg([0.0], depth=1)) is None
bare = types.SimpleNamespace(recurrent_depth=4, recurrent_enabled=True)
assert auto_select_inference_depth(bare) is None
speculative_generate(model, torch.tensor([[1, 2]]), max_new_tokens=2, repetition_penalty=0.0)


def test_auto_depth_respects_env_opt_out(monkeypatch):
from chronos.serving.runtime import auto_select_inference_depth
# Env opt-out doesn't change the selector itself (callers read the env),
# but ``auto_inference_depth=False`` on the config must suppress any pick.
cfg = _mk_cfg([_inv(d) for d in [0.5, 0.5, 0.5, 0.5]])
# Selector itself is pure; integration via load_model is covered by callers.
assert auto_select_inference_depth(cfg) == 2
def test_max_inference_depth_is_an_inference_override():
from chronos.serving.runtime import INFERENCE_OVERRIDE_KEYS, apply_inference_overrides
assert "max_inference_depth" in INFERENCE_OVERRIDE_KEYS
model = model_for("shared_first")
applied = apply_inference_overrides(model.config, {"max_inference_depth": 3})
assert applied == {"max_inference_depth": 3}
assert model.config.max_inference_depth == 3
Loading