Downloads: speed limit in Settings

hf has no bandwidth option, so the worker pauses hf (SIGSTOP/SIGCONT) whenever it is ahead of a
token bucket over bytes on disk. The limit is shared by all running downloads and re-read every
5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-13 10:04:48 +02:00
1 parent b623b16a6d
commit 85af566b93
9 files changed
+285 -8

No files matched your search

+5
View File
@@ -8,6 +8,11 @@ step 1 (Hugging Face downloader) is released as a minor version.
### Added ### Added
- **Download speed limit** (Settings → Downloads), in MB/s, for all downloads together; changes
apply to running downloads within seconds. `hf download` and hf_xet have no bandwidth option
(checked with huggingface_hub 2.1.1 / hf_xet 1.6.0), so the worker pauses and resumes the hf
process (SIGSTOP/SIGCONT) whenever it gets ahead of the limit: short bursts above it, the
average holds (tested: 145 MB at a 2 MB/s limit took 67 s). Linux only; ignored on Windows.
- **Paired A/B benchmarks** (`betterbench ab`): from a deployment's Benchmark card, pick another - **Paired A/B benchmarks** (`betterbench ab`): from a deployment's Benchmark card, pick another
running deployment of the same model as B. The same prompts go to both, alternating, with greedy running deployment of the same model as B. The same prompts go to both, alternating, with greedy
decoding, until the difference is known to ±the target precision (default 1 %, at most 200 decoding, until the difference is known to ±the target precision (default 1 %, at most 200
+8 -2
View File
@@ -1,10 +1,16 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { getRecommendedRoles } from "@/lib/settings"; import { getDownloadSpeedLimit, getRecommendedRoles } from "@/lib/settings";
import { RecommendedSettings } from "./recommended-settings"; import { RecommendedSettings } from "./recommended-settings";
import { SpeedLimit } from "./speed-limit";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Downloads · Settings" }; export const metadata: Metadata = { title: "Downloads · Settings" };
export default async function DownloadSettingsPage() { export default async function DownloadSettingsPage() {
return <RecommendedSettings initial={await getRecommendedRoles()} />; return (
<div className="flex flex-col gap-4">
<SpeedLimit initial={await getDownloadSpeedLimit()} />
<RecommendedSettings initial={await getRecommendedRoles()} />
</div>
);
} }
@@ -0,0 +1,86 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const MB = 1_000_000;
/** Download speed limit in MB/s; empty means no limit. Applies to running downloads within seconds. */
export function SpeedLimit({ initial }: { initial: number | null }) {
const [saved, setSaved] = useState(initial);
const [text, setText] = useState(initial ? String(initial / MB) : "");
const [busy, setBusy] = useState(false);
const value = text.trim() === "" ? null : Number(text.replace(",", "."));
const invalid = value != null && !(value >= 0.1);
const dirty = value !== (saved == null ? null : saved / MB);
async function save(next: number | null) {
setBusy(true);
try {
const res = await fetch("/api/settings/downloads", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ maxBytesPerSecond: next == null ? null : Math.round(next * MB) }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(body.error?.message ?? `Could not save (${res.status})`);
setSaved(body.maxBytesPerSecond);
setText(body.maxBytesPerSecond ? String(body.maxBytesPerSecond / MB) : "");
toast.success(body.maxBytesPerSecond ? `Downloads limited to ${body.maxBytesPerSecond / MB} MB/s` : "Download speed is no longer limited");
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle>Speed limit</CardTitle>
<CardDescription>
Caps the total download speed from Hugging Face, e.g. to leave bandwidth for others. It also applies to downloads that are already running. Leave empty for
no limit.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<form
className="flex items-end gap-2"
onSubmit={(e) => {
e.preventDefault();
if (!invalid) void save(value);
}}
>
<div className="flex flex-col gap-1.5">
<Label htmlFor="speed-limit">Maximum speed (MB/s)</Label>
<Input
id="speed-limit"
value={text}
onChange={(e) => setText(e.target.value.replace(/[^\d.,]/g, ""))}
inputMode="decimal"
placeholder="No limit"
className="w-40"
aria-invalid={invalid}
/>
</div>
<Button type="submit" disabled={busy || invalid || !dirty}>
Save
</Button>
{saved != null && (
<Button type="button" variant="ghost" disabled={busy} onClick={() => void save(null)}>
Remove limit
</Button>
)}
</form>
<p className="text-xs text-muted-foreground">
{invalid
? "At least 0.1 MB/s."
: `1 MB/s ≈ 8 Mbit/s. hf has no speed option of its own, so Kaname pauses it whenever it gets ahead; short bursts above the limit are normal, the average holds.`}
</p>
</CardContent>
</Card>
);
}
+15 -6
View File
@@ -2,19 +2,28 @@ import { NextResponse } from "next/server";
import { z } from "zod"; import { z } from "zod";
import { withAuth } from "@/lib/api-auth"; import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors"; import { apiError, handleApiError } from "@/lib/api-errors";
import { getRecommendedRoles, saveRecommendedRoles, SettingsError } from "@/lib/settings"; import { getDownloadSpeedLimit, getRecommendedRoles, saveDownloadSpeedLimit, saveRecommendedRoles, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
/** Download settings: which file kinds are picked along with model weights. */ async function current() {
export const GET = withAuth(async () => NextResponse.json({ recommendedRoles: await getRecommendedRoles() })); return { recommendedRoles: await getRecommendedRoles(), maxBytesPerSecond: await getDownloadSpeedLimit() };
}
const Body = z.object({ recommendedRoles: z.array(z.string()).max(32) }); /** Download settings: which file kinds are picked along with model weights, and the speed limit. */
export const GET = withAuth(async () => NextResponse.json(await current()));
const Body = z.object({
recommendedRoles: z.array(z.string()).max(32).optional(),
maxBytesPerSecond: z.number().nullable().optional(),
});
export const PUT = withAuth(async (req) => { export const PUT = withAuth(async (req) => {
try { try {
const { recommendedRoles } = Body.parse(await req.json()); const body = Body.parse(await req.json());
return NextResponse.json({ recommendedRoles: await saveRecommendedRoles(recommendedRoles) }); if (body.recommendedRoles) await saveRecommendedRoles(body.recommendedRoles);
if (body.maxBytesPerSecond !== undefined) await saveDownloadSpeedLimit(body.maxBytesPerSecond);
return NextResponse.json(await current());
} catch (err) { } catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message); if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err); return handleApiError(err);
+10
View File
@@ -0,0 +1,10 @@
// Download speed limit (Settings → Downloads). Shared by the settings API and the worker.
export const SPEED_LIMIT_KEY = "downloads.maxBytesPerSecond";
/** Smallest limit accepted (0.1 MB/s); below that hf's own timeouts start to bite. */
export const MIN_SPEED_LIMIT = 100_000;
/** The stored value as bytes per second, or null for no limit. */
export function parseSpeedLimit(v: unknown): number | null {
return typeof v === "number" && Number.isFinite(v) && v >= MIN_SPEED_LIMIT ? v : null;
}
+15
View File
@@ -4,6 +4,7 @@ import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema"; import { settings } from "@/lib/db/schema";
import { isLabelColor } from "@/lib/colors"; import { isLabelColor } from "@/lib/colors";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles"; import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend"; import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
const FILE_ROLES_KEY = "labels.fileRoles"; const FILE_ROLES_KEY = "labels.fileRoles";
@@ -84,3 +85,17 @@ export async function saveRecommendedRoles(roles: string[]): Promise<FileRole[]>
await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r))); await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r)));
return getRecommendedRoles(); return getRecommendedRoles();
} }
/** Download speed limit in bytes per second (Settings → Downloads), or null for no limit. */
export async function getDownloadSpeedLimit(): Promise<number | null> {
return parseSpeedLimit(await read<unknown>(SPEED_LIMIT_KEY));
}
export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Promise<number | null> {
if (bytesPerSecond != null && (!Number.isFinite(bytesPerSecond) || bytesPerSecond < MIN_SPEED_LIMIT)) {
throw new SettingsError("The speed limit must be at least 0.1 MB/s, or empty for no limit.");
}
if (bytesPerSecond == null) await db().delete(settings).where(eq(settings.key, SPEED_LIMIT_KEY));
else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond));
return getDownloadSpeedLimit();
}
+75
View File
@@ -11,7 +11,9 @@ import {
jobs, jobs,
modelFiles, modelFiles,
models, models,
settings,
} from "@/lib/db/schema"; } from "@/lib/db/schema";
import { parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
import { coreEnv } from "@/lib/env"; import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format"; import { formatBytes } from "@/lib/format";
import { escapeGlob } from "@/lib/selection"; import { escapeGlob } from "@/lib/selection";
@@ -29,9 +31,17 @@ import { log } from "./log";
import { settleModelStatus } from "./model-status"; import { settleModelStatus } from "./model-status";
import type { Runner } from "./runner"; import type { Runner } from "./runner";
import { SpeedMeter } from "./speed"; import { SpeedMeter } from "./speed";
import { Throttle } from "./throttle";
const SAMPLE_MS = 1_000; const SAMPLE_MS = 1_000;
const KILL_GRACE_MS = 10_000; const KILL_GRACE_MS = 10_000;
const THROTTLE_MS = 250;
const LIMIT_REFRESH_MS = 5_000;
/** SIGSTOP/SIGCONT; not on Windows (dev only), where the limit is ignored. */
const CAN_PAUSE = process.platform !== "win32";
/** Running downloads; the speed limit is the total, split evenly between them. */
const running = new Set<DownloadRunner>();
/** Environment variables passed through to hf (everything else, e.g. AUTH_SECRET, is withheld). */ /** Environment variables passed through to hf (everything else, e.g. AUTH_SECRET, is withheld). */
const PASSTHROUGH_ENV = [ const PASSTHROUGH_ENV = [
@@ -64,6 +74,7 @@ export class DownloadRunner implements Runner {
private stopReason?: "cancelled" | "interrupted"; private stopReason?: "cancelled" | "interrupted";
private killTimer?: NodeJS.Timeout; private killTimer?: NodeJS.Timeout;
private jobLog: JobLog; private jobLog: JobLog;
private paused = false;
constructor( constructor(
private job: Job, private job: Job,
@@ -100,6 +111,7 @@ export class DownloadRunner implements Runner {
this.stopReason = reason; this.stopReason = reason;
this.jobLog.system(reason === "cancelled" ? "Cancel requested, stopping hf…" : "Worker shutting down, stopping hf…"); this.jobLog.system(reason === "cancelled" ? "Cancel requested, stopping hf…" : "Worker shutting down, stopping hf…");
if (!this.child || this.child.exitCode !== null) return; if (!this.child || this.child.exitCode !== null) return;
this.resume(); // a stopped process only handles SIGTERM once it runs again
killTree(this.child, "SIGTERM"); killTree(this.child, "SIGTERM");
this.killTimer = setTimeout(() => { this.killTimer = setTimeout(() => {
if (this.child && this.child.exitCode === null) killTree(this.child, "SIGKILL"); if (this.child && this.child.exitCode === null) killTree(this.child, "SIGKILL");
@@ -272,6 +284,8 @@ export class DownloadRunner implements Runner {
if (settled) return; if (settled) return;
settled = true; settled = true;
clearInterval(timer); clearInterval(timer);
clearInterval(throttleTimer);
running.delete(this);
this.jobLog.end(); this.jobLog.end();
resolve(r); resolve(r);
}; };
@@ -291,6 +305,8 @@ export class DownloadRunner implements Runner {
}), }),
); );
child.on("close", (code, signal) => done({ code, signal })); child.on("close", (code, signal) => done({ code, signal }));
running.add(this);
const throttleTimer = this.throttle(dir, expected);
// Progress from bytes on disk, written to the DB once per second. // Progress from bytes on disk, written to the DB once per second.
const speed = new SpeedMeter(); const speed = new SpeedMeter();
@@ -313,6 +329,65 @@ export class DownloadRunner implements Runner {
}); });
} }
/**
* Enforce Settings → Downloads → Speed limit by pausing hf while it is ahead of the budget
* (see Throttle). The limit is re-read every few seconds, so changes apply to running downloads.
*/
private throttle(dir: string, expected: ExpectedFile[]): NodeJS.Timeout {
let total: number | null = null;
let readAt = 0;
let bucket: Throttle | null = null;
let busy = false;
let warned = false;
return setInterval(async () => {
if (busy || this.stopReason) return;
busy = true;
try {
const now = Date.now();
if (now - readAt >= LIMIT_REFRESH_MS) {
readAt = now;
const row = await db().query.settings.findFirst({ where: eq(settings.key, SPEED_LIMIT_KEY) });
const next = parseSpeedLimit(row?.value);
if (next !== total) {
this.jobLog.system(next ? `Speed limit: ${formatBytes(next)}/s${running.size > 1 ? ` shared by ${running.size} downloads` : ""}.` : "No speed limit.");
if (next && !CAN_PAUSE && !warned) {
warned = true;
this.jobLog.system("The speed limit only works on Linux (the worker pauses hf); ignored here.");
}
total = next;
}
}
if (!total || !CAN_PAUSE) {
bucket = null;
this.resume();
return;
}
const limit = total / Math.max(1, running.size);
if (!bucket) bucket = new Throttle(limit);
bucket.limit = limit;
const bytes = (await this.sample(dir, expected)).reduce((s, p) => s + p.done, 0);
if (bucket.update(Date.now(), bytes)) this.pause();
else this.resume();
} catch (err) {
log.error(`speed limit check failed for job ${this.job.id}`, err);
this.resume();
} finally {
busy = false;
}
}, THROTTLE_MS);
}
private pause() {
if (this.paused || !this.child || this.child.exitCode !== null) return;
if (this.child.kill("SIGSTOP")) this.paused = true;
}
private resume() {
if (!this.paused || !this.child) return;
this.paused = false;
if (this.child.exitCode === null) this.child.kill("SIGCONT");
}
private async sample(dir: string, expected: ExpectedFile[]) { private async sample(dir: string, expected: ExpectedFile[]) {
const incomplete = await listIncomplete(dir); const incomplete = await listIncomplete(dir);
return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete))); return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete)));
+39
View File
@@ -0,0 +1,39 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { Throttle } from "./throttle";
describe("Throttle", () => {
it("lets a download at the limit run", () => {
const t = new Throttle(1000);
assert.equal(t.update(0, 0), false);
for (let s = 1; s <= 10; s++) assert.equal(t.update(s * 1000, s * 1000), false);
});
it("pauses after a burst until the budget has refilled", () => {
const t = new Throttle(1000);
t.update(0, 0);
assert.equal(t.update(1000, 5000), true); // 5 KB in 1 s at 1 KB/s with a 1 s burst: 4 KB over the budget
assert.equal(t.update(2000, 5000), true);
assert.equal(t.update(3000, 5000), true);
assert.equal(t.update(4000, 5000), true);
assert.equal(t.update(5000, 5000), false);
});
it("averages to the limit over time", () => {
const t = new Throttle(1000);
let bytes = 0;
t.update(0, 0);
for (let ms = 250; ms <= 60_000; ms += 250) {
const paused = t.update(ms, bytes);
if (!paused) bytes += 2000; // hf runs at 8 KB/s whenever it isn't stopped
}
assert.ok(bytes / 60 > 900);
assert.ok(bytes / 60 < 1100);
});
it("ignores shrinking byte counts", () => {
const t = new Throttle(1000);
t.update(0, 10_000);
assert.equal(t.update(1000, 0), false);
});
});
+32
View File
@@ -0,0 +1,32 @@
/**
* Download speed limit as a token bucket over bytes on disk. Neither `hf download` nor hf_xet has a
* bandwidth option (checked: huggingface_hub 2.1.1, hf_xet 1.6.0), so the worker pauses the hf
* process (SIGSTOP/SIGCONT) whenever it got ahead of the limit. While hf is stopped its socket
* buffers fill and TCP flow control holds the sender back, so the network rate follows.
*/
export class Throttle {
private tokens = 0;
private last: { t: number; bytes: number } | null = null;
/** `burstSeconds`: how far ahead of the limit hf may run before it is paused. */
constructor(
public limit: number,
private burstSeconds = 1,
) {}
/** Feed a (time ms, total bytes) sample; returns true while hf should be paused. */
update(t: number, bytes: number): boolean {
const cap = this.limit * this.burstSeconds;
if (!this.last) {
this.last = { t, bytes };
this.tokens = cap;
return false;
}
const dt = Math.max(0, t - this.last.t) / 1000;
// Bytes can shrink when partial files are removed; that's not negative traffic.
const used = Math.max(0, bytes - this.last.bytes);
this.tokens = Math.min(cap, this.tokens + this.limit * dt) - used;
this.last = { t, bytes };
return this.tokens < 0;
}
}