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

По желанию

Обязательный пример, судья и учёт повторов

Заголовки, выходы, числа судьи, интервалы и токенные цены вымышлены. Здесь нет модели, платного API или частного запроса. Заранее обязательный пример может запретить выпуск при улучшении средней правильности.

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

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

Скачать .ipynb

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

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

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

A mandatory case, judge and retry ledger / Обязательный пример, судья и учёт повторов

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/llmops.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 / Входы и границы

Titles, outputs, judge counts, spans and token prices are fictional inputs. No model, paid API or private prompt is used. A predeclared required case can block release even when average correctness improves.

Заголовки, выходы, числа судьи, интервалы и токенные цены вымышлены. Здесь нет модели, платного API или частного запроса. Заранее обязательный пример может запретить выпуск при улучшении средней правильности.

import hashlib
import itertools
import json
import math
 
def llmops():
    # Authored format/evidence fixtures, not actual completions from a model.
    references = ["Map", "Queue", "Cache", "Trace", "Budget", "Clock", "Schema", "Drift"]
    previous = ["Map", "Queue", "Cache", "Trace", "Budget", "Time", "Schema", "Change"]
    candidate = ["Map", "Queue", "Cache", "Trace", "Budget", "Clock", "Format", "Drift"]
    old = [int(a == b) for a, b in zip(previous, references)]
    new = [int(a == b) for a, b in zip(candidate, references)]
    differences = [b-a for a,b in zip(old,new)]
    critical_index = 6
    gate = sum(differences) >= 0 and new[critical_index] == 1
    assert not gate
    trace = [{"operation": name, "start_ms": start, "finish_ms": end}
             for name, start, end in [("validate", 0, 2), ("retrieve", 2, 37),
                                      ("generate", 37, 112), ("parse", 112, 117)]]
    assert sum(span["finish_ms"]-span["start_ms"] for span in trace) == 117
    return {"references": references, "previous_outputs": previous, "candidate_outputs": candidate,
            "previous_correct": sum(old), "candidate_correct": sum(new), "items": len(old),
            "paired_differences": differences, "candidate_release_pass": gate,
            "critical_item": references[critical_index],
            "fictional_input_tokens": 800, "fictional_output_tokens": 120,
            "fictional_cost_per_call": 800 * 0.000002 + 120 * 0.000006,
            "with_one_retry_probability_0_2": (800 * 0.000002 + 120 * 0.000006) * 1.2,
            "judge_true_positive": 90, "judge_false_positive": 180,
            "judge_positive_precision": 90 / (90 + 180), "fictional_trace": trace,
            "trace_total_ms": 117}
result = llmops()
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.

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

from fractions import Fraction as F
assert sum(result["paired_differences"]) == 1
assert result["candidate_correct"] == 7 and result["previous_correct"] == 6
assert result["critical_item"] == "Schema" and result["candidate_release_pass"] is False
assert math.isclose(result["judge_positive_precision"],float(F(1,3)))
cost = 800*F(2,1_000_000) + 120*F(6,1_000_000)
assert math.isclose(result["fictional_cost_per_call"],float(cost))
assert math.isclose(result["with_one_retry_probability_0_2"],float(cost*F(6,5)))
assert result["fictional_trace"][-1]["finish_ms"] - result["fictional_trace"][0]["start_ms"] == 117
print("Self-checks passed: paired gain 1/8, mandatory failure, judge precision and retry costs.")

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

Move the mandatory-case declaration only as a separate hypothetical policy experiment, never after seeing evaluation results in a real gate. Add an overlap to the trace and compare sum of span durations with end-to-end time.

Изменяйте обязательный пример лишь как отдельный гипотетический эксперимент с политикой, а не после просмотра результатов реального критерия. Добавьте перекрытие в трассу и сравните сумму длительностей с полным временем.