File size: 9,958 Bytes
4e0b8f3
 
 
 
 
 
 
df1b2b5
4e0b8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df1b2b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e0b8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df1b2b5
 
 
4e0b8f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df1b2b5
4e0b8f3
 
 
 
 
 
 
df1b2b5
 
 
 
 
 
 
 
 
4e0b8f3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""Project outstanding study time from measured pilot, restart, geometry and publication records."""

from datetime import datetime,timezone
from math import ceil
from statistics import median

from .flatness_progress import geometry_coverage,published_pilot_timings
from .records import BATCHES,CONTEXT,HORIZONS,read_json,sha256,storage_root,time_now,write_json
from .report_records import completed


def primary_work(arms,runs):
    """Only unscored frozen checkpoints retain a test cost after their training is complete."""
    hours=0.
    publications=0
    for arm in arms:
        stage,method=arm["stage"],arm["method"]
        fitted=[r for r in runs if r["stage"]==stage and r["method"]==method and r["phase"]=="confirm"
                and completed(r) and r["tokens"]==HORIZONS[stage]]
        train_left=8-len(fitted)
        test_left=8-sum("test_nll" in r for r in fitted)
        test_hours=arm["projected_test_seconds_per_run"]/3600
        hours+=train_left*(arm["projected_hours_all_seeds"]/8-test_hours)+test_left*test_hours
        publications+=train_left+test_left
    return hours,publications


def adapter_gate_timing(arms, runs):
    """Replace the pilot's extrapolated host-probe time with the cost of the known gated updates."""
    from .windows import gate
    stage = "abstracts"
    steps = HORIZONS[stage] // (BATCHES[stage] * CONTEXT)
    calls = {seed: sum(bool(gate(seed, step)) for step in range(steps)) for seed in range(1, 9)}
    by_id = {r["id"]: r for r in runs}
    timings = {}
    for arm in arms:
        if arm["stage"] != stage or arm["method"] not in {"trace", "third"}:
            continue
        method = arm["method"]
        pilot = by_id.get(arm["pilot_run"])
        if not pilot or not pilot.get("steps") or not pilot.get("host_probe_seconds"):
            continue
        pilot_calls = sum(bool(gate(pilot["seed"], step)) for step in range(pilot["steps"]))
        if not pilot_calls:
            continue
        fitted = {r["seed"]: r for r in runs if r["stage"] == stage and r["method"] == method and
                  r["phase"] == "confirm" and completed(r) and r["tokens"] == HORIZONS[stage]}
        remaining = sorted(calls.keys() - fitted.keys())
        timed = [r for r in fitted.values() if r.get("host_probe_seconds") and r.get("steps") == steps]
        observed_calls = pilot_calls + sum(calls[r["seed"]] for r in timed)
        mean_seconds = (pilot["host_probe_seconds"] + sum(r["host_probe_seconds"] for r in timed)) / observed_calls
        remaining_calls = sum(calls[s] for s in remaining)
        scale = len(remaining) * steps / pilot["steps"]
        # The original whole-loop forecast already includes this scaled copy of the pilot's host time.
        adjustment = (remaining_calls * mean_seconds - scale * pilot["host_probe_seconds"]) / 3600
        timings[method] = {"pilot_run": pilot["id"], "pilot_calls": pilot_calls, "observed_calls": observed_calls,
                           "mean_host_seconds_per_call": mean_seconds, "registered_calls_by_seed": calls,
                           "remaining_seeds": remaining, "remaining_calls": remaining_calls,
                           "extrapolated_pilot_calls": scale * pilot_calls, "adjustment_hours": adjustment}
    return timings


def _release_benchmark(project,runs):
    """Freeze twelve recent end-to-end release intervals from checksum-matched completion receipts."""
    path=project/"results"/"feasibility"/"checkpoint-publication-time.json"
    if path.exists():
        return read_json(path)
    receipts=storage_root(project)/"releases"
    observations=[]
    for row in sorted(runs,key=lambda r:r["finished_at"],reverse=True):
        run=row["id"]
        record=receipts/(run+".json")
        if not record.is_file():
            continue
        receipt=read_json(record)
        if receipt["summary_sha256"]!=sha256(project/"results"/run/"summary.json"):
            continue
        end=datetime.fromtimestamp(record.stat().st_mtime,timezone.utc)
        seconds=(end-datetime.fromisoformat(row["finished_at"])).total_seconds()
        if seconds<0:
            raise ValueError(f"Publication receipt precedes {run}")
        observations.append({"run":run,"finished_training_at":row["finished_at"],"receipt_written_at":end.isoformat(),
                             "git_revision":receipt["git_revision"],"seconds":seconds})
        if len(observations)==12:
            result={"observations":observations,"basis":"Wall time between model completion and the local verified "
                    "Git and Hugging Face release receipt, sampled from the twelve latest published hybrid checkpoints."}
            write_json(path,result)
            return result
    return None


