"""24 small, inspectable LLM research exercises. CPU; no downloaded model/data.

These exercises test isolated mathematical properties, not paper benchmarks.
Run: python field-labs.py --lesson D08 --output D08-result.json
Run all: python field-labs.py --lesson all --output field-results.json
Sources and the exact scope of each exercise are linked from the D01-D24 lessons.
"""
import argparse
import json
import math
import platform
import random
import time
from pathlib import Path

import torch
from torch.nn import functional as F

torch.set_default_dtype(torch.float64)


def result(config, metrics, checks, limits):
    assert len(checks) >= 2 and all(value is True for value in checks.values()), checks
    return {"config": config, "metrics": metrics, "checks": checks, "limits": limits}


def d01():
    h = torch.tensor(1., requires_grad=True)
    state = h
    for _ in range(20):
        state = .5 * state
    state.backward()
    values = torch.tensor([2., 10.])
    weights = torch.tensor([.25, .75])
    context = float(weights @ values)
    return result({"steps": 20, "recurrent_multiplier": .5},
                  {"gradient": h.grad.item(), "analytical_gradient": .5 ** 20,
                   "attention_context": context},
                  {"chain_rule": abs(h.grad.item() - .5 ** 20) < 1e-12,
                   "convex_combination": context == 8. and abs(float(weights.sum()) - 1) < 1e-12},
                  "A scalar linear recurrence illustrates the gradient path. It is not an LSTM or a trained attention model.")


def d02():
    logits = torch.tensor([[2., 0., -1.], [0., 2., -1.], [1., 0., -1.]], requires_grad=True)
    labels = torch.tensor([0, 1, -100])
    loss = F.cross_entropy(logits, labels, ignore_index=-100)
    loss.backward()
    manual = -F.log_softmax(logits.detach(), dim=-1)[[0, 1], [0, 1]].mean()
    polluted = F.cross_entropy(logits.detach(), torch.tensor([0, 1, 2]))
    return result({"labels": labels.tolist(), "supervised_positions": 2},
                  {"masked_loss": loss.item(), "manual_loss": manual.item(),
                   "padding_as_target_loss": polluted.item(), "padding_gradient": logits.grad[2].abs().max().item()},
                  {"ignored_gradient_zero": float(logits.grad[2].abs().max()) == 0.,
                   "mean_uses_valid_labels": abs(loss.item() - manual.item()) < 1e-12,
                   "wrong_padding_changes_loss": abs(polluted.item() - loss.item()) > .1},
                  "The logits are fixed examples. Loss masking does not replace causal attention masking.")


def d03():
    budget = 10000.
    candidates = [25., 50., 100., 200., 400.]
    losses = [1 / n + 1 / (budget / n) for n in candidates]
    optimum = candidates[losses.index(min(losses))]
    return result({"budget_ND": budget, "loss_rule": "1/N + 1/D", "candidates": candidates},
                  {"losses": losses, "best_N": optimum, "best_D": budget / optimum},
                  {"stationary_point": optimum == math.sqrt(budget),
                   "symmetric_allocations": abs(losses[1] - losses[3]) < 1e-12},
                  "Coefficients and exponents are invented for calculus practice. They are not a fitted scaling law or measured FLOPs.")


def d04():
    # Two copies of each document, split AFTER duplication versus by source ID.
    rows = [(i, f"document-{i}") for i in range(20)] * 2
    naive_train, naive_test = rows[:20], rows[20:]
    grouped_train = [r for r in rows if r[0] < 15]
    grouped_test = [r for r in rows if r[0] >= 15]
    def overlap(train, test):
        known = {text for _, text in train}
        return sum(text in known for _, text in test) / len(test)
    naive, grouped = overlap(naive_train, naive_test), overlap(grouped_train, grouped_test)
    return result({"unique_documents": 20, "copies_per_document": 2, "split_unit": "source document"},
                  {"row_split_overlap": naive, "document_split_overlap": grouped,
                   "unique_training_documents": len(set(text for _, text in grouped_train))},
                  {"row_split_leaks": naive == 1., "group_split_separates_sources": grouped == 0.},
                  "An exact-match contamination demonstration. It does not model near duplicates, model collapse or semantic generalization.")


