diff --git a/Framework/Core/scripts/dpl-tune/README.md b/Framework/Core/scripts/dpl-tune/README.md index 8da1ad43e75ba..6f8e385f31632 100644 --- a/Framework/Core/scripts/dpl-tune/README.md +++ b/Framework/Core/scripts/dpl-tune/README.md @@ -11,10 +11,10 @@ Python 3 standard library only. | option | changed when | metrics used | |---|---|---| | `--aod-memory-rate-limit` | the devices are mostly idle and few TFs are in flight | `total-timeframes-in-flight`, `table-bytes-*-created`, `total_wall_time_ms` | -| `--pipeline dev:N` | one device is the slowest by at least 1.3x and can be pipelined | `total_wall_time_ms`, `cpuUsedAbsolute` | +| `--pipeline dev:N` | one device is the slowest by at least 1.3x and can be pipelined, or the devices within 1.3x of it can all be, and pipelining them together gains 1.3x | `total_wall_time_ms`, `cpuUsedAbsolute` | | `--readers` | the AOD reader becomes the slowest device | `total_wall_time_ms`, `aod-file-read-info` | -| `--timeframes-rate-limit` | an explicit limit would cap the TFs in flight | `total-timeframes-in-flight` | -| `--shm-segment-size` | only raised, to twice the in-flight data | sampled shared memory, `arrow-bytes-delta` | +| `--timeframes-rate-limit` | analysis: an explicit limit would cap the TFs in flight; reconstruction: the limit binds while the devices are idle (measured, or inferred when the TFs in flight are not in the metrics), or the probe exceeds the budget | `total-timeframes-in-flight`; reconstruction: `performed_computations` of the reader, `total-timeframes-consumed`, else the busy times along the topology's critical path | +| `--shm-segment-size` | only raised, to twice the in-flight data | sampled shared memory, `arrow-bytes-delta`, `total_bytes_out` | The steady state is taken from the first to the last completed TF (`total-timeframes-consumed`). The throughput is modelled as limited by the @@ -75,6 +75,9 @@ dpl-tune run workflow.json --inputs inputs.txt --files 4 --tuning out/tuning.jso Install with `pip install ./Framework/Core/scripts/dpl-tune/` to get a `dpl-tune` command, or run `python3 dpl_tune.py` directly. +`python3 -m unittest` in this directory runs the tests, on a synthetic +reconstruction (no O2 needed). + ## Outputs - `tuning.md`: the changes with the numbers behind them, the observations, the @@ -91,11 +94,21 @@ Install with `pip install ./Framework/Core/scripts/dpl-tune/` to get a plus the resident size of the shared-memory segment). The sum is an upper bound: shared pages are counted once per process touching them. On Linux PSS is read from `/proc//smaps_rollup`, which counts them once. -- **Reconstruction**: only `--pipeline` is tuned, and only when a device is - busy most of the time. The TFs in flight, the shared memory free and the - dropped messages are not in `performanceMetrics.json`, so - `--timeframes-rate-limit` and `--shm-segment-size` cannot be tuned for - reconstruction without more metrics. +- **Reconstruction**: `--timeframes-rate-limit` and `--shm-segment-size` need + the TFs in flight, which O2 writes to `performanceMetrics.json` only since + "DPL: dump the rate limiting and drop metrics". With an older O2 the driver's + `total-timeframes-in-flight` is negative (only the AOD reader counts the TFs + read), so it is ignored, and whether the configured limit binds is inferred + with Little's law: the busy times per TF along the critical path of the + topology, a lower bound of the latency, against the limit times the observed + s/TF. The memory per TF is then the shm segment size over the limit, an + upper bound, unless the shm or `total_bytes_out` metrics give it; the + segment is scaled with the limit. `tuning.md` says when the limit is inferred. + A TF source (e.g. the CTF reader) waits in its callback for the TF rate + limit, so its CPU time, not its wall time, is used as its busy time. + `performed_computations` is published at most every 5 s, so the TFs in + flight are sampled coarsely. `tuning.md` lists dropped computations and + messages, missing resource offers and whether the TF limit binds. - **Readers guard**: in the O2 versions tested, `--readers` > 1 combined with `--aod-memory-rate-limit` deadlocked (the readers wait for AOD memory offers that never come). When a verification with both fails, the extra readers are diff --git a/Framework/Core/scripts/dpl-tune/dpl_tune.py b/Framework/Core/scripts/dpl-tune/dpl_tune.py index 0dd7363554187..3b6bbfb4a255b 100755 --- a/Framework/Core/scripts/dpl-tune/dpl_tune.py +++ b/Framework/Core/scripts/dpl-tune/dpl_tune.py @@ -55,6 +55,9 @@ # we set them in every metadata entry and on the driver command line. GLOBAL_KNOBS = ["--readers", "--aod-memory-rate-limit", "--shm-segment-size", "--timeframes-rate-limit"] NOT_PIPELINABLE = re.compile(r"^internal-dpl-|writer|sink|reader|proxy|^ctf-reader$") +SOURCE = re.compile(r"^(?!internal-dpl-).*(reader|proxy)") # devices that inject the TFs of a reconstruction +# Counters dumped since "DPL: dump the rate limiting and drop metrics": anything above 0 is flagged +FLOW_METRICS = ["dropped_computations", "dropped_incoming_messages", "resources-missing", "resources-insufficient"] # Readers guard: in the O2 versions this tool was tested with, --readers > 1 combined with # --aod-memory-rate-limit deadlocked (every reader waits for an AOD memory offer that never comes, after # a few TFs). With the guard on, a failed verification of a tuning containing both backs off the extra @@ -194,6 +197,43 @@ def is_source(spec): return not spec.get("inputs") or lifetimes <= {"1", "4", "5", "6", "8"} +def rate_limit(topo, dargs): + """The configured --timeframes-rate-limit: on the driver, else on any stage (it is uniform), else 0.""" + for args in [dargs] + [m["cmdLineArgs"] for m in topo["metadata"]]: + if get_opt(args, "--timeframes-rate-limit"): + return int(get_opt(args, "--timeframes-rate-limit")) + return 0 + + +def critical_path(topo, cost): + """Longest chain of {device: seconds per TF} along the timeframe data flow of the topology: a lower bound + of the latency of one TF. Returns (seconds, [devices]).""" + def keys(spec): # origin/description/subspec, from the plain fields or from an "and" chain of a matcher + out, m = {}, spec.get("matcher", spec) + while m: + out.update({k: m[k] for k in ("origin", "description", "subspec") if k in m}) + out.update({k: v for k, v in (m.get("left") or {}).items() if k in ("origin", "description", "subspec")}) + m = m.get("matcher") if m.get("operation", "and") == "and" else None + return out + outs = [(w["name"], keys(o)) for w in topo["workflow"] for o in w["outputs"]] + preds = {} + for w in topo["workflow"]: + for i in w["inputs"]: + if is_source({"inputs": [i]}): # conditions, timers, enumerations: no TF data + continue + k = keys(i) + preds.setdefault(w["name"], set()).update(n for n, o in outs + if n != w["name"] and all(o.get(f, v) == v for f, v in k.items())) + best = {} + + def longest(n, seen=()): + if n not in best: + p = max((longest(q, seen + (n,)) for q in preds.get(n, ()) if q not in seen), default=(0.0, [])) + best[n] = (p[0] + cost.get(n, 0.0), p[1] + [n]) + return best[n] + return max((longest(w["name"]) for w in topo["workflow"]), default=(0.0, [])) + + def apply_knobs(topo, dargs, knobs, input_opt=None, input_value=None, extra=None): """Return (topology, driver args) with the knobs applied uniformly.""" topo = json.loads(json.dumps(topo)) @@ -543,15 +583,19 @@ def analyse(pm, mem_tsv=None, wall=None): # reconstruction), that window is meaningless: then use the processing period instead, from the first # processing callback anywhere (total_wall_time_ms > 0) to the last completed TF, with all TFs. p0 = min([t for m in devs.values() for t, v in series(m, "total_wall_time_ms") if v > 0] or [t_start]) + # The driver keeps the last 1024 samples of a metric: in a long run the counter starts above 1, and + # its first sample is not the completion of a TF + first = int(cons[0][1]) + 1 if cons and cons[0][1] > 1 else 1 w0 = w1 = None - if ntf >= 2 and cons: - w0 = next(t for t, v in cons if v >= 1) + if ntf > first and cons: + w0 = next(t for t, v in cons if v >= first) w1 = next((t for t, v in cons if v >= ntf), t_end) - nwin = ntf - 1 + nwin = ntf - first if w0 is None or (w1 - w0) < 0.2 * (w1 - p0): w1 = next((t for t, v in cons if v >= ntf), t_end) if cons else t_end w0, nwin = p0, max(1, ntf) - window_kind = "processing period (TFs complete in a burst)" + window_kind = "processing period (TFs complete in a burst)" if first == 1 else \ + f"whole run, from the first processing (the driver kept total-timeframes-consumed from {first - 1} TFs on)" else: window_kind = "first to last completed TF" T = max(1e-3, (w1 - w0) / 1000.0) @@ -597,9 +641,15 @@ def analyse(pm, mem_tsv=None, wall=None): delta = [(t, v - 2.0 ** 64 if v >= 2.0 ** 63 else v) for t, v in series(drv, "arrow-bytes-delta")] infl = series(drv, "total-timeframes-in-flight") res["arrow_peak_bytes"] = max([v for _, v in delta] or [0]) - # read - consumed is only meaningful when an AOD reader counts what it sends (df-sent) + # read - consumed is only meaningful when an AOD reader counts what it sends (df-sent); otherwise (e.g. a + # CTF reader) it is negative. Unknown (None) then, not 0. A few -1 are races between the two counters. win_infl = [v for t, v in infl if w0 <= t <= w1] if any(v > 0 for _, v in read) else [] - res["inflight_max"] = max(win_infl or [0]) + if sum(v < 0 for v in win_infl) > 0.1 * len(win_infl) or (infl and not win_infl): + res["inflight_invalid"] = f"total-timeframes-in-flight from {min(v for _, v in infl):.0f} to " \ + f"{max(v for _, v in infl):.0f} (read - consumed; total-timeframes-read is only " \ + "counted by the AOD reader)" + win_infl = [] + res["inflight_max"] = max(win_infl) if win_infl else None if len(win_infl) > 1: # time-weighted mean of TFs in flight in the window pts = [(t, v) for t, v in infl if w0 <= t <= w1] @@ -607,6 +657,24 @@ def analyse(pm, mem_tsv=None, wall=None): res["inflight_mean"] = acc / max(1, pts[-1][0] - pts[0][0]) else: res["inflight_mean"] = None + # Reconstruction: TFs in flight = computations of the TF source (performed_computations, one per TF + # injected) - TFs consumed by the sink; drops and starvation from the device counters. These metrics + # are in performanceMetrics.json only since "DPL: dump the rate limiting and drop metrics". + src = [series(m, "performed_computations") for n, m in devs.items() if SOURCE.search(n)] + started = max(src, key=lambda s: s[-1][1] if s else 0, default=[]) + # a counter that stays at 0 is never sent, so these are known only when performed_computations is there + dumped = any("performed_computations" in m for m in devs.values()) + res["flow"] = {k: {n: s[-1][1] for n, m in devs.items() if (s := series(m, k)) and s[-1][1] > 0} + for k in FLOW_METRICS} if dumped else {} + res["resources_counted"] = any("resources-satisfactory" in m for m in devs.values()) # debug builds only + if not win_infl and started and cons: + pts = sorted({t for t, _ in started + cons if w0 <= t <= w1} | {w0, w1}) + k = [max(0.0, interp(started, t) - interp(cons, t)) for t in pts] + res["inflight_max"] = max(k) + res["inflight_mean"] = sum(v * (t1 - t0) for v, t0, t1 in zip(k, pts, pts[1:])) / max(1, pts[-1] - pts[0]) + res["inflight_source"] = "performed_computations of the TF source - total-timeframes-consumed" + tx = [series(m, "total_bytes_out") for n, m in devs.items() if not n.startswith("internal-dpl-")] # not CCDB objects + res["bytes_out_per_tf"] = sum(s[-1][1] for s in tx if s) * MB / ntf if ntf and any(tx) else None res["peak_private_sum_bytes"] = peak_sum_mem or None res["shm_resident_peak_bytes"] = peak_shm or None return res @@ -626,17 +694,36 @@ def tune(an, topo, dargs, kind, budget, cores): d["b"] = d["busy_win_s"] / N / max(1, d["lanes"]) # busy seconds per TF per lane d["u"] = d["busy_win_s"] / T / max(1, d["lanes"]) # busy fraction per lane d["c"] = d["cpu_win_s"] / N # CPU seconds per TF (all lanes) + waits = [] + for k, d in devs.items(): + # A TF source (e.g. the CTF reader) waits in its callback for the TF rate limit (RateLimiter) or for + # back-pressure: its wall time is not work. Its CPU is used instead. Not the AOD reader: it is + # throttled by resource offers before its callback, which is reading. + if (is_source(specs[k]) if k in specs else not specs and SOURCE.search(k)) and \ + not k.startswith("internal-dpl-aod-reader") and d["b"] > 2 * d["c"] / max(1, d["lanes"]): + waits.append(f"{k} is a TF source: in its callback {d['u']:.0%} of the window ({d['b']*1000:.0f} ms/TF, " + f"total_wall_time_ms) but it uses {d['c']*1000:.0f} ms of CPU per TF: the rest is waiting for " + "the TF rate limit or back-pressure, so its CPU time is used as its busy time") + d["b"], d["u"] = d["c"] / max(1, d["lanes"]), d["c"] / tau / max(1, d["lanes"]) ranked = sorted(devs.items(), key=lambda kv: -kv[1]["b"]) top, topd = ranked[0] cpu_per_tf = sum(d["c"] for d in devs.values()) cpu_util = cpu_per_tf / tau / cores # memory model: sum of per-device private peaks + in-flight shm mem_known = all(d["mem_bytes"] for d in devs.values()) - priv = sum(d["mem_bytes"] or 0 for d in devs.values()) + priv = sum((d["mem_bytes"] or 0) * max(1, d["lanes"]) for d in devs.values()) # mem_bytes: per lane measured_peak = an.get("peak_private_sum_bytes") or priv s_tf = an["table_bytes_per_tf"] if kind == "analysis" else 0 # shm: resident pages of the FairMQ segment (macOS, measured); otherwise the arrow bytes in flight shm_now = max(0, an.get("shm_resident_peak_bytes") or (an["arrow_peak_bytes"] if kind == "analysis" else 0)) + # Reconstruction with the TFs in flight measured: shm per TF from the segment's resident size, else the + # bytes the devices send per TF (total_bytes_out; an upper bound, a message sent to N consumers counts N + # times). The TF rate limit binds when the TFs in flight reach it. + tfl = rate_limit(topo, dargs) + reco_k = kind != "analysis" and "inflight_source" in an + if reco_k: + s_tf = shm_now / max(1.0, an["inflight_max"]) if shm_now else an.get("bytes_out_per_tf") or 0 + binding = reco_k and tfl > 0 and an["inflight_max"] >= tfl - 0.5 pred = {"tau_obs_s": tau, "cpu_util_obs": cpu_util, "bottleneck": top, "bottleneck_busy_frac": topd["u"], "measured_peak_private_bytes": measured_peak, "measured_shm_peak_bytes": shm_now, "measured_peak_total_bytes": measured_peak} @@ -645,6 +732,7 @@ def tune(an, topo, dargs, kind, budget, cores): notes.append(f"busiest device per lane: {top} busy {topd['u']:.0%} of the window " f"({topd['b']*1000:.0f} ms/TF, total_wall_time_ms); next: " + ", ".join(f"{k} {v['u']:.0%}" for k, v in ranked[1:4])) + notes += waits notes.append(f"CPU in the window: {cpu_per_tf:.2f} CPU-s/TF = {cpu_util:.0%} of {cores} cores (cpuUsedAbsolute)") if not mem_known: notes.append("per-device memory not measured for every device (no mem.tsv / PSS): memory-raising knobs are " @@ -663,7 +751,11 @@ def tune(an, topo, dargs, kind, budget, cores): regime = "concurrency" pred["regime"] = regime notes.append(f"regime: {regime}-bound (sum of busy times {busy_sum_per_tf*1000:.0f} ms/TF vs " - f"{tau*1000:.0f} ms/TF observed; TFs in flight mean {an['inflight_mean'] or 0:.1f}, max {an['inflight_max']:.0f})") + f"{tau*1000:.0f} ms/TF observed; TFs in flight " + + (f"mean {an['inflight_mean'] or 0:.1f}, max {an['inflight_max']:.0f})" + if an["inflight_max"] is not None else "not measured)")) + if an.get("inflight_invalid") and "inflight_source" not in an: + notes.append(f"TFs in flight unknown: {an['inflight_invalid']}") if regime == "cpu": notes.append("CPU-bound: no knob raises throughput on this many cores; nothing changed") return knobs, why, notes, pred @@ -678,7 +770,32 @@ def tune(an, topo, dargs, kind, budget, cores): pred["latency_s"] = lat tau_cpu = cpu_per_tf / (0.9 * cores) k_cur = max(1, int(an["inflight_max"] or 1)) - can_k = kind == "analysis" and s_tf > 0 # only the AOD rate limit has a measured per-TF size + # Reconstruction without the TFs in flight (older O2): infer whether the configured TF limit binds from + # Little's law, TFs in flight = latency / period, the latency being at least the critical path of the + # busy times per TF along the data flow. + s_src = inferred = None + if kind != "analysis" and not reco_k and tfl > 0 and specs and regime == "concurrency" and \ + not an.get("window_kind", "").startswith("processing"): + cp, chain = critical_path(topo, {k: d["b"] * max(1, d["lanes"]) for k, d in devs.items()}) + chain = [c for c in chain if devs.get(c, {}).get("b")] + binding = inferred = cp >= 0.5 * tfl * tau + notes.append(f"TF rate limit {tfl} (--timeframes-rate-limit) inferred to {'bind' if binding else 'not bind'}: " + f"the busy times per TF along the critical path ({' -> '.join(chain)}) " + f"add up to {cp:.2f} s, i.e. at least {cp / tau:.1f} TFs in flight by Little's law at {tau:.2f} s/TF " + f"(taken as binding from {0.5 * tfl:.1f}), while the devices are mostly idle") + if binding: + seg = int(get_opt(dargs, "--shm-segment-size") or 0) + if shm_now: + s_tf, s_src = shm_now / tfl, f"sampled shm segment resident / {tfl} TFs in flight" + elif an.get("bytes_out_per_tf"): + s_tf, s_src = an["bytes_out_per_tf"], "bytes sent per TF (total_bytes_out; an upper bound)" + elif seg: + s_tf, s_src = seg / tfl, (f"conservative, no shm or bytes-out metric: the run held {tfl} TFs in the " + f"{fmt_bytes(seg)} shm segment, so at most {fmt_bytes(seg / tfl)} each") + shm_now = shm_now or tfl * s_tf # the TFs in flight are in the measured memory already + reco_k, k_cur, lat = True, tfl, max(tfl * tau, cp) + pred["latency_s"] = lat + can_k = (kind == "analysis" or binding) and s_tf > 0 # a TF limit that does not bind changes nothing def per_lane(lanes): return {k: devs[k]["b"] * lanes0[k] / lanes[k] for k in devs} @@ -707,6 +824,12 @@ def plan(lanes): "period: the run is bound by start-up and the first TF's latency (initialisation, CCDB), not by " "a device's throughput or the TFs in flight; no runtime knob in scope changes that: nothing changed") lanes_ok = False + elif regime == "concurrency" and not can_k and (reco_k or inferred is not None): + notes.append(f"{kind}: devices are mostly idle ({topd['u']:.0%} at most) and the TF rate limit " + + (f"({tfl}) binds, but the memory per TF is unknown (no shm or bytes-out metric, no " + "--shm-segment-size); nothing changed" if binding else + f"({tfl or 'none'}) does not bind: the source, not the limit, sets the TFs in flight; nothing changed")) + lanes_ok = False elif regime == "concurrency" and not can_k: notes.append(f"{kind}: devices are mostly idle ({topd['u']:.0%} at most) but the TFs in flight cannot be " "measured for this kind of workflow (no in-flight / shm metric in performanceMetrics.json): " @@ -723,23 +846,31 @@ def plan(lanes): if tau_cpu >= 0.95 * eff[bott]: notes.append(f"after the changes the CPU ({cpu_per_tf:.2f} CPU-s/TF on {cores} cores) is the limit") break + # the devices within 1.3x of the slowest are pipelined together, down to the next one (or the CPU) + group = [k for k in eff if eff[k] >= eff[bott] / 1.3] + rest = max([v for k, v in eff.items() if k not in group] + [1e-6]) + stuck = [k for k in group if NOT_PIPELINABLE.search(k) or (is_source(specs[k]) if k in specs else bool(specs))] if bott == reader and kind == "analysis": - n = lanes[bott] + 1 - elif not NOT_PIPELINABLE.search(bott) and (bott in specs and not is_source(specs[bott]) or not specs) \ - and eff[bott] >= 1.3 * second and eff[bott] >= 0.02: - n = min(math.ceil(lanes[bott] * eff[bott] / max(second, tau_cpu)), max(1, cores // 2), 8) + upd = {bott: lanes[bott] + 1} + elif not stuck and eff[bott] >= 1.3 * rest and eff[bott] >= 0.02 and (len(group) == 1 or eff[bott] >= 1.3 * tau_cpu): + upd = {k: min(math.ceil(lanes[k] * eff[k] / max(rest, tau_cpu)), max(1, cores // 2), 8) for k in group} else: if eff[bott] >= 0.02: - notes.append(f"{bott} would be the next limit ({eff[bott]*1000:.0f} ms/TF per lane) but " - + ("it cannot be pipelined" if bott in specs or bott.startswith("internal-") else "it is not in the topology") - + (f" or does not dominate (next {second*1000:.0f} ms/TF)" if eff[bott] < 1.3 * second else "")) + why_not = [f"{k} " + ("cannot be pipelined" if k in specs or k.startswith("internal-") + else "is not in the topology") for k in stuck] + if len(group) > 1: + why_not.append(f"it does not dominate (next {second*1000:.0f} ms/TF)" if stuck else + f"pipelining the {len(group)} devices within 1.3x of it gains less than 1.3x (next " + f"{rest*1000:.0f} ms/TF, CPU {tau_cpu*1000:.0f} ms/TF)") + notes.append(f"{bott} would be the next limit ({eff[bott]*1000:.0f} ms/TF per lane) but " + " and ".join(why_not)) break - if n <= lanes[bott]: + if all(n <= lanes[k] for k, n in upd.items()): break - trial = dict(lanes, **{bott: n}) + trial = dict(lanes, **upd) t_tau, t_need, t_k = plan(trial) if mem(trial, t_k) > usable or (can_k and t_k < t_need and lat / max(t_k, 1) >= eff[bott]): - notes.append(f"{bott}: {n} lanes do not fit the memory budget with the TFs in flight they need: left alone") + notes.append(f"{', '.join(f'{k}: {n}' for k, n in upd.items())} lanes do not fit the memory budget with the TFs " + "in flight they need: left alone") break lanes = trial if not lanes_ok and regime == "concurrency" and an.get("window_kind", "").startswith("processing"): @@ -747,6 +878,12 @@ def plan(lanes): tau_t, k_need, k_new = plan(lanes) tau_pred = max(tau_t, lat / max(k_new, 1)) if can_k else max(tau_t, tau if regime != "device" else tau_t) eff = per_lane(lanes) + if s_src and can_k: + nxt = sorted(eff, key=eff.get, reverse=True)[:2] + notes.append(f"with {max(k_cur, k_new)} TFs in flight the latency allows {lat / max(k_cur, k_new):.2f} s/TF; the next " + "limits are " + ", then ".join(f"{k} ({eff[k]*1000:.0f} ms/TF per lane, {lanes[k]} lane" + f"{'s' if lanes[k] > 1 else ''})" for k in nxt) + + f", and the CPU at {tau_cpu:.2f} s/TF ({cpu_per_tf:.2f} CPU-s/TF on 90% of {cores} cores)") for d in devs: if lanes[d] == lanes0[d]: continue @@ -765,7 +902,33 @@ def plan(lanes): f"pipelinable device; {lanes[d]} lanes bring it to {eff[d]*1000:.0f} ms/TF per lane, at " f"+{fmt_bytes((lanes[d]-lanes0[d])*(devs[d]['mem_bytes'] or 0))} (private peak " f"{fmt_bytes(devs[d]['mem_bytes'])} per lane)")) - if can_k and k_new > k_cur and mem_known: + if can_k and k_new > k_cur and mem_known and reco_k: + knobs["global"]["--timeframes-rate-limit"] = k_new + why.append(("--timeframes-rate-limit", k_new, + (f"the limit of {tfl} TFs in flight binds (inferred: TFs in flight not measured) while the devices " + f"are mostly idle: the TF latency is {lat:.2f} s ({tfl} x {tau:.2f} s/TF by Little's law)" + if s_src else + f"the limit of {tfl} TFs in flight binds (max {an['inflight_max']:.0f}, mean " + f"{an['inflight_mean'] or 0:.1f}: {an['inflight_source']}) while the devices are mostly idle: the TF " + f"latency is {lat:.2f} s") + + f" and the slowest lane needs {tau_t*1000:.0f} ms/TF, so {k_need} TFs in " + f"flight are needed; {k_new} fit in the budget at {fmt_bytes(s_tf)} of shm per TF" + + (f" ({s_src}): {fmt_bytes(measured_peak)} measured + {k_new - tfl} x {fmt_bytes(s_tf)} = " + f"{fmt_bytes(mem(lanes, k_new))} of {fmt_bytes(usable)} usable (90% of the budget); the fixed " + f"memory of every device (largest: {max(devs, key=lambda k: devs[k]['mem_bytes'] or 0)} " + f"{fmt_bytes(max(d['mem_bytes'] or 0 for d in devs.values()))}) is counted once, not per TF" + if s_src else ""))) + elif s_src and can_k and mem_known: + notes.append(f"the TF limit binds (inferred) but no TF more fits the budget: {fmt_bytes(measured_peak)} measured + " + f"{fmt_bytes(s_tf)} per TF ({s_src}) > {fmt_bytes(usable)} usable (90% of the budget)") + elif reco_k and "inflight_source" in an and tfl > 0 and s_tf > 0 and measured_peak > usable and \ + an["inflight_max"] - math.ceil((measured_peak - usable) / s_tf) >= 1: # fewer TFs in flight fit the budget + k_fit = int(an["inflight_max"] - math.ceil((measured_peak - usable) / s_tf)) + knobs["global"]["--timeframes-rate-limit"] = k_new = k_fit + why.append(("--timeframes-rate-limit", k_fit, + f"the probe needs {fmt_bytes(measured_peak)}, above the budget, with up to " + f"{an['inflight_max']:.0f} TFs in flight ({an['inflight_source']}) at {fmt_bytes(s_tf)} of shm per TF")) + elif can_k and k_new > k_cur and mem_known: old = get_opt(dargs, "--aod-memory-rate-limit") limit = int(math.ceil(k_new * s_tf * 1.1 / MB) * MB) if old is None or limit > int(old): @@ -783,17 +946,24 @@ def plan(lanes): why.append(("--timeframes-rate-limit", k_new, f"the explicit TF limit {tfl} would cap the {k_new} TFs in flight")) elif can_k and k_need > k_cur and not mem_known: notes.append(f"{k_need} TFs in flight would be needed but the memory is unknown: rate limit unchanged") - k_final = max(k_cur, k_new) if can_k else k_cur + k_final = max(k_cur, k_new) if can_k else (k_new if "--timeframes-rate-limit" in knobs["global"] else k_cur) # shm segment: must hold the in-flight data (twice, for fragmentation); never shrink it shm = get_opt(dargs, "--shm-segment-size") shm_cur = int(shm) if shm else None need = 2 * shm_for(k_final) - if shm_cur is not None and need > shm_cur: + if s_src and s_src.startswith("conservative") and shm_cur is not None: + need = shm_cur * k_final / tfl # s_tf is the segment / TFs in flight: keep that headroom per TF + if need > shm_cur: + new = int(math.ceil(need / GiB) * GiB) + knobs["global"]["--shm-segment-size"] = new + why.append(("--shm-segment-size", new, f"scaled with the TFs in flight: {fmt_bytes(shm_cur)} for {tfl} TFs, " + f"so {fmt_bytes(need)} for {k_final} (untouched pages of the segment are not resident)")) + elif shm_cur is not None and need > shm_cur: new = int(math.ceil(need / GiB) * GiB) knobs["global"]["--shm-segment-size"] = new - why.append(("--shm-segment-size", new, f"in-flight data up to {fmt_bytes(need/2)} (TFs in flight x table " - f"bytes per TF) needs 2x headroom over {fmt_bytes(shm_cur)}")) + why.append(("--shm-segment-size", new, f"in-flight data up to {fmt_bytes(need/2)} ({k_final} TFs in flight x " + f"{fmt_bytes(s_tf)} per TF) needs 2x headroom over {fmt_bytes(shm_cur)}")) elif shm_cur is not None: notes.append(f"--shm-segment-size {fmt_bytes(shm_cur)} kept: in-flight shm {fmt_bytes(shm_for(k_final))} " "at most; a smaller segment saves no resident memory (untouched pages are not counted)") @@ -807,6 +977,29 @@ def plan(lanes): return knobs, why, notes, pred +def backpressure(an, dargs): + """Drops, starvation and a binding TF rate limit, from the metrics dumped since "DPL: dump the rate limiting + and drop metrics"; empty for older O2 versions.""" + out = [] + why = {"dropped_computations": "timeslices evicted from the relayer before they were complete, or invalid: " + "their computation is lost", + "dropped_incoming_messages": "messages that arrived for a timeslice already processed, or that match no input", + "resources-missing": "the device found no resource offer (rate limiting; debug builds only)", + "resources-insufficient": "the resource offers were not enough (rate limiting; debug builds only)"} + for k, devs in an.get("flow", {}).items(): + if devs: + out.append(f"`{k}`: " + ", ".join(f"{d} {v:.0f}" for d, v in sorted(devs.items(), key=lambda kv: -kv[1])) + + f" ({why[k]})") + if an.get("flow") and not out: + out.append("no dropped computation or message" + (", no missing resource offer" if an.get("resources_counted") else "")) + tfl = int(get_opt(dargs, "--timeframes-rate-limit") or 0) + if "inflight_source" in an: + state = "binds" if tfl and an["inflight_max"] >= tfl - 0.5 else "does not bind" + out.append(f"TF rate limit {tfl or 'none'} {state}: TFs in flight max {an['inflight_max']:.0f}, mean " + f"{an['inflight_mean'] or 0:.1f} ({an['inflight_source']})") + return out + + # ---------------------------------------------------------------------------------------------- def write_outputs(out, topo, driver, dargs, knobs, why, notes, pred, an, args, input_opt): os.makedirs(out, exist_ok=True) @@ -825,7 +1018,7 @@ def write_outputs(out, topo, driver, dargs, knobs, why, notes, pred, an, args, i if knobs["pipeline"]: flat += ["--pipeline", ",".join(f"{k}:{v}" for k, v in knobs["pipeline"].items())] js = {"knobs": knobs, "changes": [{"option": k, "value": v, "reason": r} for k, v, r in why], - "notes": notes, "prediction": pred, "extra_args": flat, "analysis": an, + "notes": notes, "prediction": pred, "extra_args": flat, "analysis": an, "backpressure": backpressure(an, dargs), "inputs": {"budget_bytes": pred.get("budget_bytes"), "cores": args.cores, "input_option": input_opt}} with open(os.path.join(out, "tuning.json"), "w") as f: json.dump(js, f, indent=1, default=str) @@ -837,6 +1030,8 @@ def write_outputs(out, topo, driver, dargs, knobs, why, notes, pred, an, args, i else: lines.append("- none") lines += ["", "## Observations"] + [f"- {n}" for n in notes] + if js["backpressure"]: + lines += ["", "## Back-pressure and drops"] + [f"- {b}" for b in js["backpressure"]] lines += ["", "## Prediction"] if "tau_pred_s" in pred: lines.append(f"- s/TF: {pred['tau_obs_s']:.3f} observed -> {pred['tau_pred_s']:.3f} predicted (lower bound)") diff --git a/Framework/Core/scripts/dpl-tune/test_dpl_tune.py b/Framework/Core/scripts/dpl-tune/test_dpl_tune.py new file mode 100644 index 0000000000000..05c1e94986b4e --- /dev/null +++ b/Framework/Core/scripts/dpl-tune/test_dpl_tune.py @@ -0,0 +1,109 @@ +# Copyright 2019-2026 CERN and copyright holders of ALICE O2. +# See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +# All rights not expressly granted are reserved. +# +# This software is distributed under the terms of the GNU General Public +# License v3 (GPL Version 3), copied verbatim in the file "COPYING". +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization +# or submit itself to any jurisdiction. +"""Tests of dpl-tune on a synthetic reconstruction, without running O2: python3 -m unittest""" +import unittest + +import dpl_tune as dt + +GiB = dt.GiB +TAU = 10.0 # s/TF: the TF rate limit of 2 binds +# name: (inputs, outputs, lanes, wall s/TF, CPU s/TF, memory GiB per lane); per-TF times, over all lanes +DEVICES = { + "ctf-reader": (["ENUM"], ["CTF"], 1, 9.9, 0.1, 0.5), # waits for the rate limit in its callback + "decoder": (["CTF"], ["DIG"], 1, 1.0, 1.0, 0.5), + "gpu-reconstruction": (["DIG"], ["TPC"], 1, 0.5, 0.5, 16), # fixed memory pool + "tracker": (["DIG"], ["ITS"], 4, 3.0, 12.0, 1), # multithreaded: CPU >> wall + "matcher": (["TPC", "ITS"], ["ITSTPC"], 1, 4.0, 4.0, 1), + "tof-matcher": (["ITSTPC"], ["TOF"], 1, 3.5, 3.5, 1), + "writer": (["TOF"], [], 1, 0.1, 0.1, 0.1), +} + + +def spec(desc): + return {"binding": desc.lower(), "origin": "TST", "description": desc, "subspec": 0, "lifetime": 5 if desc == "ENUM" else 0} + + +def topology(limit): + args = ["--timeframes-rate-limit", str(limit), "--shm-segment-size", str(8 * GiB)] + return {"workflow": [{"name": n, "inputs": [spec(i) for i in d[0]], "outputs": [spec(o) for o in d[1]], + "maxInputTimeslices": d[2]} for n, d in DEVICES.items()], + "metadata": [{"name": n, "executable": "o2-test", "cmdLineArgs": list(args)} for n in DEVICES], + "command": "o2-test -b " + " ".join(args)} + + +def metrics(ntf=50, kept_from=30): + """performanceMetrics.json of a run at TAU s/TF, sampled every TAU s. As from an O2 without the rate + limiting metrics: the driver kept total-timeframes-consumed only from kept_from TFs on, and + total-timeframes-in-flight (read - consumed) is negative since no AOD reader counts the TFs read.""" + t0 = 1_000_000_000_000 + ts = [t0 + int(i * TAU * 1000) for i in range(ntf + 1)] + + def m(vals): + return [{"timestamp": str(t), "value": str(v)} for t, v in vals] + pm = {"driver": {"total-timeframes-consumed": m([(t, i) for i, t in enumerate(ts) if i >= kept_from]), + "total-timeframes-read": m([(t, 0) for t in ts]), + "total-timeframes-in-flight": m([(t, -i) for i, t in enumerate(ts) if i >= kept_from])}} + for n, (_, _, lanes, wall, cpu, mem) in DEVICES.items(): + for lane in range(lanes): + pm[f"{n}_t{lane}" if lanes > 1 else n] = { + "total_wall_time_ms": m([(t, i * wall / lanes * 1000) for i, t in enumerate(ts)]), + "cpuUsedAbsolute": m([(t, cpu / lanes * 1e6 * (i > 0)) for i, t in enumerate(ts)]), + "proportionalSetSize": m([(ts[-1], mem * GiB / 1024)])} + return pm + + +def run(limit=2, budget=32): + topo = topology(limit) + _, dargs = dt.driver_stage(topo) + an = dt.analyse(metrics()) + return an, dt.tune(an, topo, dargs, "reconstruction", budget * GiB, 16) + + +class InferredRateLimit(unittest.TestCase): + def test_inflight_unknown(self): + an = dt.analyse(metrics()) + self.assertIsNone(an["inflight_max"]) # negative read - consumed: unknown, not 0 + self.assertIn("inflight_invalid", an) + self.assertAlmostEqual(an["window_s"] / an["tf_in_window"], TAU) # counter kept from 30 TFs on + + def test_critical_path(self): + cp, chain = dt.critical_path(topology(2), {n: d[3] for n, d in DEVICES.items()}) + self.assertAlmostEqual(cp, 9.9 + 1.0 + 3.0 + 4.0 + 3.5 + 0.1) + self.assertEqual(chain, ["ctf-reader", "decoder", "tracker", "matcher", "tof-matcher", "writer"]) + + def test_raise_limit(self): + an, (knobs, why, notes, pred) = run(budget=32) + self.assertEqual(pred["bottleneck"], "matcher") # not the source waiting in its callback + # 23.6 GiB measured (16 GiB of it the fixed GPU pool, counted once) + 4 GiB per TF (8 GiB segment / 2 TFs) + self.assertEqual(knobs["global"]["--timeframes-rate-limit"], 3) + self.assertEqual(knobs["pipeline"], {}) # the latency, not a device, is still the limit + self.assertAlmostEqual(pred["tau_pred_s"], 2 * TAU / 3) + self.assertTrue(any("inferred to bind" in n for n in notes)) + + def test_pipeline_after_limit(self): + an, (knobs, why, notes, pred) = run(budget=64) + self.assertEqual(set(knobs["pipeline"]), {"matcher", "tof-matcher"}) # within 1.3x: together + self.assertNotIn("tracker", knobs["pipeline"]) # 4 lanes, idle + self.assertGreater(knobs["global"]["--timeframes-rate-limit"], 3) + + def test_over_budget(self): + an, (knobs, why, notes, pred) = run(budget=24) + self.assertEqual(why, []) + self.assertTrue(any("no TF more fits" in n for n in notes)) + + def test_not_binding(self): + an, (knobs, why, notes, pred) = run(limit=8, budget=64) + self.assertEqual(why, []) + self.assertTrue(any("inferred to not bind" in n for n in notes)) + + +if __name__ == "__main__": + unittest.main()