diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3f7c63e..3601a17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,11 @@ step 1 (Hugging Face downloader) is released as a minor version.
### 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
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
diff --git a/src/app/(app)/settings/downloads/page.tsx b/src/app/(app)/settings/downloads/page.tsx
index c556ae7..6dc0852 100644
--- a/src/app/(app)/settings/downloads/page.tsx
+++ b/src/app/(app)/settings/downloads/page.tsx
@@ -1,10 +1,16 @@
import type { Metadata } from "next";
-import { getRecommendedRoles } from "@/lib/settings";
+import { getDownloadSpeedLimit, getRecommendedRoles } from "@/lib/settings";
import { RecommendedSettings } from "./recommended-settings";
+import { SpeedLimit } from "./speed-limit";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Downloads · Settings" };
export default async function DownloadSettingsPage() {
- return ;
+ return (
+
+
+
+
+ );
}
diff --git a/src/app/(app)/settings/downloads/speed-limit.tsx b/src/app/(app)/settings/downloads/speed-limit.tsx
new file mode 100644
index 0000000..9b590eb
--- /dev/null
+++ b/src/app/(app)/settings/downloads/speed-limit.tsx
@@ -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 (
+
+
+ Speed limit
+
+ 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.
+
+
+
+
+
+ {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.`}
+
+
+
+ );
+}
diff --git a/src/app/api/settings/downloads/route.ts b/src/app/api/settings/downloads/route.ts
index bfb6ce9..df69727 100644
--- a/src/app/api/settings/downloads/route.ts
+++ b/src/app/api/settings/downloads/route.ts
@@ -2,19 +2,28 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
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";
-/** Download settings: which file kinds are picked along with model weights. */
-export const GET = withAuth(async () => NextResponse.json({ recommendedRoles: await getRecommendedRoles() }));
+async function current() {
+ 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) => {
try {
- const { recommendedRoles } = Body.parse(await req.json());
- return NextResponse.json({ recommendedRoles: await saveRecommendedRoles(recommendedRoles) });
+ const body = Body.parse(await req.json());
+ if (body.recommendedRoles) await saveRecommendedRoles(body.recommendedRoles);
+ if (body.maxBytesPerSecond !== undefined) await saveDownloadSpeedLimit(body.maxBytesPerSecond);
+ return NextResponse.json(await current());
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
diff --git a/src/lib/download-limit.ts b/src/lib/download-limit.ts
new file mode 100644
index 0000000..8b3d01d
--- /dev/null
+++ b/src/lib/download-limit.ts
@@ -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;
+}
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 7f71b81..2d0b362 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -4,6 +4,7 @@ import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { isLabelColor } from "@/lib/colors";
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";
const FILE_ROLES_KEY = "labels.fileRoles";
@@ -84,3 +85,17 @@ export async function saveRecommendedRoles(roles: string[]): Promise
await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r)));
return getRecommendedRoles();
}
+
+/** Download speed limit in bytes per second (Settings → Downloads), or null for no limit. */
+export async function getDownloadSpeedLimit(): Promise {
+ return parseSpeedLimit(await read(SPEED_LIMIT_KEY));
+}
+
+export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Promise {
+ 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();
+}
diff --git a/src/worker/download.ts b/src/worker/download.ts
index 0b83735..2cddd7a 100644
--- a/src/worker/download.ts
+++ b/src/worker/download.ts
@@ -11,7 +11,9 @@ import {
jobs,
modelFiles,
models,
+ settings,
} from "@/lib/db/schema";
+import { parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { escapeGlob } from "@/lib/selection";
@@ -29,9 +31,17 @@ import { log } from "./log";
import { settleModelStatus } from "./model-status";
import type { Runner } from "./runner";
import { SpeedMeter } from "./speed";
+import { Throttle } from "./throttle";
const SAMPLE_MS = 1_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();
/** Environment variables passed through to hf (everything else, e.g. AUTH_SECRET, is withheld). */
const PASSTHROUGH_ENV = [
@@ -64,6 +74,7 @@ export class DownloadRunner implements Runner {
private stopReason?: "cancelled" | "interrupted";
private killTimer?: NodeJS.Timeout;
private jobLog: JobLog;
+ private paused = false;
constructor(
private job: Job,
@@ -100,6 +111,7 @@ export class DownloadRunner implements Runner {
this.stopReason = reason;
this.jobLog.system(reason === "cancelled" ? "Cancel requested, stopping hf…" : "Worker shutting down, stopping hf…");
if (!this.child || this.child.exitCode !== null) return;
+ this.resume(); // a stopped process only handles SIGTERM once it runs again
killTree(this.child, "SIGTERM");
this.killTimer = setTimeout(() => {
if (this.child && this.child.exitCode === null) killTree(this.child, "SIGKILL");
@@ -272,6 +284,8 @@ export class DownloadRunner implements Runner {
if (settled) return;
settled = true;
clearInterval(timer);
+ clearInterval(throttleTimer);
+ running.delete(this);
this.jobLog.end();
resolve(r);
};
@@ -291,6 +305,8 @@ export class DownloadRunner implements Runner {
}),
);
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.
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[]) {
const incomplete = await listIncomplete(dir);
return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete)));
diff --git a/src/worker/throttle.test.ts b/src/worker/throttle.test.ts
new file mode 100644
index 0000000..274bc16
--- /dev/null
+++ b/src/worker/throttle.test.ts
@@ -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);
+ });
+});
diff --git a/src/worker/throttle.ts b/src/worker/throttle.ts
new file mode 100644
index 0000000..d7b34a9
--- /dev/null
+++ b/src/worker/throttle.ts
@@ -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;
+ }
+}