Skip to content
Open
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
3 changes: 2 additions & 1 deletion dev/tests/engine/native_arguments_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ void testServerCommandLines(const char *path) {
{"disable_ane", [](NativeArguments &read) { read.neuralEngine = false; }},
{"recalibrate_ane", [](NativeArguments &read) { read.recalibrateAne = true; }},
{"activations_bf16", [](NativeArguments &read) { read.int8Activations = ops::Int8Activations::Off; }},
{"suppress_tokens", [](NativeArguments &read) { read.suppressTokensFile = "/srv/mask.json"; }},
{"verify_rows_all", [](NativeArguments &read) { read.verifyRows = model::VerifyRows::All; }},
// The defaults the server leaves out are the engine's: each meaning
// names the value, so a change of the engine's default fails it.
Expand Down Expand Up @@ -219,7 +220,7 @@ void testServerCommandLines(const char *path) {
read.expertMemory == meant.expertMemory && read.sparseKvMemory == meant.sparseKvMemory &&
read.kvSpillAlways == meant.kvSpillAlways && read.kvWindowTrim == meant.kvWindowTrim &&
read.verifyRows == meant.verifyRows && read.int8Activations == meant.int8Activations &&
read.lanes == meant.lanes;
read.lanes == meant.lanes && read.suppressTokensFile == meant.suppressTokensFile;
};
const auto golden = readGolden(path);
require(golden.size() == changes.size(),
Expand Down
1 change: 1 addition & 0 deletions dev/tests/engine/native_command_golden.txt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ disable_ane | --disable-ane | auto auto --ane off
recalibrate_ane | --recalibrate-ane | auto auto --ane-calibration again
activations_bf16 | --activations bf16 | auto auto --activations bf16
activations_auto | --activations auto | auto auto
suppress_tokens | --suppress-tokens /srv/mask.json | auto auto --suppress-tokens /srv/mask.json
verify_rows_all | --verify-rows all | auto auto --verify-rows all
verify_rows_auto | --verify-rows auto | auto auto
max_concurrent_requests | --max-concurrent-requests 8 | auto auto --max-concurrent-requests 8
Expand Down
47 changes: 47 additions & 0 deletions dev/tests/engine/target_sampling_metal_test.mm
Original file line number Diff line number Diff line change
Expand Up @@ -2776,6 +2776,51 @@ void setChildren(const Batch &batch, uint32_t lane, uint32_t row, uint32_t depth
next[i] = static_cast<float>(children.q[i]);
}

void outputSuppression(MetalBackend &backend) {
constexpr uint32_t vocabulary = 1003, forbidden = 529, allowed = 701;
const MetalBuffer mask = allocate(backend, 130 * sizeof(uint32_t));
std::iota(static_cast<uint32_t *>(mask.contents()), static_cast<uint32_t *>(mask.contents()) + 130, 400U);
const Sampling sampling(vocabulary, mask);
const Batch batch = makeBatch(backend, vocabulary, 2);
const std::array<SamplingPolicy, 2> policies{{{}, {.temperature = 1.0F}}};
const auto fill = [&] {
for (uint32_t row = 0; row < batch.rows; ++row) {
std::fill_n(batch.row(row), vocabulary, -1.0e4F);
batch.row(row)[forbidden] = 100.0F;
batch.row(row)[allowed] = 0.0F;
}
batch.poison();
};

fill();
const auto firstRows = initialRows(policies.size(), 3);
CommandGraph first;
sampling.addInitial(first, policies, batch.buffers, firstRows, kStopTokens, {});
static_cast<void>(backend.submitCommandAsync(first.dispatches()).wait());
for (const uint32_t row : firstRows)
require(batch.outputTokens()[row] == allowed, "the first token must exclude a suppressed maximum");

fill();
CommandGraph mixed;
sampling.addInitial(mixed, policies, batch.buffers, firstRows, kStopTokens, {}, 0b10);
static_cast<void>(backend.submitCommandAsync(mixed.dispatches()).wait());
require(batch.row(firstRows[0])[forbidden] == 100.0F, "a score-only lane must keep its raw logit");
require(batch.outputTokens()[firstRows[1]] == allowed, "the generating lane must exclude a suppressed maximum");

fill();
Children children;
std::iota(children.ids.begin(), children.ids.end(), 100U);
children.ids[0] = forbidden;
children.q[0] = 1.0;
children.draws = {0};
setChildren(batch, 1, 0, 0, children);
CommandGraph verify;
sampling.addVerify(verify, policies, batch.buffers, layOut(batch.buffers, blocks(policies.size())), kStopTokens, {});
static_cast<void>(backend.submitCommandAsync(verify.dispatches()).wait());
for (uint32_t row = 0; row < batch.rows; ++row)
require(batch.outputTokens()[row] == allowed, "a verify row must not select a suppressed token");
}

// A sampled verify row that tests the children its draft drew selects as the
// recursion does with its uniforms: for each lane's chain of rows, with
// production and other policies, of zero to four children each, their
Expand Down Expand Up @@ -3594,6 +3639,8 @@ int main(int argc, char **argv) {
stage = "recursive rejection sampling";
recursiveRejectionSampling();
MetalBackend backend(argv[1]);
stage = "output suppression in initial and speculative selection";
outputSuppression(backend);
stage = "invalid penalties";
invalidPenalties(backend);
stage = "buffer extents";
Expand Down
1 change: 1 addition & 0 deletions dev/tests/install/test_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@ def test_the_apps_launch_options_are_the_serve_options(self):
"--draft-model",
"--mmproj",
"--chat-template-file",
"--suppress-tokens",
"--reasoning-effort",
}
self.assertIn("--max-memory", flags)
Expand Down
3 changes: 3 additions & 0 deletions dev/tests/server/test_serve_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ def values(flag, accepted, refused, repeatable=False):
"--activations": values(
"--activations", {"auto": "auto", "bf16": "bf16"}, ("", "on", "off", "BF16")
),
"--suppress-tokens": values(
"--suppress-tokens", {"/srv/mask.json": Path("/srv/mask.json")}, ("", " ")
),
"--verify-rows": values(
"--verify-rows",
{"auto": "auto", "all": "all"},
Expand Down
1 change: 1 addition & 0 deletions dev/tests/server_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,7 @@ def main_args(**overrides):
"disable_ane": False,
"recalibrate_ane": False,
"activations": "auto",
"suppress_tokens": None,
"verify_rows": "auto",
"max_image_pixels": images.MAX_PIXELS,
"request_timeout": None,
Expand Down
2 changes: 1 addition & 1 deletion docs/package.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ coding agents with `splash AGENT --port PORT`, typed into a new terminal of the
window's drawer in the folder the agents work in, the last one chosen, whose
environment holds the running server's API key. Its launch options are every option `splash serve` takes but the
ones of one model (`--revision`, `--draft-model`, `--mmproj`,
`--chat-template-file`), the ones it
`--chat-template-file`, `--suppress-tokens`), the ones it
sets itself and `--reasoning-effort`, which it leaves to the command line,
from one table (`LaunchOption.all`) the tests hold to `splash serve --help`. It offers a model only those its family can use, and passes
no other: at launch it runs `install/families.py`, which reports for each
Expand Down
1 change: 1 addition & 0 deletions docs/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ paths for `--model-dir`, `--draft-model` and `--mmproj`.
| `--served-model-name` | None | Additional model name the API accepts; repeatable. See [API model aliases](#api-model-aliases). |
| `--announce-served-name` | Off | Report the first `--served-model-name` in responses; needs `--served-model-name`. |
| `--sampling-default` | None (the served family's published `temperature`, `top_p` and `top_k`; the neutral value for the rest) | Value of a sampling field that a request leaves out; repeatable, e.g. `temperature=0.6`. See [sampling](api.md#sampling). |
| `--suppress-tokens FILE` | Off | Forbid model-specific token IDs in generated output. The engine reads a JSON array or an object with `target_token_ids` at startup. IDs must be unique, in the model's vocabulary, and cannot be stop tokens. Prompt and raw scoring tokens are unaffected. Greedy selection and sampled DFlash2 verification both exclude these IDs. Requests whose thinking cutoff would force a suppressed token fail. This option belongs to the model's command line, outside the desktop app's shared launch settings. |
| `--reasoning-effort` | `SPLASH_REASONING_EFFORT` or each request's own | Effort of every Chat, Responses and Messages request, whatever the request asks; `none` turns thinking off. See [default reasoning effort](#default-reasoning-effort). |
| `--default-reasoning-effort` | `SPLASH_DEFAULT_REASONING_EFFORT` or the template's | Effort of Chat and Responses requests that set none. See [default reasoning effort](#default-reasoning-effort). |
| `--thinking-token-budget` | `SPLASH_THINKING_TOKEN_BUDGET` or none | Thinking tokens of a request that sets no budget. See [thinking token budget](#thinking-token-budget). |
Expand Down
20 changes: 8 additions & 12 deletions runtime/engine/Bootstrap.mm
Original file line number Diff line number Diff line change
Expand Up @@ -448,24 +448,23 @@ RuntimeBootstrapReport reportForPlan(const EngineMemoryPlan &plan) {
}
config.nativeLoop.engine.vocabularySize =
config.resources.model.capabilities.vocabularySize;
// Images are admitted up to the server's pixel cap; a model without vision
// admits none.
// A model without vision admits no image patches.
config.nativeLoop.engine.maxImagePatches =
config.resources.model.hasVision() ? config.resources.maximumImagePatches
: 0;

std::unique_ptr<model::RuntimeModel> modelRuntime;
try {
// The plan's fixed bytes already proved the arenas' sum fits.
// Admit the planned arenas and the optional token ID buffer together.
const auto &budget = resources->memoryPlan().breakdown();
// Admission reports a refusal by its failure alone. One raised while the
// runtime allocates keeps its own message, which says what to do.
std::string refusal;
auto context = resources->modelContext();
context.suppressedTokens = config.nativeLoop.engine.suppressedTokens;
const metal::AllocationResult arenas =
resources->memoryGovernor().allocationAdmission()(
budget.sharedPrefillBytes + budget.sharedDecodeBytes, [&] {
budget.sharedPrefillBytes + budget.sharedDecodeBytes + context.suppressedTokens.size_bytes(), [&] {
try {
modelRuntime = model::createRuntime(resources->modelContext());
modelRuntime = model::createRuntime(std::move(context));
} catch (const metal::MetalAllocationError &error) {
refusal = error.what();
throw;
Expand All @@ -489,8 +488,7 @@ RuntimeBootstrapReport reportForPlan(const EngineMemoryPlan &plan) {
fail(std::move(base), RuntimeBootstrapStage::ModelCreation,
"modelRuntime creation failed with an unknown exception");
}
// The parser and engine consume the same resolved ceiling. In automatic
// mode it cannot be known until resource planning has measured the device.
// The parser and engine use the same context, resolved by the memory plan.
const protocol::ProtocolLimits limits = protocolLimitsFor(
config.resources.model.capabilities, config.nativeLoop.engine.maxContext);
const protocol::ReadyEvent ready =
Expand All @@ -499,9 +497,7 @@ RuntimeBootstrapReport reportForPlan(const EngineMemoryPlan &plan) {
std::unique_ptr<NativeRuntime> nativeLoop;
try {
connectToGovernor(config.nativeLoop.engine, resources->memoryGovernor());
// The model's pools join the ledger, which ranks them after the sources
// the engine registers as it is built (the cache, then the engine's own
// victims), and the ledger logs each decision it makes.
// The ledger ranks model pools after the cache and engine victims.
MemoryLedger &ledger = resources->memoryGovernor().ledger();
for (model::ElasticPool *pool : modelRuntime->pools())
ledger.addPool(*pool);
Expand Down
24 changes: 10 additions & 14 deletions runtime/engine/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,30 +93,26 @@ Engine::Engine(EngineConfig config, Cache &cache, model::Model &model,
Engine::~Engine() { config_.governor->ledger().removeSource(victims_); }

void Engine::submit(EngineRequest value) {
const auto outOfVocabulary = [&](uint32_t token) {
return token >= config_.vocabularySize;
};
if (value.prompt.size() + value.maxNewTokens > config_.maxContext) {
const auto outOfVocabulary = [&](uint32_t token) { return token >= config_.vocabularySize; };
if (value.prompt.size() + value.maxNewTokens > config_.maxContext)
throw std::invalid_argument("request exceeds the context window");
}
if (std::any_of(value.prompt.begin(), value.prompt.end(), outOfVocabulary)) {
if (std::ranges::any_of(value.prompt, outOfVocabulary))
throw std::invalid_argument("prompt token is out of vocabulary");
}
if (std::any_of(value.scoreTokens.begin(), value.scoreTokens.end(),
outOfVocabulary)) {
if (std::ranges::any_of(value.scoreTokens, outOfVocabulary))
throw std::invalid_argument("score token is out of vocabulary");
}
if (value.thinkingBudget) {
if (const char *reason = value.thinkingBudget->unusable())
throw std::invalid_argument(reason);
if (std::any_of(value.thinkingBudget->end.begin(),
value.thinkingBudget->end.end(), outOfVocabulary) ||
if (std::ranges::any_of(value.thinkingBudget->end, outOfVocabulary) ||
outOfVocabulary(value.thinkingBudget->alsoEnds))
throw std::invalid_argument("thinking end token is out of vocabulary");
if (std::ranges::any_of(value.thinkingBudget->end, [&](uint32_t token) {
return std::ranges::binary_search(config_.suppressedTokens, token);
}))
throw std::invalid_argument("thinking end token is suppressed by --suppress-tokens");
}
if (!value.images.empty() && !config_.maxImagePatches) {
if (!value.images.empty() && !config_.maxImagePatches)
throw std::invalid_argument("this model is serving without vision");
}
// The protocol bounds an image by the most patches the vision encoder
// takes; the server's pixel cap may allow fewer.
if (std::any_of(value.images.begin(), value.images.end(),
Expand Down
2 changes: 2 additions & 0 deletions runtime/engine/Engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ struct EngineConfig final {
// the next request (WeightResidency): the native loop's; empty where
// nothing is released.
std::optional<WeightResidencyConfig> weights;
// Sorted output exclusions also checked against forced thinking ends.
std::vector<uint32_t> suppressedTokens;
};

// What a request fails with once it has waited the resource wait limit for
Expand Down
4 changes: 4 additions & 0 deletions runtime/engine/NativeArguments.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ NativeArguments parseNativeArguments(int argc, const char *const *argv) {
if (value != "auto" && value != "bf16")
throw UsageError("--activations requires auto or bf16");
result.int8Activations = value == "auto" ? ops::Int8Activations::On : ops::Int8Activations::Off;
} else if (option == "--suppress-tokens") {
if (value.empty())
throw UsageError("--suppress-tokens requires a JSON file");
result.suppressTokensFile = std::filesystem::path(value);
} else if (option == "--verify-rows") {
if (value != "auto" && value != "all")
throw UsageError("--verify-rows requires auto or all");
Expand Down
1 change: 1 addition & 0 deletions runtime/engine/NativeArguments.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ struct NativeArguments final {
// --verify-rows auto|all: the rows of the draft's block a decode
// cycle verifies (RuntimeResourcesConfig::verifyRows).
model::VerifyRows verifyRows = model::VerifyRows::Auto;
std::filesystem::path suppressTokensFile;
// --max-concurrent-requests REQUESTS: the lanes the runtime runs, 1 to
// ExecutionLimits::maximumBatchWidth (RuntimeResourcesConfig::lanes).
uint32_t lanes = model::ExecutionLimits::defaultLanes;
Expand Down
Loading
Loading