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
62 changes: 62 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,67 @@
# Changelog

## [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`.

### 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).
- `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.

### 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}`.

### 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).

### 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.

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

Stable release. No kernel code changes beyond 0.3.3a1; this release bumps the version string and ships the final documentation set.
Expand Down
2 changes: 1 addition & 1 deletion chronos/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Project Chronos: On-device low-latency lookahead dual-layer MoE inference
__version__ = "0.3.3"
__version__ = "0.3.4"

# Register with HuggingFace AutoXXX factories so
# AutoModelForCausalLM.from_pretrained("path/to/chronos") works out of the box.
Expand Down
5 changes: 5 additions & 0 deletions chronos/model/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ 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
33 changes: 31 additions & 2 deletions chronos/runtime/speculative.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,23 @@ def as_dict(self) -> dict:
"tokens_per_s": round(self.generated / self.elapsed_s, 2) if self.elapsed_s else None}


def _apply_rep_penalty(logits: torch.Tensor, seen_ids: torch.Tensor, penalty: float) -> torch.Tensor:
"""CTRL rule, shape-agnostic: ``logits`` is 1D over vocab.

Applied on the raw logits *before* the draft and verify distributions, so
the two match on the same context and speculative rejection sampling
stays an exact sample from the full-depth target (Leviathan et al. 2023).
"""
if penalty == 1.0 or seen_ids.numel() == 0:
return logits
seen = torch.unique(seen_ids)
picked = logits[seen]
penalized = torch.where(picked < 0, picked * penalty, picked / penalty)
out = logits.clone()
out[seen] = penalized
return out


