mirror of
https://github.com/unslothai/unsloth.git
synced 2026-08-25 08:42:25 +00:00
* Add opt-in DSpark speculative decoding * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix lint blockers, retry-guard test and DSpark broken-build gate for PR #7968 Three fixes for the failing CI on this branch: - Drop the unused `Literal` import from unsloth_cli/commands/chat.py and inference.py. The options are typed with `SpeculativeType`, so the added import was a leftover and tripped the import-hoist blocker. - Make test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry whitespace insensitive. The guard now names both drafters, so formatting wrapped the call and the literal substring assertion no longer matched. It asserts on both `_extra_args_requests_mtp` and `_extra_args_requests_dspark` now, so the DSpark half is covered too. - Gate DSpark on the whole broken build window instead of one tag. The reshape regression is ggml-org/llama.cpp#26531 and the fix is #26577, so every prebuilt based on b10259 through b10268 aborts on a DSpark load, not only b10265-mix-89aa77b. Matching the base build number keeps source builds unaffected, since those carry no install marker. * Probe DSpark support before downloading the sidecar The ~11 GB DSpark sidecar was fetched at llama_cpp.py:8664 while the first supports_dspark consumer sat ~480 lines later, so a binary that cannot run draft-dspark paid for the whole download and then fell back without ever opening the file. probe_server_capabilities is already called just above for supports_kv_unified, so the answer is in scope and cached and the check costs nothing. This is the default path right now, not an edge case: the shipped unslothai/llama.cpp prebuilt b10265-mix-89aa77b sits inside the known-broken b10259..b10268 window, so supports_dspark is False on a standard install. Also swaps the order of the first two DSpark fallbacks. Now that the fetch is gated on the same answer, a gated binary leaves no sidecar, and checking the drafter first reported "no matching dspark-*.gguf sidecar was found" and told the user to place a file that was never the problem, while re-loading on every Apply through the drafter_not_found dedup branch. Adds three regression tests, all of which fail without this change. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Enforce fixed fit for pass-through DSpark, size split sidecars, correct the hint Three fixes from the latest review round. Extras that own --spec-type return from _build_speculative_flags before _speculative_type is set, so the --fit strip keyed only on that field never fired for a pass-through DSpark launch and a user --fit on survived. DSpark's layout cannot be reshaped, so that aborts the load. The strip now also reads the accumulated spec types, which covers both the flag and the env. The training coexistence estimate sized the drafter with a bare stat(), while the main weight beside it already used the split-aware helper. Discovery hands back shard 1, so a split sidecar was counted at one shard and the guard could admit a load that evicts the training run it exists to protect. The Speculative Decoding hint promised "no accuracy hit" unconditionally, which DSpark does not meet: on a quantized target its greedy output can differ from a non speculative run (ggml-org/llama.cpp#25618). Measured here on DeepSeek-V4-Flash-0731 UD-Q4_K_XL, where the same greedy conversation produced 10570 tokens without a drafter and 14687 with one. The claim now stays with Auto, and DSpark carries its own caveat. Both backend fixes have regression tests that fail without them. * Pin fit off for pass-through DSpark, keep cached sidecars visible, reclaim them on delete * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Allow DSpark under --fit on: fitting only skips the sidecar reserve * Gate the training-guard DSpark estimate on binary support, fix the picker contract marker * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Default Auto to DSpark when a sidecar is available, and stop the two reload loops it exposed * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Charge no drafter when forced DSpark is gated off by the binary * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Gate remote Auto DSpark sizing, retry only a failed sidecar fetch, refresh the Auto hint * Apply ruff kwarg-spacing formatting --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <unslothai@gmail.com>
147 lines
5.2 KiB
Python
147 lines
5.2 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-only
|
|
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
|
|
|
|
from typing import List, Optional
|
|
|
|
import typer
|
|
|
|
from unsloth_cli._inference import (
|
|
SpeculativeType,
|
|
collect_stream,
|
|
configure_quiet_logging,
|
|
connect_studio_server,
|
|
load_chat_backend,
|
|
mlx_distributed_info,
|
|
mlx_distributed_uses_mpi,
|
|
raise_on_streamed_error,
|
|
stream_to_stdout,
|
|
)
|
|
|
|
|
|
def inference(
|
|
model: str = typer.Argument(..., help = "HF model id or local path."),
|
|
prompt: str = typer.Argument(..., help = "Prompt to send to the model."),
|
|
hf_token: Optional[str] = typer.Option(
|
|
None, "--hf-token", envvar = "HF_TOKEN", help = "Hugging Face token if needed."
|
|
),
|
|
temperature: float = typer.Option(0.7, "--temperature"),
|
|
top_p: float = typer.Option(0.9, "--top-p"),
|
|
top_k: int = typer.Option(40, "--top-k"),
|
|
max_new_tokens: int = typer.Option(256, "--max-new-tokens"),
|
|
repetition_penalty: float = typer.Option(1.1, "--repetition-penalty"),
|
|
system_prompt: str = typer.Option(
|
|
"",
|
|
"--system-prompt",
|
|
help = "Optional system prompt to prepend.",
|
|
),
|
|
max_seq_length: int = typer.Option(2048, "--max-seq-length"),
|
|
load_in_4bit: bool = typer.Option(True, "--load-in-4bit/--no-load-in-4bit"),
|
|
tensor_parallel: bool = typer.Option(
|
|
False,
|
|
"--tensor-parallel/--no-tensor-parallel",
|
|
help = (
|
|
"Split a GGUF across GPUs by tensor (--split-mode tensor) instead "
|
|
"of by layer. Under non-MPI mlx.launch, select MLX tensor "
|
|
"parallel mode instead of pipeline mode."
|
|
),
|
|
),
|
|
speculative_type: Optional[SpeculativeType] = typer.Option(
|
|
None,
|
|
"--speculative-type",
|
|
help = "Speculative decoding mode for GGUF models, including DSpark sidecar discovery.",
|
|
),
|
|
spec_draft_n_max: Optional[int] = typer.Option(
|
|
None,
|
|
"--spec-draft-n-max",
|
|
min = 1,
|
|
max = 16,
|
|
help = "Maximum draft tokens per step for MTP or DSpark (1..16).",
|
|
),
|
|
llama_extra_args: Optional[List[str]] = typer.Option(
|
|
None,
|
|
"--llama-extra-arg",
|
|
help = (
|
|
"Extra llama-server arg for GGUF models. Repeat for multiple "
|
|
"tokens, e.g. --llama-extra-arg=--top-k --llama-extra-arg 20."
|
|
),
|
|
),
|
|
think: bool = typer.Option(
|
|
False,
|
|
"--think/--no-think",
|
|
help = "Show the model's <think> reasoning. Off by default so reasoning "
|
|
"models answer directly instead of spending the token budget thinking.",
|
|
),
|
|
verbose: bool = typer.Option(
|
|
False,
|
|
"--verbose",
|
|
"-v",
|
|
help = "Show backend and llama-server logs (otherwise only the answer).",
|
|
),
|
|
no_server: bool = typer.Option(
|
|
False,
|
|
"--no-server",
|
|
help = "Load the model in-process even if an Unsloth server is running.",
|
|
),
|
|
):
|
|
"""Run a single inference using the specified model."""
|
|
if not verbose:
|
|
configure_quiet_logging()
|
|
|
|
is_mlx_distributed, rank, _world_size = mlx_distributed_info()
|
|
if is_mlx_distributed and mlx_distributed_uses_mpi():
|
|
if rank == 0:
|
|
typer.echo(
|
|
"Distributed `unsloth inference` with MPI is not supported by "
|
|
"the current subprocess backend. Use a non-MPI MLX launcher "
|
|
"backend such as ring/JACCL for now.",
|
|
err = True,
|
|
)
|
|
raise typer.Exit(code = 1)
|
|
|
|
# A running Unsloth server keeps the model warm between runs. Under
|
|
# mlx.launch, every rank must enter the local MLX path instead of rank 0
|
|
# alone talking to a server.
|
|
load_opts = dict(
|
|
hf_token = hf_token,
|
|
max_seq_length = max_seq_length,
|
|
load_in_4bit = load_in_4bit,
|
|
tensor_parallel = tensor_parallel,
|
|
llama_extra_args = llama_extra_args,
|
|
)
|
|
if speculative_type is not None:
|
|
load_opts["speculative_type"] = speculative_type
|
|
if spec_draft_n_max is not None:
|
|
load_opts["spec_draft_n_max"] = spec_draft_n_max
|
|
chat_backend = (
|
|
None if (no_server or is_mlx_distributed) else connect_studio_server(model, **load_opts)
|
|
)
|
|
if chat_backend is None:
|
|
chat_backend = load_chat_backend(model, **load_opts)
|
|
try:
|
|
stream = chat_backend.stream(
|
|
[{"role": "user", "content": prompt}],
|
|
system_prompt = system_prompt,
|
|
temperature = temperature,
|
|
top_p = top_p,
|
|
top_k = top_k,
|
|
max_new_tokens = max_new_tokens,
|
|
repetition_penalty = repetition_penalty,
|
|
enable_thinking = think,
|
|
)
|
|
stream = raise_on_streamed_error(stream)
|
|
if rank == 0:
|
|
typer.echo("Assistant:")
|
|
try:
|
|
stream_to_stdout(stream, show_thinking = think)
|
|
except RuntimeError as exc:
|
|
typer.echo(f"Error: {exc}", err = True)
|
|
raise typer.Exit(code = 1)
|
|
else:
|
|
try:
|
|
collect_stream(stream, show_thinking = think)
|
|
except RuntimeError:
|
|
if not is_mlx_distributed:
|
|
raise
|
|
raise typer.Exit(code = 1)
|
|
finally:
|
|
chat_backend.close()
|