def d05():
    def rotation(angle):
        return torch.tensor([[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]])
    q, k = torch.tensor([1., 2.]), torch.tensor([3., -1.])
    score = torch.dot(rotation(.2) @ q, rotation(.7) @ k)
    shifted = torch.dot(rotation(1.2) @ q, rotation(1.7) @ k)
    relative = torch.dot(q, rotation(.5) @ k)
    x = torch.tensor([3., 4.])
    rms = lambda a: a / torch.sqrt(a.square().mean() + 1e-12)
    return result({"query_position_angle": .2, "key_position_angle": .7, "shared_shift": 1.},
                  {"score": score.item(), "shifted_score": shifted.item(),
                   "relative_score": relative.item(), "rms_scale_error": float((rms(x) - rms(7 * x)).abs().max())},
                  {"relative_rotation_identity": torch.allclose(score, relative, atol=1e-12),
                   "shared_shift_invariance": torch.allclose(score, shifted, atol=1e-12),
                   "rms_positive_scale_invariance": torch.allclose(rms(x), rms(7*x), atol=1e-10)},
                  "One two-dimensional rotation pair and RMS without learned gain. No length-extrapolation quality claim.")


def d06():
    balanced = torch.tensor([[.9, .1]] * 4 + [[.1, .9]] * 4)
    collapsed = torch.tensor([[.9, .1]] * 8)
    def routing(probs):
        counts = torch.bincount(probs.argmax(-1), minlength=2)
        fraction = counts / len(probs)
        return counts.tolist(), float(2 * (fraction * probs.mean(0)).sum()), int((counts - 4).clamp_min(0).sum())
    bc, bl, bd = routing(balanced)
    cc, cl, cd = routing(collapsed)
    return result({"tokens": 8, "experts": 2, "top_k": 1, "capacity_per_expert": 4, "aux_coefficient": 1.},
                  {"balanced_counts": bc, "collapsed_counts": cc, "balanced_aux": bl,
                   "collapsed_aux": cl, "balanced_overflow": bd, "collapsed_overflow": cd},
                  {"balanced_capacity_fits": bd == 0, "collapsed_overflow": cd == 4,
                   "aux_penalizes_this_collapse": cl > bl},
                  "Router probabilities are supplied, not trained. Overflow is counted; real dispatch policies may drop, reroute or use dropless execution.")


def d07():
    q, k, v = [torch.randn(8, 4) for _ in range(3)]
    logits = q @ k.T / 2
    causal = torch.ones(8, 8, dtype=torch.bool).tril()
    positions = torch.arange(8)
    window = causal & ((positions[:, None] - positions[None, :]) < 3)
    def attention(mask, value):
        return logits.masked_fill(~mask, -torch.inf).softmax(-1) @ value
    changed = v.clone()
    changed[0] += 10
    local_change = float((attention(window, v)[-1] - attention(window, changed)[-1]).abs().max())
    dense_change = float((attention(causal, v)[-1] - attention(causal, changed)[-1]).abs().max())
    return result({"length": 8, "width": 4, "window": 3},
                  {"dense_edges": int(causal.sum()), "local_edges": int(window.sum()),
                   "distant_value_effect_dense": dense_change, "distant_value_effect_local": local_change},
                  {"local_removes_edges": int(window.sum()) < int(causal.sum()),
                   "local_cannot_read_distant_value_in_one_layer": local_change == 0.,
                   "dense_negative_control": dense_change > 1e-6},
                  "A single-layer causal sliding window, not the complete Longformer pattern. Multiple layers or global tokens change the receptive field.")


