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
7 changes: 5 additions & 2 deletions omlx/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
)
from .utils.proc_memory import get_graphics_footprint, get_phys_footprint
from .utils.sampling import make_sampler as omlx_make_sampler
from .utils.sampling import make_shared_sampler as omlx_make_shared_sampler
from .utils.tokenizer import create_streaming_detokenizer


Expand Down Expand Up @@ -7008,8 +7009,10 @@ def _build_sampler_and_processors(
) -> tuple[Callable[[mx.array], mx.array], list[Callable]]:
"""Build per-request sampler and logits processors."""
# omlx.utils.sampling.make_sampler carries the fused top-p/top-k and
# MTP acceptance metadata that mlx_lm.sample_utils does not.
sampler = omlx_make_sampler(
# MTP acceptance metadata that mlx_lm.sample_utils does not. Requests
# with equal parameters share one sampler object so a decode batch
# samples all of them in one call (see make_shared_sampler).
sampler = omlx_make_shared_sampler(
temp=sampling_params.temperature,
top_p=sampling_params.top_p,
min_p=sampling_params.min_p,
Expand Down
92 changes: 91 additions & 1 deletion omlx/utils/sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
from __future__ import annotations

import math
from typing import Callable, List
import os
import threading
from collections import OrderedDict
from typing import Callable, List, Sequence

import mlx.core as mx

Expand Down Expand Up @@ -255,3 +258,90 @@ def sample_with_logprobs(logprobs: mx.array, *, rowwise: bool = False):
sampler.min_tokens_to_keep = min_tokens_to_keep
sampler.xtc_probability = xtc_probability
return sampler


# mlx-lm's GenerationBatch._step samples a batch in one call only when every
# row's sampler is the same object; otherwise it runs each row's filter and
# sampling chain on a one-row slice and concatenates the results. The server
# builds a sampler per request, so a decode batch of B requests paid B chains
# (top-k, top-p, categorical over the full vocabulary: about forty graph ops
# and their GPU launches per row) even when every request asked for the same
# parameters. The samplers are stateless (their randomness comes from MLX's
# global RNG, which the per-row loop already advanced row by row), so
# requests with equal parameters can share one object and mlx-lm samples
# them together. Each row still draws from its own filtered distribution;
# only the RNG stream behind the draws changes.
#
# XTC is never shared: its coin flip is one draw per call, which a shared
# call would turn into one flip for the whole batch.
#
# OMLX_SHARED_SAMPLERS=0 builds one sampler per request again.
_SHARED_SAMPLERS_ENABLED = os.environ.get("OMLX_SHARED_SAMPLERS", "1") != "0"
_SHARED_SAMPLERS_MAX = 256
_shared_samplers: OrderedDict[tuple, Callable[[mx.array], mx.array]] = OrderedDict()
_shared_samplers_lock = threading.Lock()


def _shared_sampler_key(
temp: float,
top_p: float,
min_p: float,
min_tokens_to_keep: int,
top_k: int,
) -> tuple:
return (
float(temp),
float(top_p),
float(min_p),
int(min_tokens_to_keep),
int(top_k or 0),
)


def make_shared_sampler(
temp: float = 0.0,
top_p: float = 0.0,
min_p: float = 0.0,
min_tokens_to_keep: int = 1,
top_k: int = 0,
xtc_probability: float = 0.0,
xtc_threshold: float = 0.0,
xtc_special_tokens: Sequence[int] = (),
) -> Callable[[mx.array], mx.array]:
"""``make_sampler`` that hands equal parameters the same sampler object.

Falls back to a fresh ``make_sampler`` for XTC and when
``OMLX_SHARED_SAMPLERS=0``.
"""
if not _SHARED_SAMPLERS_ENABLED or xtc_probability > 0.0:
return make_sampler(
temp=temp,
top_p=top_p,
min_p=min_p,
min_tokens_to_keep=min_tokens_to_keep,
top_k=top_k,
xtc_probability=xtc_probability,
xtc_threshold=xtc_threshold,
xtc_special_tokens=list(xtc_special_tokens or ()),
)
key = _shared_sampler_key(temp, top_p, min_p, min_tokens_to_keep, top_k)
with _shared_samplers_lock:
sampler = _shared_samplers.get(key)
if sampler is not None:
_shared_samplers.move_to_end(key)
return sampler
sampler = make_sampler(
temp=temp,
top_p=top_p,
min_p=min_p,
min_tokens_to_keep=min_tokens_to_keep,
top_k=top_k,
)
with _shared_samplers_lock:
# A racing thread may have built the same key; keep the first one so
# every row of a batch holds one object.
sampler = _shared_samplers.setdefault(key, sampler)
_shared_samplers.move_to_end(key)
while len(_shared_samplers) > _SHARED_SAMPLERS_MAX:
_shared_samplers.popitem(last=False)
return sampler
136 changes: 136 additions & 0 deletions tests/test_shared_sampler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# SPDX-License-Identifier: Apache-2.0
"""Requests with equal sampling parameters share one sampler object.

mlx-lm's GenerationBatch._step samples a decode batch in one call only when
every row's sampler is the same object. These tests pin the sharing, its
exceptions (XTC, the opt-out) and that a shared call over a batch filters each
row exactly as a one-row call would. CPU only.
"""

from __future__ import annotations

from types import SimpleNamespace

import mlx.core as mx
import pytest

from omlx.request import SamplingParams
from omlx.utils import sampling


@pytest.fixture(autouse=True, scope="module")
def _cpu_device():
# CPU only, but restore the previous default device: a module-level
# set_default_device would move every later test in the session.
previous = mx.default_device()
mx.set_default_device(mx.cpu)
yield
mx.set_default_device(previous)


@pytest.fixture(autouse=True)
def _fresh_cache(monkeypatch):
monkeypatch.setattr(sampling, "_shared_samplers", type(sampling._shared_samplers)())
monkeypatch.setattr(sampling, "_SHARED_SAMPLERS_ENABLED", True)


def test_equal_parameters_share_one_sampler():
a = sampling.make_shared_sampler(temp=0.7, top_p=0.95, top_k=20)
b = sampling.make_shared_sampler(temp=0.7, top_p=0.95, top_k=20)
assert a is b
assert a.temp == 0.7 and a.top_p == 0.95 and a.top_k == 20


def test_different_parameters_get_different_samplers():
a = sampling.make_shared_sampler(temp=0.7, top_p=0.95, top_k=20)
assert sampling.make_shared_sampler(temp=0.6, top_p=0.95, top_k=20) is not a
assert sampling.make_shared_sampler(temp=0.7, top_p=0.9, top_k=20) is not a
assert sampling.make_shared_sampler(temp=0.7, top_p=0.95, top_k=40) is not a
assert (
sampling.make_shared_sampler(temp=0.7, top_p=0.95, top_k=20, min_p=0.05)
is not a
)
assert sampling.make_shared_sampler(temp=0.0) is sampling.make_shared_sampler(
temp=0.0
)


def test_xtc_is_never_shared():
kwargs = dict(temp=1.0, xtc_probability=0.5, xtc_threshold=0.1)
assert sampling.make_shared_sampler(**kwargs) is not sampling.make_shared_sampler(
**kwargs
)


def test_opt_out_builds_one_sampler_per_call(monkeypatch):
monkeypatch.setattr(sampling, "_SHARED_SAMPLERS_ENABLED", False)
kwargs = dict(temp=0.7, top_p=0.95, top_k=20)
assert sampling.make_shared_sampler(**kwargs) is not sampling.make_shared_sampler(
**kwargs
)


def test_cache_is_bounded(monkeypatch):
monkeypatch.setattr(sampling, "_SHARED_SAMPLERS_MAX", 4)
for k in range(1, 10):
sampling.make_shared_sampler(temp=0.7, top_k=k)
assert len(sampling._shared_samplers) == 4


def _logprobs(rows: int, vocab: int = 128 * 80, seed: int = 0) -> mx.array:
logits = mx.random.normal((rows, vocab), key=mx.random.key(seed)) * 4.0
return logits - mx.logsumexp(logits, axis=-1, keepdims=True)


@pytest.mark.parametrize(
"kwargs",
[
dict(temp=0.7, top_p=0.95, top_k=20),
dict(temp=0.7, top_p=0.9),
dict(temp=0.7, min_p=0.05, top_k=50),
],
)
def test_batched_filter_matches_one_row_calls(kwargs):
sampler = sampling.make_shared_sampler(**kwargs)
logprobs = _logprobs(8)
batched = sampler._mtp_sampling_logits(logprobs)
rows = mx.concatenate(
[sampler._mtp_sampling_logits(logprobs[e : e + 1]) for e in range(8)], axis=0
)
assert mx.array_equal(batched, rows).item()


def test_greedy_batched_call_matches_one_row_calls():
sampler = sampling.make_shared_sampler(temp=0.0)
logprobs = _logprobs(8, seed=1)
rows = mx.concatenate([sampler(logprobs[e : e + 1]) for e in range(8)], axis=0)
assert mx.array_equal(sampler(logprobs), rows).item()


def test_batched_draws_stay_inside_each_rows_support():
sampler = sampling.make_shared_sampler(temp=0.7, top_p=0.95, top_k=20)
logprobs = _logprobs(8, seed=2)
support = sampler._mtp_sampling_logits(logprobs) > -float("inf")
for _ in range(16):
tokens = sampler(logprobs)
assert tokens.shape == (8,)
assert mx.take_along_axis(support, tokens[:, None], axis=-1).all().item()


def test_scheduler_requests_with_equal_parameters_share_a_sampler():
from omlx.scheduler import Scheduler

fake = SimpleNamespace(_xtc_special_tokens=[], _model_suppress_tokens=set())
params = SamplingParams(temperature=0.7, top_p=0.95, top_k=20)
first, _ = Scheduler._build_sampler_and_processors(fake, params)
second, _ = Scheduler._build_sampler_and_processors(
fake, SamplingParams(temperature=0.7, top_p=0.95, top_k=20, seed=3)
)
other, _ = Scheduler._build_sampler_and_processors(
fake, SamplingParams(temperature=0.7, top_p=0.95, top_k=40)
)
assert first is second
assert other is not first
# mlx-lm GenerationBatch._step's one-call condition.
samplers = [first, second]
assert all(s is samplers[0] for s in samplers)