File size: 12,289 Bytes
5487a45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Offline, run-audited sequence alignment. No fixed receive-time window.

All identities remain inferred. Duration is an alignment feature, so duration
agreement after matching is NOT independent proof of timing accuracy.
"""
import bisect
import math

import numpy as np
import numba
from numba import njit

VERSION = "rank-sequence-alignment-v2"


def correlation(a, b):
    if len(a) < 3 or np.std(a) == 0 or np.std(b) == 0:
        return None
    return float(np.corrcoef(a, b)[0, 1])


def sglang_groups(records, expected, full_timed, ordinals):
    lengths = [len(full_timed[r]) for r in expected]
    if not lengths[0] or len(set(lengths)) != 1:
        raise ValueError("SGLang ordinal join requires equal full-capture timed counts")
    n = lengths[0]
    ref = np.asarray(full_timed[expected[0]])
    checks = {}
    for rank in expected[1:]:
        other = np.asarray(full_timed[rank])
        global_corr = correlation(ref, other)
        windows, failed, minimum = 0, [], 1.0
        for low in range(0, n, 1000):
            high = min(n, low+1000)
            if high-low < 3:
                continue
            zero = correlation(ref[low:high], other[low:high])
            prev = correlation(ref[low+1:high], other[low:high-1])
            following = correlation(ref[low:high-1], other[low+1:high])
            windows += 1
            if zero is None or zero < .7 or any(c is not None and c >= zero for c in (prev, following)):
                failed.append(low)
            if zero is not None:
                minimum = min(minimum, zero)
        if global_corr is None or global_corr < .995 or failed:
            raise ValueError(f"SGLang ordinal audit failed for rank {rank}: {failed}")
        checks[str(rank)] = dict(global_correlation=global_corr, checked_windows=windows,
                                 failed_windows=failed, minimum_zero_lag_correlation=minimum)
    groups = {}
    selected = {}
    for row in records:
        ordinal = ordinals[row["source_line"]]
        groups.setdefault(ordinal, []).append(row)
        selected.setdefault(row["dp_rank"], []).append(ordinal)
    output = []
    for ordinal, group in sorted(groups.items()):
        output.append((sorted(group, key=lambda r: r["dp_rank"]),
                       dict(method="validated_full_capture_timed_ordinal", full_capture_ordinal=ordinal)))
    return output, dict(method="validated_full_capture_timed_ordinal", version=VERSION,
                        full_capture_timed_counts=dict(zip(expected, lengths)),
                        selected_ordinal_ranges={r:[min(v),max(v)] for r,v in selected.items()},
                        zero_lag_vs_adjacent_lag_audits=checks,
                        warning="Run-specific inferred correspondence; not a publisher-certified global ID.")


@njit
def segment(at, aw, bt, bw, gap):
    n, m = len(aw), len(bw)
    cost = np.zeros((n+1, m+1))
    trace = np.zeros((n+1, m+1), dtype=np.uint8)
    for i in range(1,n+1):
        cost[i,0], trace[i,0] = gap*i, 1
    for j in range(1,m+1):
        cost[0,j], trace[0,j] = gap*j, 2
    for i in range(1,n+1):
        for j in range(1,m+1):
            scale = .00003 + .0001*max(aw[i-1],bw[j-1])
            duration = math.log1p(abs(aw[i-1]-bw[j-1])/scale)
            timing = .10*min(abs(at[i-1]-bt[j-1])/(.002+max(aw[i-1],bw[j-1])),10.)
            values = (cost[i-1,j-1]+duration+timing, cost[i-1,j]+gap, cost[i,j-1]+gap)
            op = 0
            if values[1] < values[op]:
                op = 1
            if values[2] < values[op]:
                op = 2
            cost[i,j], trace[i,j] = values[op], op
    result = np.full(n,-1,dtype=np.int64)
    i,j=n,m
    while i or j:
        op=trace[i,j]
        if op==0:
            result[i-1]=j-1
            i-=1
            j-=1
        elif op==1:
            i-=1
        else:
            j-=1
    return result


def candidates(a,b,radius):
    center=np.searchsorted(b[:,0],a[:,0]).clip(0,len(b)-1)
    js=center[:,None]+np.arange(-radius,radius+1)
    valid=(js>=0)&(js<len(b))
    safe=js.clip(0,len(b)-1)
    maximum=np.maximum(a[:,1,None],b[safe,1])
    delta=abs(a[:,1,None]-b[safe,1])
    score=delta/(.00005+.0001*maximum)
    score+=.10*abs(a[:,0,None]-b[safe,0])/(.002+maximum)
    score[~valid]=np.inf
    order=np.argsort(score,axis=1,kind="stable")
    ix=np.arange(len(a))
    best=safe[ix,order[:,0]]
    values=score[ix,order[:,0]]
    margin=score[ix,order[:,1]]-values
    good=(delta[ix,order[:,0]]<.00005+.0001*maximum[ix,order[:,0]])&(values<2)&(margin>.2)
    return best,good


def anchors(a,b,radius):
    best,good=candidates(a,b,radius)
    inverse,other_good=candidates(b,a,radius)
    indices=np.flatnonzero(good&other_good[best]&(inverse[best]==np.arange(len(a))))
    tails,tail_indices=[],[]
    predecessors=np.full(len(indices),-1,dtype=int)
    for k,i in enumerate(indices):
        j=int(best[i]);pos=bisect.bisect_left(tails,j)
        if pos:
            predecessors[k]=tail_indices[pos-1]
        if pos==len(tails):
            tails.append(j);tail_indices.append(k)
        else:
            tails[pos]=j;tail_indices[pos]=k
    selected=[]
    if tail_indices:
        k=tail_indices[-1]
        while k>=0:
            selected.append(indices[k]);k=predecessors[k]
    selected=np.asarray(selected[::-1],dtype=int)
    return selected,best[selected],len(indices)-len(selected)


def pair(a,b,radius=12,gap=4.):
    ia,ib,crossings=anchors(a,b,radius)
    result=np.full(len(a),-1,dtype=int)
    result[ia]=ib
    weak=np.zeros(len(a),dtype=bool)
    longest=(0,0);unresolved=[]
    bounds=list(zip([-1,*ia,len(a)],[-1,*ib,len(b)]))
    for (i,j),(ni,nj) in zip(bounds[:-1],bounds[1:]):
        lowa,lowb=int(i+1),int(j+1);ni,nj=int(ni),int(nj)
        n,m=ni-lowa,nj-lowb
        if not n or not m:
            continue
        if n*m>longest[0]*longest[1]:
            longest=(n,m)
        if n*m>1_000_000:
            unresolved.append((lowa,ni,lowb,nj));continue
        local=segment(a[lowa:ni,0],a[lowa:ni,1],b[lowb:nj,0],b[lowb:nj,1],gap)
        matched=local>=0
        selected=np.arange(lowa,ni)[matched]
        result[selected]=local[matched]+lowb
        # One isolated record among many missing steps is not enough to locate
        # a unique iteration, even if the minimum-cost path picks one.
        if max(n,m)>32 and min(n,m)<4:
            weak[selected]=True
    return result,weak,dict(anchors=len(ia),anchor_crossings_rejected=crossings,
                            largest_segment=longest,unresolved_segments=unresolved,
                            matched=int((result>=0).sum()),weak_sparse_matches=int(weak.sum()))


def vllm_groups(records,expected):
    by_rank={r:[] for r in expected}
    for row in records:
        by_rank[row["dp_rank"]].append(row)
    for values in by_rank.values():
        values.sort(key=lambda r:r["counter_id"])
        if not values:
            raise ValueError("No positive records for an expected vLLM rank")
    origin=min(row["received_at_ns"] for row in records)
    data={r:np.asarray([((x["received_at_ns"]-origin)/1e9,x["wall_time"]) for x in values])
          for r,values in by_rank.items()}
    if any(np.any(np.diff(a[:,0])<0) for a in data.values()):
        raise ValueError("Recorder clock is not monotonic within a rank")
    primary=max(expected,key=lambda r:len(by_rank[r]))
    # Explicit independent reference for this validated capture; not a producer ID.
    secondary=3 if 3 in expected and primary!=3 else next(r for r in expected if r!=primary)
    maps,weakness,summaries={},{},{}
    for ref in (primary,secondary):
        maps[ref]={ref:np.arange(len(data[ref]))}
        weakness[ref]={ref:np.zeros(len(data[ref]),dtype=bool)}
        summaries[str(ref)]={}
        for rank in expected:
            if rank==ref:
                continue
            mapping,weak,summary=pair(data[ref],data[rank])
            maps[ref][rank],weakness[ref][rank]=mapping,weak
            summaries[str(ref)][str(rank)]=summary
    final={primary:maps[primary][primary].copy()}
    consistency={};sensitivity={};rejected={}
    middle=maps[primary][secondary]
    for rank in expected:
        if rank==primary:
            continue
        direct=maps[primary][rank]
        transitive=np.full(len(direct),-1,dtype=int)
        exists=middle>=0
        transitive[exists]=maps[secondary][rank][middle[exists]]
        both=(direct>=0)&(transitive>=0)
        conflict=both&(direct!=transitive)
        alternative,_,_=pair(data[primary],data[rank],radius=24,gap=3.)
        competing=(direct>=0)&(alternative>=0)&(direct!=alternative)
        # A conservative run can abstain on a true prefill duration difference;
        # abstention is not a conflicting positive correspondence.
        accept=~(conflict|competing|weakness[primary][rank])
        result=direct.copy();result[~accept]=-1
        final[rank]=result
        consistency[str(rank)]=dict(shared_pairs=int(both.sum()),
                                    matching_pairs=int((both&~conflict).sum()),
                                    competing_pairs=int(conflict.sum()))
        sensitivity[str(rank)]=dict(competing_positive_pairs=int(competing.sum()),
                                    conservative_abstentions=int(((direct>=0)&(alternative<0)).sum()))
        rejected[str(rank)]=int(((direct>=0)&~accept).sum())
    used=set();output=[]
    for i in range(len(data[primary])):
        members=[]
        for rank in expected:
            j=int(final[rank][i])
            if j<0:
                continue
            row=by_rank[rank][j]
            if row["source_line"] in used:
                raise ValueError("Sequence matching reused an observation")
            used.add(row["source_line"]);members.append(row)
        output.append((members,dict(method="monotone_anchor_sequence", reference_rank=primary,
                                   reference_counter_id=by_rank[primary][i]["counter_id"],
                                   reference_sequence_index=i,assignment="matched_to_reference")))
    orphan_count=0
    for row in sorted(records,key=lambda r:(r["received_at_ns"],r["dp_rank"],r["source_line"])):
        if row["source_line"] not in used:
            output.append(([row],dict(method="monotone_anchor_sequence",assignment="unresolved_observation")))
            used.add(row["source_line"]);orphan_count+=1
    assert len(used)==len(records)
    return output,dict(method="monotone_anchor_sequence",version=VERSION,
                        primary_reference_rank=primary,secondary_reference_rank=secondary,
                        positive_records_per_rank={r:len(v) for r,v in by_rank.items()},
                        pairwise=summaries,reference_path_consistency=consistency,
                        sensitivity=sensitivity,rejected_reference_matches=rejected,
                        unresolved_observations=orphan_count,
                        configuration=dict(anchor_candidate_radius_iterations=12,
                                           sensitivity_candidate_radius_iterations=24,
                                           gap_penalty=4.,sensitivity_gap_penalty=3.,
                                           max_segment_cells=1_000_000,
                                           weak_sparse_segment_max_dimension=32,
                                           weak_sparse_segment_min_dimension_exclusive=4),
                        duration_is_alignment_feature=True,
                        warning="Monotone sequence inference, not native global execution IDs. Equal duration after matching is not independent validation.")


def align_records(records,case,full_timed,ordinals):
    expected=case["expected_dp_ranks"]
    if len(expected)==1:
        groups=[([r],dict(method="single_rank")) for r in records]
        report=dict(method="single_rank",version=VERSION)
    elif case["backend"]=="sglang":
        groups,report=sglang_groups(records,expected,full_timed,ordinals)
    else:
        groups,report=vllm_groups(records,expected)
    report["dependencies"]={"numpy":np.__version__,"numba":numba.__version__}
    return groups,report