def d08():
    state = torch.tensor([[2., 9.]])
    key = torch.tensor([1., 0.])
    value = torch.tensor([5.])
    beta, alpha = .5, .8
    additive = state + beta * torch.outer(value, key)
    delta = state + beta * torch.outer(value - state @ key, key)
    gated = alpha * state + beta * torch.outer(value - alpha * state @ key, key)
    matrix_form = alpha * state @ (torch.eye(2) - beta * torch.outer(key, key)) + beta * torch.outer(value, key)
    return result({"state": state.tolist(), "key": key.tolist(), "value": value.tolist(), "alpha": alpha, "beta": beta},
                  {"additive": additive.tolist(), "delta": delta.tolist(), "gated_delta": gated.tolist()},
                  {"delta_corrects_existing_value": torch.allclose(delta, torch.tensor([[3.5, 9.]])),
                   "gate_decays_other_key": abs(gated[0, 1].item() - 7.2) < 1e-12,
                   "two_gated_forms_agree": torch.allclose(gated, matrix_form, atol=1e-12)},
                  "One unit-norm key in a two-coordinate memory. No learned gates, chunkwise GPU kernel or complete Mamba/Gated DeltaNet model.")


def d09():
    decoupled = torch.tensor(2., requires_grad=True)
    coupled = torch.tensor(2., requires_grad=True)
    aw = torch.optim.AdamW([decoupled], lr=.1, betas=(0., 0.), eps=0., weight_decay=.1)
    adam = torch.optim.Adam([coupled], lr=.1, betas=(0., 0.), eps=0., weight_decay=.1)
    decoupled.grad = torch.tensor(.2)
    coupled.grad = torch.tensor(.2)
    aw.step()
    adam.step()
    return result({"initial_weight": 2., "gradient": .2, "lr": .1, "decay": .1, "betas": [0., 0.]},
                  {"adamw_weight": decoupled.item(), "adam_with_l2_weight": coupled.item(),
                   "fp32_adam_state_estimate_bytes_per_parameter": 16},
                  {"adamw_matches_decoupled_formula": abs(decoupled.item() - 1.88) < 1e-12,
                   "adaptive_l2_differs": abs(coupled.item() - 1.9) < 1e-12},
                  "Artificial betas isolate one update. The 16-byte estimate is FP32 parameter, gradient, and two moments only, excluding activations and temporary buffers.")


def d10():
    scores = torch.tensor([1000., 1001., 999., 1002.])
    values = torch.tensor([[1., 0.], [0., 2.], [3., 1.], [-1., 4.]])
    reference = scores.softmax(0) @ values
    maximum, denominator, numerator = -math.inf, 0., torch.zeros(2)
    for score, value in zip(scores.tolist(), values):
        new_max = max(maximum, score)
        scale = math.exp(maximum - new_max)
        denominator = denominator * scale + math.exp(score - new_max)
        numerator = numerator * scale + math.exp(score - new_max) * value
        maximum = new_max
    online = numerator / denominator
    naive_finite = bool(torch.isfinite(scores.exp()).all())
    return result({"scores": scores.tolist(), "streamed_chunk_size": 1},
                  {"reference_output": reference.tolist(), "online_output": online.tolist(),
                   "maximum_error": float((online - reference).abs().max()), "naive_exp_is_finite": naive_finite},
                  {"online_softmax_exact_within_roundoff": torch.allclose(online, reference, atol=1e-12),
                   "naive_negative_control_overflows": not naive_finite},
                  "An online softmax identity used in tiled attention; this Python loop is not FlashAttention and measures no GPU speedup.")


def d11():
    weights = torch.tensor([.1, .2, .3, 4.])
    scale = float(weights.abs().max()) / 7
    quantized = (weights / scale).round().clamp(-7, 7) * scale
    typical = torch.tensor([1., 1., 1., .1])
    shifted = torch.tensor([10., 10., 10., .1])
    error = quantized - weights
    return result({"bits": 4, "integer_range": [-7, 7], "scale": scale, "weights": weights.tolist()},
                  {"dequantized": quantized.tolist(), "weight_rmse": float(error.square().mean().sqrt()),
                   "typical_output_error": abs(float(typical @ error)), "shifted_output_error": abs(float(shifted @ error))},
                  {"rounding_bound": bool((error.abs() <= scale / 2 + 1e-12).all()),
                   "input_changes_output_error": abs(float(shifted @ error)) > abs(float(typical @ error))},
                  "Symmetric round-to-nearest in floating storage, not GPTQ/SmoothQuant implementation or packed 4-bit memory.")


