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:
1 parent
b623b16a6d
commit
85af566b93
9 files changed
+285
-8
No files matched your search
@@ -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<DownloadRunner>();
|
||||
|
||||
/** 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)));
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user