Перейти к содержимому
BIASED
К теме

По желанию

Часы батча и их границы

Приходы — упорядоченные непустые неотрицательные моменты. Один воркер обслуживает все принятые объекты; длительность — 4+2b мс. Цель ожидания отсчитывается от старейшего прихода, но занятый воркер может отправить батч позже. В конечной симуляции нет отмен и политики приёма; это не реализация сервера.

Версия
v2
Минут
~20
Проверка
Самопроверка в ноутбуке

Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.

Скачать .ipynb

Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.

Содержимое ноутбука

Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.

A batch clock and its limits / Часы батча и их границы

Optional practice; Python standard library only. The core lesson does not require running code. No downloads, network, accounts, models, user data or actual deployments.

Необязательная практика; только стандартная библиотека Python. Для основной темы запуск кода не требуется. Без загрузок, сети, аккаунтов, моделей, пользовательских данных или реальных деплоев.

Authored for the Fedor Pakhurov project with Codex assistance. Case functions and fictional inputs come from the independently reviewed first-party note and fixture at published revision 82b6cb07167b37710c6a786a3a41878a4e928483. New packaging and exact-arithmetic self-checks are added here. No exclusive copyright guarantee is asserted.

Note: https://github.com/fpakhurov/fpakhurov.com/blob/82b6cb07167b37710c6a786a3a41878a4e928483/src/content/notes/mlops/serving-models.mdx

Fixture: https://github.com/fpakhurov/fpakhurov.com/blob/82b6cb07167b37710c6a786a3a41878a4e928483/scripts/notes/mlops-renewal-cases.py

The note retains primary conceptual citations; no external source-specific dataset, model output, figure or code is included.

Inputs and limits / Входы и границы

Arrivals are ordered, nonempty, nonnegative timestamps. One worker serves every admitted item; service is 4+2b ms. The wait target uses the oldest arrival, but a busy worker can dispatch after that target. This finite simulation has no cancellation or admission policy and is not a server implementation.

Приходы — упорядоченные непустые неотрицательные моменты. Один воркер обслуживает все принятые объекты; длительность — 4+2b мс. Цель ожидания отсчитывается от старейшего прихода, но занятый воркер может отправить батч позже. В конечной симуляции нет отмен и политики приёма; это не реализация сервера.

import hashlib
import itertools
import json
import math
 
def serve(arrivals, max_batch, wait, fixed, per_item):
    pending = list(enumerate(arrivals))
    now = 0
    finish = {}
    batches = []
    while pending:
        now = max(now, pending[0][1])
        deadline = pending[0][1] + wait
        count = sum(at <= now for _, at in pending)
        if count < max_batch and now < deadline:
            full_at = pending[max_batch - 1][1] if len(pending) >= max_batch else math.inf
            now = max(now, min(deadline, full_at))
        selected = [item for item in pending if item[1] <= now][:max_batch]
        start = now
        now += fixed + per_item * len(selected)
        for index, _ in selected:
            finish[index] = now
        pending = pending[len(selected):]
        batches.append({"start_ms": start, "finish_ms": now,
                        "requests": [index for index, _ in selected]})
    latencies = [finish[i] - at for i, at in enumerate(arrivals)]
    return {"batches": batches, "latencies_ms": latencies,
            "mean_latency_ms": sum(latencies) / len(latencies),
            "burst_finish_ms": now, "completed_per_second_in_burst": 1000 * len(arrivals) / now}
 
def serving():
    arrivals = [0, 2, 3, 9, 10, 17]
    single = serve(arrivals, 1, 0, 4, 2)
    batched = serve(arrivals, 3, 3, 4, 2)
    assert single["burst_finish_ms"] == 36
    assert batched["burst_finish_ms"] == 27
    return {"arrivals_ms": arrivals, "service_ms": "4 + 2 * batch_size",
            "single": single, "batched": batched}
result = serving()
print(json.dumps(result, indent=2, allow_nan=False))

Check independently / Независимая проверка

The checks below use conservation, exact arithmetic or boundary cases in addition to the case function. Passing them establishes these declared examples, not production reliability.

Ниже проверяются сохранение, точная арифметика или граничные случаи сверх функции примера. Их прохождение устанавливает эти заданные примеры, а не надёжность продакшена.

arrivals = result["arrivals_ms"]
for mode in ["single", "batched"]:
    batches = result[mode]["batches"]
    assert [i for b in batches for i in b["requests"]] == list(range(len(arrivals)))
    assert all(arrivals[i] <= b["start_ms"] for b in batches for i in b["requests"])
    assert all(a["finish_ms"] <= b["start_ms"] for a,b in zip(batches,batches[1:]))
assert result["batched"]["latencies_ms"] == [13,11,10,12,11,10]
assert serve([0],3,3,4,2)["latencies_ms"] == [9]
assert serve([0],1,0,4,2)["latencies_ms"] == [6]
print("Self-checks passed: conservation, causality, nonoverlap and low-load counterexample.")

Change one assumption / Измените одно предположение

Compare one isolated request with wait 0 and wait 3. Then change an arrival gap and inspect whose latency improves or worsens, rather than inferring sustained capacity from the finite burst.

Сравните один изолированный запрос при ожидании 0 и 3. Затем измените промежуток прихода и проследите улучшение или ухудшение задержек отдельных запросов вместо вывода об устойчивой ёмкости по конечному всплеску.