def d12():
    x, w = torch.randn(3, 4), torch.randn(4, 4)
    a = torch.randn(2, 4, requires_grad=True)
    b = torch.zeros(4, 2, requires_grad=True)
    target = torch.randn(3, 4)
    output = x @ w.T + (x @ a.T) @ b.T
    F.mse_loss(output, target).backward()
    zero_a, nonzero_b = float(a.grad.abs().max()), float(b.grad.abs().max())
    with torch.no_grad():
        b -= .01 * b.grad
    merged = x @ (w + b @ a).T
    separate = x @ w.T + (x @ a.T) @ b.T
    return result({"input_width": 4, "output_width": 4, "rank": 2, "scale": 1.},
                  {"A_gradient_at_zero_B": zero_a, "B_gradient_at_zero_B": nonzero_b,
                   "merged_output_error": float((merged - separate).abs().max().detach()),
                   "adapter_parameters": a.numel() + b.numel()},
                  {"zero_B_blocks_first_A_gradient": zero_a == 0., "B_can_start_learning": nonzero_b > 0.,
                   "merge_is_algebraically_equivalent": torch.allclose(merged, separate, atol=1e-12)},
                  "One dense linear layer with no dropout. Tiny rank-2 dimensions do not save parameters here; real savings depend on r(d_in+d_out) versus d_in*d_out.")


def d13():
    policy = torch.tensor([-2., -3.], requires_grad=True)
    reference = torch.tensor([-2.5, -2.5])
    beta = .2
    margin = beta * ((policy[0] - policy[1]) - (reference[0] - reference[1]))
    loss = F.softplus(-margin)
    loss.backward()
    expected = -math.log(1 / (1 + math.exp(-.2)))
    return result({"policy_sequence_logp": policy.detach().tolist(), "reference_sequence_logp": reference.tolist(), "beta": beta},
                  {"margin": margin.item(), "loss": loss.item(), "sequence_logp_gradients": policy.grad.tolist()},
                  {"scalar_loss_matches_formula": abs(loss.item() - expected) < 1e-12,
                   "descent_increases_preferred_logp": policy.grad[0].item() < 0.,
                   "descent_decreases_rejected_logp": policy.grad[1].item() > 0.},
                  "Independent sequence log-probability variables show the local objective. They are not a normalized policy or a complete preference training run.")


def d14():
    # A transparent example-conditioned estimator, explicitly NOT an LLM.
    x = torch.tensor([[1.], [2.], [3.]])
    y = torch.tensor([2., 4., 6.])
    slope = float(torch.linalg.lstsq(x, y).solution[0])
    permuted = y.flip(0)
    permuted_slope = float(torch.linalg.lstsq(x, permuted).solution[0])
    smooth_scores = [.40, .49, .51, .60]
    threshold_scores = [int(s >= .5) for s in smooth_scores]
    return result({"input_examples": x.flatten().tolist(), "labels": y.tolist(), "permuted_labels": permuted.tolist()},
                  {"fitted_slope": slope, "permuted_slope": permuted_slope,
                   "continuous_metric": smooth_scores, "threshold_metric": threshold_scores},
                  {"examples_identify_linear_rule": abs(slope - 2) < 1e-12,
                   "label_mapping_matters_for_this_estimator": abs(slope - permuted_slope) > .5,
                   "threshold_creates_jump": threshold_scores == [0, 0, 1, 1]},
                  "Least squares is an analogy under an explicit linear-model assumption. It does not establish what an LLM learns in context or resolve emergence debates.")