def _probs(logits: torch.Tensor, temperature: float, top_k: int, top_p: float) -> torch.Tensor:
logits = logits.float() / max(temperature, 1e-6)
if top_k and top_k > 0:
Expand Down Expand Up @@ -118,7 +135,8 @@ def rejection_step(p: torch.Tensor, q: torch.Tensor, token: int, generator=None)
def speculative_generate(model, input_ids: torch.Tensor, *, max_new_tokens: int = 128,
draft_depth: int = 1, gamma: int = 4, adaptive_gamma: bool = True,
gamma_max: int = 8, do_sample: bool = False, temperature: float = 1.0,
top_k: int = 0, top_p: float = 1.0, eos_token_id=None,
top_k: int = 0, top_p: float = 1.0, repetition_penalty: float = 1.0,
eos_token_id=None,
generator: torch.Generator | None = None, on_token=None,
forward_fn=None, should_stop=None):
"""Return (output_ids [1, T], SpecStats). Batch size 1 (serving path).
Expand All @@ -139,6 +157,9 @@ def speculative_generate(model, input_ids: torch.Tensor, *, max_new_tokens: int
eos = set([eos_token_id] if isinstance(eos_token_id, int) else (eos_token_id or []))
gamma_max = max(1, int(gamma_max))
gamma = max(1, min(int(gamma), gamma_max))
penalty = float(repetition_penalty)
if penalty <= 0:
raise ValueError("repetition_penalty must be > 0")
set_cache_slack(model, gamma_max + 1)
device = input_ids.device
stats, t0 = SpecStats(), time.perf_counter()
Expand All @@ -149,11 +170,19 @@ def speculative_generate(model, input_ids: torch.Tensor, *, max_new_tokens: int
def forward_fn(ids, cache, depth):
return model(ids, past_key_values=cache, use_cache=True, recurrent_depth=depth)

def _seen_vec():
# Tokens the model has already committed to the output — the target of
# the CTRL penalty. Rebuilt from the Python list on each call because the
# cache is truncated on rejection and ``input_ids`` only holds the prompt.
return torch.tensor(tokens, device=device, dtype=torch.long)

def dist(row):
return _probs(row, temperature, top_k, top_p)
return _probs(_apply_rep_penalty(row, _seen_vec(), penalty), temperature, top_k, top_p)

def pick(row):
if not do_sample:
# Argmax under the penalty, so greedy decoding sees the rule too.
row = _apply_rep_penalty(row, _seen_vec(), penalty)
return int(torch.argmax(row))
return int(torch.multinomial(dist(row), 1, generator=generator))

Expand Down
18 changes: 14 additions & 4 deletions chronos/serving/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def _encode(self, messages, prompt: Optional[str] = None):
def generate(self, *, messages=None, prompt=None, max_tokens: int = 128,
temperature: float = 0.85, top_p: float = 0.95,
top_k: int = 50, do_sample: bool = True,
repetition_penalty: float = 1.0,
miss_policy: str = "on_demand") -> tuple[str, dict]:
ids, mask, modalities = self._encode(messages or [], prompt=prompt)
output = self.engine.generate(
Expand All @@ -57,6 +58,7 @@ def generate(self, *, messages=None, prompt=None, max_tokens: int = 128,
top_p=float(top_p),
top_k=int(top_k),
do_sample=bool(do_sample),
repetition_penalty=float(repetition_penalty),
miss_policy=miss_policy,
modality_inputs=modalities or None,
modality_mask=(torch.ones(ids.shape[0]) if modalities else None),
Expand All @@ -77,6 +79,7 @@ def openai_chat_completion(self, request: Mapping[str, Any]) -> dict:
top_p=request.get("top_p", 0.95),
top_k=request.get("top_k", 50),
do_sample=request.get("do_sample", True),
repetition_penalty=request.get("repetition_penalty", 1.0),
miss_policy=request.get("chronos_miss_policy", "on_demand"),
)
return openai_chat_response(
Expand All @@ -96,6 +99,9 @@ def ollama_chat(self, request: Mapping[str, Any]) -> dict:
top_p=request.get("top_p", options.get("top_p", 0.95)),
top_k=request.get("top_k", options.get("top_k", 50)),
do_sample=bool(request.get("do_sample", True)),
repetition_penalty=request.get(
"repetition_penalty", options.get("repeat_penalty", 1.0)
),
miss_policy=request.get("chronos_miss_policy", "on_demand"),
)
return ollama_chat_response(
Expand All @@ -106,13 +112,17 @@ def ollama_chat(self, request: Mapping[str, Any]) -> dict:
)

def ollama_generate(self, request: Mapping[str, Any]) -> dict:
options = request.get("options") or {}
text, stats = self.generate(
prompt=request.get("prompt", ""),
max_tokens=request.get("options", {}).get("num_predict", 128),
temperature=request.get("options", {}).get("temperature", 0.85),
top_p=request.get("options", {}).get("top_p", 0.95),
top_k=request.get("options", {}).get("top_k", 50),
max_tokens=options.get("num_predict", 128),
temperature=options.get("temperature", 0.85),
top_p=options.get("top_p", 0.95),
top_k=options.get("top_k", 50),
do_sample=bool(request.get("do_sample", True)),
repetition_penalty=request.get(
"repetition_penalty", options.get("repeat_penalty", 1.0)
),
miss_policy=request.get("chronos_miss_policy", "on_demand"),
)
return ollama_generate_response(
Expand Down
11 changes: 11 additions & 0 deletions chronos/serving/ollama_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@ def _options(body: dict) -> dict:
"temperature": float(opts.get("temperature", body.get("temperature", 0.0)) or 0.0),
"top_k": int(opts.get("top_k", body.get("top_k", 0)) or 0),
"top_p": float(opts.get("top_p", body.get("top_p", 1.0)) or 1.0),
# Ollama spells it ``repeat_penalty``; OpenAI/transformers call it
# ``repetition_penalty``. Accept either; default 1.0 keeps existing
# scripts byte-identical (speculative decoding is exact at 1.0).
"repetition_penalty": float(
opts.get(
"repeat_penalty",
opts.get("repetition_penalty", body.get("repetition_penalty", 1.0)),
)
or 1.0
),
"seed": opts.get("seed", body.get("seed")),
"stop": opts.get("stop", body.get("stop")) or [],
"speculative": bool(opts.get("chronos_speculative", True)),
Expand Down Expand Up @@ -320,6 +330,7 @@ async def openai_chat(request: Request):
opts = _options({**body, "options": {"num_predict": body.get("max_tokens") or body.get("max_completion_tokens") or 256,
"temperature": body.get("temperature", 0.0), "top_p": body.get("top_p", 1.0),
"seed": body.get("seed"), "stop": body.get("stop"),
"repetition_penalty": body.get("repetition_penalty", 1.0),
**(body.get("chronos") or {})}})
cid, created = f"chatcmpl-{uuid.uuid4().hex}", int(time.time())
with_tools = bool(body.get("tools"))
Expand Down
86 changes: 83 additions & 3 deletions chronos/serving/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,66 @@ 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.
INFERENCE_OVERRIDE_KEYS = ("kv_cache_dtype", "kv_quant_group_size", "mla_decode", "mla_cache_rope",
"router_scope", "max_resident_experts", "ram_budget_mb")
"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:
Expand Down Expand Up @@ -114,6 +173,24 @@ 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 Expand Up @@ -261,7 +338,8 @@ def encode_prompt(self, lm: LoadedModel, prompt: str, system: str | None = None,
return self.encode_chat(lm, msgs)

def generate_stream(self, name: str, input_ids: list[int], *, max_new_tokens: int = 256,
temperature: float = 0.0, top_k: int = 0, top_p: float = 1.0, seed: int | None = None,
temperature: float = 0.0, top_k: int = 0, top_p: float = 1.0,
repetition_penalty: float = 1.0, seed: int | None = None,
speculative: bool = True, draft_depth: int = 1, gamma: int = 4,
miss_policy: str = "on_demand", stop: list[str] | None = None):
"""Yield ``{"text": delta}`` chunks, then a final ``{"done": True, ...stats}``."""
Expand Down Expand Up @@ -310,7 +388,9 @@ def on_token(t):
lm.model, ids, max_new_tokens=max_new_tokens,
draft_depth=draft_depth if use_spec else depth, gamma=gamma,
do_sample=do_sample, temperature=max(float(temperature), 1e-6),
top_k=int(top_k or 0), top_p=float(top_p or 1.0), eos_token_id=eos,
top_k=int(top_k or 0), top_p=float(top_p or 1.0),
repetition_penalty=float(repetition_penalty or 1.0),
eos_token_id=eos,
generator=gen, on_token=on_token, forward_fn=self._forward_fn(lm, telemetry),
should_stop=cancel.is_set)
result.update(stats.as_dict())
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "Project_Chronos"
version = "0.3.3"
version = "0.3.4"
description = "Storage-aware recurrent-depth MoE: lookahead expert prefetch, SSD-lazy experts, hybrid MLA/SWA attention, self-speculative decoding"
readme = "README.md"
license = "Apache-2.0"
Expand Down
Loading
Loading