def remaining_work(project,study,primary,followup,uptime,original_done,original_total):
    """Separate the timing scenarios from statistical uncertainty about prediction and basin width."""
    counts=geometry_coverage(study)
    runs=[r for r in study["runs"] if completed(r)]
    hybrids=[r for r in runs if r["phase"] in {"hybrid","branch"}]
    covered=original_done+len(hybrids)+sum(c["complete"] for c in counts.values())
    total=original_total+8*(6+1)+sum(c["planned"] for c in counts.values())
    text=[f"Across training, references, final tests, hybrid runs and flatness evaluations, "
          f"**{covered}/{total} milestones are complete ({covered/total:.1%})** and {total-covered} remain. "
          "Each milestone has equal weight in this count. Data preparation, software and publications are recorded separately."]
    timing=published_pilot_timings(project)
    if not (timing and primary and followup):
        return text
    releases=_release_benchmark(project,hybrids)
    if not releases:
        return text
    arms=primary["arms"]
    confirm_hours,publications=primary_work(arms,runs)
    gate_timing=adapter_gate_timing(arms,runs)
    gate_adjustment=sum(t["adjustment_hours"] for t in gate_timing.values())
    confirm_hours+=gate_adjustment
    auxiliary_hours=0.
    for stage in HORIZONS:
        missing=sum(not any(r["stage"]==stage and r["phase"]=="pilot" and r["method"]==m for r in runs)
                    for m in ("hessian_norm","sham","combined"))
        seconds=max(a["pilot_loop_seconds"]+a["pilot_finalizing_seconds"] for a in arms if a["stage"]==stage)
        auxiliary_hours+=missing*seconds/3600
        publications+=missing
    # Charge a whole six-job block for a partly trained seed. The replay has its own measured proxy.
    finished={(r["seed"],r["method"]) for r in hybrids}
    blocks=sum(any((seed,m) not in finished for m in ("trunk","adaptive","late","trace","strong","always")) for seed in range(21,29))
    replays=sum((seed,"replay") not in finished for seed in range(21,29))
    hybrid_hours=blocks*(followup["observed_six_jobs_hours"]-(uptime or {}).get("observed_gap_hours",0.))
    hybrid_hours+=replays*(followup["estimated_one_replay_hours"]-(uptime or {}).get("replay_proxy_gap_hours",0.))
    release_times=sorted(obs["seconds"] for obs in releases["observations"])
    scenarios={}
    for name,estimate,release in (("typical",median,median(release_times)),
                                  ("slower",max,release_times[ceil(.9*len(release_times))-1])):
        geometry_hours=sum((c["planned"]-c["complete"])*estimate(r["cycle_seconds"] for r in timing["rows"]
                           if r["stage"]==stage)/3600 for stage,c in counts.items())
        costs={"confirmatory_training_and_test":confirm_hours,"hybrid_training_and_widths":hybrid_hours,
               "secondary_pilots":auxiliary_hours,"flatness_and_its_publication":geometry_hours,
               "original_model_publications":publications*release/3600}
        scenarios[name]={**costs,"total_hours":sum(costs.values())}
    now=time_now()
    available=168-(datetime.fromisoformat(now)-datetime.fromisoformat(primary["first_training_update_at"])).total_seconds()/3600
    write_json(project/"results"/"feasibility"/"remaining-work.json",
               {"as_of":now,"completed":covered,"planned":total,"remaining":total-covered,"remaining_hours_in_week":available,
                "hybrid_blocks_left_including_partial":blocks,"replays_left":replays,"remaining_primary_publications":publications,
                "geometry":counts,"adapter_gate_timing":gate_timing,"scenarios":scenarios})
    low,high=(scenarios[k]["total_hours"] for k in ("typical","slower"))
    text.append(f"Projected remaining machine time is **{low:.2f}–{high:.2f} hours**, including model publication and "
                f"geometry. There are {available:.2f} hours left in the original week. These are two timing scenarios. "
                "They use the recorded pilot rates, whole remaining hybrid seed blocks, the longest primary pilot as a proxy "
                "for each remaining secondary pilot, and median or slower diagnostic and release cycles. Machine or network "
                "interruptions can extend them. [Cost by task](../results/feasibility/remaining-work.json) · "
                "[Observed release times](../results/feasibility/checkpoint-publication-time.json)")
    if gate_timing:
        actual=sum(t["remaining_calls"] for t in gate_timing.values())
        scaled=sum(t["extrapolated_pilot_calls"] for t in gate_timing.values())
        text.append(f"The registered adapter schedules require {actual:,} host derivative calls across unfinished "
                    f"runs. Scaling the pilot by token count alone gives {scaled:,.0f}. Pricing the scheduled calls "
                    f"at each method’s measured mean changes the forecast by {gate_adjustment:+.2f} hours. "
                    "The original pre-test feasibility record retains its initial estimate. "
                    "[Per-arm counts and observed costs](../results/feasibility/remaining-work.json) · "
                    "[Training gate](../src/thirdloss/windows.py)")
    return text