def d15():
    n, correct, k = 6, 2, 3
    estimate = 1 - math.comb(n - correct, k) / math.comb(n, k)
    candidates = [False, True, False, True, False, False]
    verifier = [.9, .3, .6, .7, .5, .4]
    selected = max(range(n), key=lambda i: verifier[i])
    reward = torch.ones(4)
    advantage = (reward - reward.mean()) / (reward.std(unbiased=False) + 1e-8)
    return result({"n": n, "correct_count": correct, "k": k, "verifier_scores": verifier},
                  {"pass_at_1": correct / n, "estimated_pass_at_3": estimate,
                   "selected_is_correct": candidates[selected], "all_equal_reward_advantage": advantage.tolist()},
                  {"pass_at_k_combinatorics": abs(estimate - .8) < 1e-12,
                   "oracle_presence_is_not_selection": any(candidates) and not candidates[selected],
                   "equal_rewards_produce_zero_group_signal": bool((advantage == 0).all())},
                  "Fixed samples and a supplied verifier, not model generations. A zero centered reward term does not rule out gradients from KL or other losses.")


def d16():
    documents = [["cat", "sleeps"], ["cat", "sits", "mat"], ["dog", "runs"]]
    query, k1, b = ["cat"], 1.2, .75
    average = sum(map(len, documents)) / len(documents)
    scores = []
    for doc in documents:
        score = 0.
        for word in query:
            count, df = doc.count(word), sum(word in d for d in documents)
            idf = math.log(1 + (len(documents) - df + .5) / (df + .5))
            score += idf * count * (k1 + 1) / (count + k1 * (1 - b + b * len(doc) / average))
        scores.append(score)
    ranking = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
    gold = 1
    return result({"documents": documents, "query": query, "gold_document_index": gold, "k1": k1, "b": b},
                  {"bm25_scores": scores, "ranking": ranking,
                   "recall_at_1": int(gold in ranking[:1]), "recall_at_2": int(gold in ranking[:2])},
                  {"relevant_word_ranks_above_absence": scores[0] > scores[2],
                   "retrieval_cutoff_changes_gold_availability": gold not in ranking[:1] and gold in ranking[:2]},
                  "Word-token BM25 on three authored documents. A gold document is defined by the task, not by lexical relevance; no dense model or generator is run.")


def d17():
    # Deterministic mock tool environment. No web access, execution or LLM API.
    def episode(wrong_plan=False, wrong_tool=False):
        a, b = 7, 5
        action = "subtract" if wrong_plan else "add"
        returned = a - b if action == "subtract" else a + b
        if wrong_tool:
            returned = -1
        return {"action": action, "tool_result": returned, "reported_done": True,
                "environment_success": returned == 12, "calls": 1}
    baseline, plan_error, tool_error = episode(), episode(True), episode(False, True)
    return result({"task": "Return the sum of 7 and 5", "model": "none; deterministic mock planner"},
                  {"baseline": baseline, "plan_error": plan_error, "tool_error": tool_error},
                  {"baseline_succeeds": baseline["environment_success"],
                   "plan_error_is_observable": not plan_error["environment_success"],
                   "completion_claim_does_not_prove_success": tool_error["reported_done"] and not tool_error["environment_success"]},
                  "Only an environment/test-harness example. It does not reproduce an agent benchmark or assess an LLM's planning.")


def d18():
    scores = torch.tensor([[2., 0.], [.5, 1.5]], requires_grad=True)
    labels = torch.arange(2)
    aligned = .5 * (F.cross_entropy(scores, labels) + F.cross_entropy(scores.T, labels))
    shuffled = .5 * (F.cross_entropy(scores, labels.flip(0)) + F.cross_entropy(scores.T, labels.flip(0)))
    aligned.backward()
    return result({"image_text_logits": scores.detach().tolist(), "temperature": "absorbed into supplied logits"},
                  {"aligned_symmetric_loss": aligned.item(), "shuffled_symmetric_loss": shuffled.item(),
                   "logit_gradients": scores.grad.tolist()},
                  {"matched_pairs_lower_this_loss": aligned.item() < shuffled.item(),
                   "descent_strengthens_diagonal": bool((scores.grad.diag() < 0).all()),
                   "descent_weakens_off_diagonal": bool((scores.grad[[0, 1], [1, 0]] > 0).all())},
                  "A supplied 2x2 similarity matrix, not trained image/text encoders or a visual instruction model.")


