forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB0ec5cf8Tahinli1 month ago3839 commits

av1-timeline-report.py225 lines, 9.5 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Reads `EC_AV1_TIMELINE=1` TSV (stderr of decode_probe) and reports what
3bounds the wall: per-phase durations, reference waits, the critical path
4through the reference DAG, concurrency over time, and dispatcher cap waits.
5
6Usage: EC_AV1_TIMELINE=1 decode_probe f.obu 2>tl.tsv; av1-timeline-report.py tl.tsv
7"""
8import sys
9from statistics import median
10
11COLS = ("idx type show submit start refs_ready hdr_done tile_done recon_done "
12 "filters_done slot_fulfil grain_done output wait_slot wait_owner wait_us "
13 "pipe deps").split()
14INT = set(COLS) - {"type", "deps"}
15
16# (label, from, to) -- the phases of one frame, in order.
17PHASES = [
18 ("queue submit->start", "submit", "start"),
19 ("refwait start->refs", "start", "refs_ready"),
20 ("setup refs->hdr", "refs_ready", "hdr_done"),
21 ("parse hdr->tile", "hdr_done", "tile_done"),
22 ("recontail tile->recon", "tile_done", "recon_done"),
23 ("filters recon->filt", "recon_done", "filters_done"),
24 ("publish filt->fulfil", "filters_done", "slot_fulfil"),
25 ("grain fulfil->grain", "slot_fulfil", "grain_done"),
26 ("outwait grain->output", "grain_done", "output"),
27]
28# Which phase a chain segment's time is charged to (same order).
29CHAIN_KEYS = [p[0].split()[0] for p in PHASES]
30
31
32def load(path):
33 frames, caps, end = [], [], 0
34 with (open(path) if path != "-" else sys.stdin) as fh:
35 for line in fh:
36 f = line.rstrip("\n").split("\t")
37 if f[0] == "TL":
38 r = dict(zip(COLS, f[1:]))
39 for k in INT:
40 r[k] = int(r[k])
41 r["deps"] = [] if r["deps"] == "-" else [int(x) for x in r["deps"].split(",")]
42 frames.append(r)
43 elif f[0] == "TL_CAP":
44 caps.append((f[1], int(f[2]), int(f[3])))
45 elif f[0] == "TL_END":
46 end = int(f[1])
47 return {f["idx"]: f for f in frames}, caps, end
48
49
50def ms(us):
51 return us / 1000.0
52
53
54def stats(vals):
55 vals = sorted(v for v in vals if v is not None)
56 if not vals:
57 return None
58 p90 = vals[min(len(vals) - 1, int(round(0.9 * (len(vals) - 1))))]
59 return median(vals), p90, vals[-1], sum(vals), len(vals)
60
61
62def dur(r, a, b):
63 """Duration of one phase, or None when either end was never reached."""
64 if r[a] == 0 or r[b] == 0 or r[b] < r[a]:
65 return None
66 return r[b] - r[a]
67
68
69def main():
70 path = sys.argv[1] if len(sys.argv) > 1 else "-"
71 fr, caps, end = load(path)
72 if not fr:
73 sys.exit("no TL rows")
74 t0 = min(min(v for k, v in r.items() if k in INT and k not in
75 ("idx", "show", "wait_slot", "wait_owner", "wait_us", "pipe") and v > 0)
76 for r in fr.values())
77 wall = end - t0
78 n = len(fr)
79 npipe = sum(r["pipe"] for r in fr.values())
80 print(f"frames={n} (key={sum(1 for r in fr.values() if r['type']=='K')} "
81 f"shown={sum(r['show'] for r in fr.values())} pipelined_filters={npipe}/{n}) "
82 f"wall={ms(wall):.1f} ms (first event {ms(t0):.1f} ms, end {ms(end):.1f} ms)")
83
84 print("\n(a) per-frame phase durations, ms")
85 print(f"{'phase':24} {'n':>4} {'median':>8} {'p90':>8} {'max':>8} {'sum':>9} {'sum/wall':>8}")
86 for label, a, b in PHASES:
87 s = stats([dur(r, a, b) for r in fr.values()])
88 if not s:
89 print(f"{label:24} -")
90 continue
91 med, p90, mx, tot, cnt = s
92 print(f"{label:24} {cnt:>4} {ms(med):>8.2f} {ms(p90):>8.2f} {ms(mx):>8.2f} "
93 f"{ms(tot):>9.1f} {tot/wall:>8.2f}")
94 s = stats([dur(r, "start", "grain_done") for r in fr.values()])
95 if s:
96 print(f"{'TOTAL start->grain':24} {s[4]:>4} {ms(s[0]):>8.2f} {ms(s[1]):>8.2f} "
97 f"{ms(s[2]):>8.2f} {ms(s[3]):>9.1f} {s[3]/wall:>8.2f}")
98
99 print("\n(b) reference wait (start -> refs_ready), ms")
100 waits = [(dur(r, "start", "refs_ready") or 0, r) for r in fr.values() if r["start"]]
101 s = stats([w for w, _ in waits])
102 print(f" n={s[4]} median={ms(s[0]):.2f} p90={ms(s[1]):.2f} max={ms(s[2]):.2f} "
103 f"sum={ms(s[3]):.1f} ({s[3]/wall:.2f}x wall)")
104 zero = sum(1 for w, _ in waits if w < 1000)
105 print(f" frames waiting <1 ms: {zero}/{len(waits)}")
106 print(" top waiters (frame -> longest-blocking producer):")
107 for w, r in sorted(waits, key=lambda x: -x[0])[:10]:
108 print(f" f{r['idx']:<4}{r['type']} waited {ms(w):8.2f} on slot {r['wait_slot']} "
109 f"produced by f{r['wait_owner']} (deps {r['deps']})")
110
111 # (c) critical path. A frame's critical predecessor is the dependency
112 # whose slot publish is the LAST one -- the edge that actually released
113 # this frame's refs_ready.
114 def pred(r):
115 best, bt = None, -1
116 for d in r["deps"]:
117 p = fr.get(d)
118 if p is None:
119 continue
120 t = own_w[d]
121 if t > bt:
122 best, bt = p, t
123 return best
124
125 # Walk back from the frame on the longest WORK-WEIGHTED chain (the frame
126 # that finishes last is often in a short last-GOP chain: a key frame
127 # resets the DAG, so wall-clock-last is not dependency-deepest).
128 own_w = {}
129 for i in sorted(fr):
130 r = fr[i]
131 own_w[i] = max([own_w.get(d, 0) for d in r["deps"]] + [0]) + sum(
132 dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7])
133 tail = fr[max(own_w, key=lambda k: own_w[k])]
134 chain, cur = [], tail
135 while cur is not None:
136 chain.append(cur)
137 cur = pred(cur)
138 chain.reverse()
139 head = chain[0]
140 span_a = head["hdr_done"] or head["start"] or t0
141 span_b = max(tail["output"], tail["grain_done"])
142 print(f"\n(c) critical path: {len(chain)} frames "
143 f"({chain[0]['idx']} -> {chain[-1]['idx']}), "
144 f"{ms(span_b - span_a):.1f} ms = {(span_b-span_a)/wall*100:.1f}% of wall")
145 charge = dict.fromkeys(CHAIN_KEYS, 0)
146 slack = 0
147 for i, r in enumerate(chain):
148 for (label, a, b) in PHASES:
149 d = dur(r, a, b)
150 if d is None:
151 continue
152 k = label.split()[0]
153 if i == 0 and k in ("queue", "refwait"):
154 continue
155 # A frame's own wait is charged only for the part after its
156 # predecessor published -- before that the predecessor's own
157 # phases already account for the time.
158 if k == "refwait":
159 p = chain[i - 1]
160 d = max(0, r["refs_ready"] - max(r["start"], p["slot_fulfil"] or p["filters_done"]))
161 if k == "outwait" and r is not tail:
162 continue
163 charge[k] += d
164 if i:
165 p = chain[i - 1]
166 pt = p["slot_fulfil"] or p["filters_done"]
167 if r["start"] and r["start"] > pt:
168 slack += r["start"] - pt
169 print(f" {'segment':12} {'ms':>9} {'% of chain':>11}")
170 tot = span_b - span_a
171 for k in CHAIN_KEYS:
172 if charge[k]:
173 print(f" {k:12} {ms(charge[k]):>9.1f} {charge[k]/tot*100:>10.1f}%")
174 print(f" {'(late start)':12} {ms(slack):>9.1f} {slack/tot*100:>10.1f}% "
175 "producer published before the consumer's worker even started")
176 print(f" chain frames: {[r['idx'] for r in chain][:40]}"
177 f"{' ...' if len(chain) > 40 else ''}")
178
179 # Infinite-core lower bound: earliest finish of every frame if a core
180 # were always free -- own work only, no queueing.
181 own = {}
182 for i in sorted(fr):
183 r = fr[i]
184 w = sum(dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7])
185 own[i] = max([own.get(d, 0) for d in r["deps"]] + [0]) + w
186 crit = max(own, key=lambda k: own[k])
187 print(f" infinite-core bound (longest work-weighted chain, ends at f{crit}): "
188 f"{ms(own[crit]):.1f} ms = {own[crit]/wall*100:.1f}% of wall")
189 work = sum(sum(dur(r, a2, b2) or 0 for (_, a2, b2) in PHASES[2:7]) for r in fr.values())
190 print(f" frame-thread work total {ms(work):.1f} ms = {work/wall:.2f} cores' worth; "
191 f"work/bound = {work/own[crit]:.2f} (the parallelism the DAG would need)")
192
193 print("\n(d) concurrency (frames between start and slot publish), 10 ms ticks")
194 def tick(live, label):
195 counts = []
196 t = t0
197 while t < end:
198 counts.append(sum(1 for a, b in live if a <= t < b))
199 t += 10000
200 counts.sort()
201 lt2 = sum(1 for c in counts if c < 2)
202 print(f" {label:9} median={counts[len(counts)//2]:3} "
203 f"p90={counts[int(0.9*(len(counts)-1))]:3} max={counts[-1]:3} "
204 f"mean={sum(counts)/len(counts):5.2f} <2 for {lt2/len(counts)*100:5.1f}% of wall"
205 f" (<1: {sum(1 for c in counts if c<1)/len(counts)*100:.1f}%)")
206
207 end_of = lambda r: r["slot_fulfil"] or r["grain_done"] or r["filters_done"]
208 # in flight = dispatched and not yet published (includes frames blocked on
209 # a reference); running = past its reference waits, i.e. actually runnable.
210 tick([(r["start"], end_of(r)) for r in fr.values() if r["start"]], "in-flight")
211 tick([(r["refs_ready"], end_of(r)) for r in fr.values() if r["refs_ready"]], "running")
212 tick([(r["hdr_done"], r["tile_done"]) for r in fr.values() if r["hdr_done"] and r["tile_done"]],
213 "parsing")
214
215 print("\n(e) dispatcher in-flight cap waits")
216 for kind in ("decode", "show"):
217 k = [(b, e) for t_, b, e in caps if t_ == kind]
218 tot = sum(e - b for b, e in k)
219 mx = max((e - b for b, e in k), default=0)
220 print(f" {kind:7} blocks={len(k):5} total={ms(tot):9.1f} ms "
221 f"({tot/wall*100:5.1f}% of wall) max={ms(mx):.2f} ms")
222
223
224if __name__ == "__main__":
225 main()