def d19():
    labels = torch.tensor([1., 1., 1., 0.])
    overconfident, calibrated = torch.full((4,), .99), torch.full((4,), .75)
    brier = lambda p: float((p - labels).square().mean())
    ece_single_bin = lambda p: abs(float(p.mean()) - float(labels.mean()))
    return result({"binary_labels": labels.tolist(), "decision_threshold": .5, "ece_bins": "one occupied bin"},
                  {"accuracy_both": .75, "overconfident_brier": brier(overconfident),
                   "calibrated_brier": brier(calibrated), "overconfident_ece": ece_single_bin(overconfident),
                   "calibrated_ece": ece_single_bin(calibrated)},
                  {"same_hard_predictions": bool(((overconfident > .5) == (calibrated > .5)).all()),
                   "brier_distinguishes_probabilities": brier(calibrated) < brier(overconfident),
                   "single_bin_matches_empirical_frequency": ece_single_bin(calibrated) == 0.},
                  "Four fixed examples cannot establish deployment calibration. Bin definitions, sample size and distribution shift matter.")


def d20():
    candidates = {"identity": lambda x: x, "absolute": abs}
    visible, additional = [1, 2, 3], [-2, 0, 4]
    passes = lambda fn, cases: all(fn(x) == abs(x) for x in cases)
    initial = {name: passes(fn, visible) for name, fn in candidates.items()}
    expanded = {name: passes(fn, visible + additional) for name, fn in candidates.items()}
    return result({"task": "absolute value", "visible_inputs": visible, "additional_inputs": additional},
                  {"visible_test_pass": initial, "expanded_test_pass": expanded},
                  {"weak_tests_accept_wrong_program": initial["identity"],
                   "negative_case_exposes_bug": not expanded["identity"],
                   "correct_baseline_still_passes": expanded["absolute"]},
                  "Two fixed local functions illustrate test coverage. No downloaded code is executed and no repository benchmark score is reproduced.")


def d21():
    # Hand-authored labels, not attack prompts or personal data.
    requested_behavior = ["answer", "answer", "refuse", "refuse"]
    model_behavior = ["refuse", "answer", "refuse", "answer"]
    benign_refusal = sum(model_behavior[i] == "refuse" for i in [0, 1]) / 2
    harmful_answer = sum(model_behavior[i] == "answer" for i in [2, 3]) / 2
    return result({"requested_behavior": requested_behavior, "observed_behavior": model_behavior,
                   "synthetic_candidates": 16, "supplied_secret_rank": 2},
                  {"benign_false_refusal_rate": benign_refusal, "unsafe_answer_rate": harmful_answer,
                   "illustrative_rank_bits": math.log2(16) - math.log2(2)},
                  {"benign_and_unsafe_errors_have_separate_denominators": benign_refusal == .5 and harmful_answer == .5,
                   "rank_calculation": math.log2(16) - math.log2(2) == 3.},
                  "Labels and rank are supplied synthetic examples. Rank bits are not a measured privacy guarantee or evidence that a model memorized anything.")


def d22():
    clean = torch.tensor([2., 100.])
    corrupt = torch.tensor([0., 100.])
    readout = torch.tensor([3., 0.])
    clean_score, corrupt_score = float(clean @ readout), float(corrupt @ readout)
    causal_patch = corrupt.clone(); causal_patch[0] = clean[0]
    high_activation_patch = corrupt.clone(); high_activation_patch[1] = 0.
    restoration = (float(causal_patch @ readout) - corrupt_score) / (clean_score - corrupt_score)
    return result({"clean_activation": clean.tolist(), "corrupt_activation": corrupt.tolist(), "readout": readout.tolist()},
                  {"clean_score": clean_score, "corrupt_score": corrupt_score, "causal_patch_restoration": restoration,
                   "large_activation_patch_effect": float(high_activation_patch @ readout) - corrupt_score},
                  {"causal_patch_restores_output": restoration == 1.,
                   "large_activation_negative_control": float(high_activation_patch @ readout) == corrupt_score},
                  "A fully specified linear computation. Effects in real models depend on intervention site, clean/corrupt distribution and the chosen output metric.")


def d23():
    # Exact enumeration of masking, using fixed losses independent of mask pattern.
    losses = [1., 2., 3.]
    t = .5
    mean_estimator = 0.
    for mask in range(8):
        contribution = sum(losses[i] for i in range(3) if mask & (1 << i)) / t
        mean_estimator += contribution / 8
    w = torch.tensor(0., requires_grad=True)
    loss_before = (2 * w - 4).square()
    loss_before.backward()
    with torch.no_grad():
        updated = w - .1 * w.grad
    loss_after = float((2 * updated - 4).square())
    return result({"mask_probability": t, "fixed_token_losses": losses, "inner_learning_rate": .1},
                  {"expected_inverse_mask_weighted_sum": mean_estimator, "full_sum": sum(losses),
                   "inner_weight_before": w.item(), "inner_weight_after": updated.item(),
                   "inner_loss_before": loss_before.item(), "inner_loss_after": loss_after},
                  {"mask_weight_recovers_fixed_sum": abs(mean_estimator - sum(losses)) < 1e-12,
                   "inner_update_changes_fast_weight": updated.item() != w.item(),
                   "inner_fit_improves_this_example": loss_after < loss_before.item()},
                  "Fixed-loss masking and a separate scalar inner update. Actual diffusion losses depend on corrupted context; no diffusion sampler, TTT outer training or EWC model is reproduced.")


def d24():
    texts = {"ko": "나는 고양이를 좋아한다.", "en": "I like cats."}
    lengths = {language: {"characters": len(text), "utf8_bytes": len(text.encode("utf-8")),
                          "whitespace_pieces": len(text.split())} for language, text in texts.items()}
    macro = (.8 + .95) / 2
    weighted = (80 + 855) / (100 + 900)
    return result({"texts": texts, "language_counts": {"ko": 100, "en": 900},
                   "correct_counts": {"ko": 80, "en": 855}},
                  {"lengths": lengths, "macro_accuracy": macro, "example_weighted_accuracy": weighted},
                  {"utf8_is_not_character_count_for_korean": lengths["ko"]["utf8_bytes"] > lengths["ko"]["characters"],
                   "ascii_bytes_equal_characters": lengths["en"]["utf8_bytes"] == lengths["en"]["characters"],
                   "aggregate_weights_change_conclusion": weighted > macro},
                  "UTF-8 bytes and whitespace pieces are not a model tokenizer. One translated pair cannot estimate language fairness or general tokenization cost.")


LABS = {f"D{i:02}": globals()[f"d{i:02}"] for i in range(1, 25)}


def run(lesson, seed):
    torch.manual_seed(seed)
    random.seed(seed)
    started = time.perf_counter()
    report = LABS[lesson]()
    return {"format": "llm-daily-lab-field-v1", "codeVersion": 1, "lesson": lesson,
            "python": platform.python_version(), "torch": torch.__version__,
            "device": "cpu", "seed": seed, "threads": torch.get_num_threads(),
            **report, "seconds": round(time.perf_counter() - started, 4)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--lesson", choices=["all", *LABS], required=True)
    parser.add_argument("--seed", type=int, default=7)
    parser.add_argument("--output", default="field-result.json")
    args = parser.parse_args()
    torch.set_num_threads(2)
    reports = [run(lesson, args.seed) for lesson in (LABS if args.lesson == "all" else [args.lesson])]
    payload = reports if args.lesson == "all" else reports[0]
    Path(args.output).write_text(json.dumps(payload, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8")
    for report in reports:
        print(f"{report['lesson']}: {len(report['checks'])} checks passed ({report['seconds']}s)")


if __name__ == "__main__":
    main()
