From 6baca7a935e259f947151dd21f7295b176720673 Mon Sep 17 00:00:00 2001 From: Shawn Jackson Date: Sun, 4 Oct 2026 15:13:48 -0700 Subject: [PATCH] Grouped expert dispatch: no padding to the busiest expert Training the large Strix profile slowed to half speed as it went and then crashed. Measured on its checkpoint: routing grows "sink" experts that nearly every character picks among its top 8 - 1,960 of 2,081 characters at a typical row, 15x the fair share with 128 experts on the card. The dispatch padded every expert to the busiest one's load, so uncapped it computed ~16x the routed work and its buffers kept growing; capped, it dropped 30-60% of routing. - minagi/pool.py: the chosen experts are grouped by load (rounded with _bucket) and each group runs its own batched matmuls at its own size. Weights are gathered once per call and split into the groups' views; a gather per group was slower, because each one's backward allocates a gradient the size of the whole card. One character is a single group of top_k experts, so writing reads top_k experts' weights. The old single rectangle stays behind PooledMLP.grouped_dispatch = False. - Buffer capacities are rounded to a few dozen sizes (_bucket). ROCm on Windows ignores expandable_segments, and a new buffer size every call fragmented 17 GB of live tensors into 49 GB reserved. - train.py: allocated / reserved / peak GPU memory in the history file at every checkpoint. - tools/gpu_mem_sampler.ps1: per-process dedicated and shared GPU memory from Windows' performance counters. - Profiles and README: expandable_segments is ignored on Windows ROCm, and why capacity_factor stays 0 on the large profile. On the 8060S, step 1,938 of the large model, uncapped: training step 475 -> 813 char/s, peak 24.6 -> 18.8 GB, 0% dropped writing 5.3 -> 19.8 char/s A 45-minute run held 100-147 steps per 5 minutes (58 before) with reserved memory flat at 22.8 GB; held-out 2.17 -> 2.00. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- configs/strix_halo.yaml | 8 +- configs/strix_halo_large.yaml | 24 +++-- minagi/pool.py | 184 +++++++++++++++++++++++----------- tests/test_dispatch.py | 86 +++++++++++++--- tools/bench_hw.py | 11 +- tools/gpu_mem_sampler.ps1 | 23 +++++ train.py | 10 ++ 8 files changed, 258 insertions(+), 90 deletions(-) create mode 100644 tools/gpu_mem_sampler.ps1 diff --git a/README.md b/README.md index d9019ed..5a6c3be 100644 --- a/README.md +++ b/README.md @@ -478,7 +478,7 @@ python tools/bench_hw.py --config configs/strix_halo_large.yaml # measure befor | `ram_tier_on_gpu` | holds the expert pool's RAM tier as device tensors, so paging an expert onto the card is a device-to-device copy rather than a blocking host transfer. System memory *is* the card's memory here | | `rocm_aotriton` | `TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1` - the fast SDPA kernels on RDNA 3.5. Without them the cached forward falls back to math attention, which builds the full score matrix at every row | | `tunableop` | `PYTORCH_TUNABLEOP_ENABLED=1`. Off in both profiles: the expert dispatch's matmuls change shape every forward, so it re-tunes nearly every call - a held-out pass ran past half an hour on the 8060S | -| `expandable_segments` | the allocator setting train.py has always used; turn it off if your ROCm build warns it is unsupported | +| `expandable_segments` | the allocator setting train.py has always used. ROCm on Windows ignores it ("not supported on this platform"), so the profiles turn it off and `minagi/pool.py` rounds the expert dispatch buffer to a few fixed sizes instead - without that, an uncapped run fragmented to 49 GB reserved for 17 GB live and crashed | Every run prints a `hardware:` line naming the device, backend, whether memory is unified, the budget and where it came from. diff --git a/configs/strix_halo.yaml b/configs/strix_halo.yaml index 06322a4..89e388b 100644 --- a/configs/strix_halo.yaml +++ b/configs/strix_halo.yaml @@ -231,8 +231,12 @@ hardware: unified: true ram_tier_on_gpu: true # the expert RAM tier lives on the device: a # page-in is a device-to-device copy - expandable_segments: true # turn off if your ROCm build warns it is - # unsupported (some Windows builds) + expandable_segments: false # IGNORED by ROCm on Windows, which warns + # "not supported on this platform". It is what + # stops the allocator fragmenting elsewhere; here + # minagi/pool.py rounds the expert buffer to a few + # sizes instead. Measured before that: 49 GB + # reserved for 17 GB live, half speed, a crash rocm_aotriton: true # fast SDPA kernels on RDNA 3.5; without them a # 4k window builds its whole T x T scores per row tunableop: false # OFF on purpose. The expert dispatch's batched diff --git a/configs/strix_halo_large.yaml b/configs/strix_halo_large.yaml index cad37e9..3b1b9cd 100644 --- a/configs/strix_halo_large.yaml +++ b/configs/strix_halo_large.yaml @@ -98,14 +98,14 @@ pool: capacity_factor: 0 # most of a batch one expert may take, as a multiple # of its fair share; the rest is dropped. 0 removes - # the cap. The cap exists to bound memory on an 8 GB - # card; with 128 experts on the card a fresh model's - # router piles onto a few, and at 1.5 it dropped 59% - # of routing in tools/bench_hw.py (76% in a real - # run's first minutes) - most of what the experts - # could learn. Uncapped, a step was 27% slower and - # peaked at 22.8 GB instead of 17.8. Measured on the - # 8060S: 3 dropped 41%, 6 dropped 25% + # the cap. With 128 experts on the card the router + # grows "sink" experts nearly every character picks + # - 15x the fair share - so any cap drops a lot: + # 1.5 dropped 59% of routing, 4 dropped 30%. The + # grouped dispatch in minagi/pool.py runs each + # expert at its own load, so uncapped costs nothing: + # measured at step 1,938 on the 8060S, 813 char/s + # and 18.8 GB uncapped, 733 char/s capped at 4 # THE BALANCE TERM - how the whole pool gets used. Left alone the router # keeps choosing the same experts: reading held-out on its own it put 59 of @@ -237,8 +237,12 @@ hardware: unified: true ram_tier_on_gpu: true # the expert RAM tier lives on the device: a # page-in is a device-to-device copy - expandable_segments: true # turn off if your ROCm build warns it is - # unsupported (some Windows builds) + expandable_segments: false # IGNORED by ROCm on Windows, which warns + # "not supported on this platform". It is what + # stops the allocator fragmenting elsewhere; here + # minagi/pool.py rounds the expert buffer to a few + # sizes instead. Measured before that: 49 GB + # reserved for 17 GB live, half speed, a crash rocm_aotriton: true # fast SDPA kernels on RDNA 3.5; without them a # 4k window builds its whole T x T scores per row tunableop: false # OFF on purpose. The expert dispatch's batched diff --git a/minagi/pool.py b/minagi/pool.py index b90e343..4729989 100644 --- a/minagi/pool.py +++ b/minagi/pool.py @@ -335,10 +335,10 @@ def __init__(self, pool, d_model, top_k=4, site=0, z_weight=1e-3, # ...and the denominator, so the counter reads as a share of the # work rather than as a number nobody can scale. self.routed = 0 - # Run only the experts a call actually chose when they are at most - # half the card - see the dispatch. Off reproduces the old path, which - # the tests compare against. - self.subset_dispatch = True + # Group the chosen experts by load and run each group at its own size + # - see the dispatch. Off reproduces the single padded rectangle, + # which the tests compare against. + self.grouped_dispatch = True @property def pool(self): @@ -573,66 +573,119 @@ def requested(scores): self.dropped += int((~keep).sum()) e_sorted, t_sorted = e_sorted[keep], t_sorted[keep] w_sorted, slot = w_sorted[keep], slot[keep] + counts = counts.clamp(max=limit) cap = limit - # ONLY THE EXPERTS THAT WERE CHOSEN RUN. The buffer is [n, cap, D] and - # every matmul below reads every expert's weights - and casts them to - # the compute dtype - whether or not anything was routed to it. A - # training chunk of 2,048 characters reaches nearly every expert on - # the card, so that costs nothing there. A character being written is - # a forward of its own and reaches top_k of them: with 128 on the - # card, every row read and cast all 128 to run 8, and writing was - # bound by memory bandwidth - 2.9 characters a second on Strix Halo. + # The slot buffer, and everything computed from it, in the COMPUTE + # dtype rather than the residual stream's. The residual stays fp32 by + # design; the dispatch does not need to, and halving this buffer is + # the difference between fitting on the card and not. Autocast does + # not do it for us: the weights are cast TO the buffer's dtype below, + # so the matmuls run at whatever the buffer is. + dt = compute_dtype() if flat.device.type == "cuda" else flat.dtype + + # GROUPED BY LOAD. One padded rectangle [n, cap, D] pads every expert + # to the BUSIEST expert's load. Routing here grows "sink" experts that + # nearly every character picks among its top_k - measured on the large + # Strix profile, 1,960 of 2,081 characters at a typical row, 15x the + # fair share with 128 experts on the card - so one rectangle computed + # 16x the work the routing asked for, slowed training by half as the + # sinks formed, and its buffers grew until one failed to allocate. # - # So when at most half the experts are in use, the weights of just - # those are gathered first. Half, because the gather copies them in - # fp32 before the cast; below that the copy is no larger than the - # cast of the whole card it replaces, so peak memory never rises. - sub = None - if self.subset_dispatch and n > 1: + # So the experts this call chose are sorted into groups by their own + # load, rounded with _bucket, and each group runs its own three + # batched matmuls at its own size. Nothing is dropped that the + # capacity factor did not drop, and the work is at most twice the + # routing's instead of n times the worst expert's. The buckets also + # keep the allocator to a few dozen buffer sizes: on ROCm for Windows, + # which ignores expandable_segments, a buffer of a new size every call + # fragmented 17 GB of live tensors into 49 GB reserved. + # + # Only experts something was routed to run, so a character being + # written - which reaches top_k of the card - reads and casts top_k + # experts' weights, not the whole card's. Where most of the card is in + # use the weights are cast once and the groups gather from the cast; + # where few are, each group gathers its fp32 experts and casts those. + groups = None + cast_first = False + if self.grouped_dispatch and n > 1: if N == 1: - # sorted and distinct already, and the count is known here - present = e_sorted + # one character: top_k distinct experts, one assignment each, + # already sorted - no need to ask the device for the counts + k_ = int(e_sorted.numel()) + groups = [(1, 0, k_, 0, k_)] + seq_t = e_sorted + e_rank = torch.arange(k_, device=flat.device) + used = k_ else: - present = torch.nonzero(counts > 0).squeeze(1) - m = int(present.numel()) - if 0 < m * 2 <= n: - remap = torch.full((n,), -1, dtype=torch.long, - device=flat.device) - remap[present] = torch.arange(m, device=flat.device) - e_sorted = remap[e_sorted] - sub, n = present, m - - def pick(W): - return W if sub is None else W.index_select(0, sub) + cl = counts.tolist() + by = {} + for e, c in enumerate(cl): + if c > 0: + by.setdefault(_bucket(c), []).append(e) + used = sum(len(v) for v in by.values()) + if not (len(by) == 1 and used == n): + seq = [e for c in sorted(by) for e in by[c]] + seq_t = torch.tensor(seq, device=flat.device) + rank = torch.full((n,), -1, dtype=torch.long, + device=flat.device) + rank[seq_t] = torch.arange(len(seq), device=flat.device) + r = rank[e_sorted] + o2 = torch.argsort(r, stable=True) + e_rank, t_sorted = r[o2], t_sorted[o2] + w_sorted, slot = w_sorted[o2], slot[o2] + groups, r0, a0 = [], 0, 0 + for c in sorted(by): + es = by[c] + a1 = a0 + sum(cl[e] for e in es) + groups.append((c, r0, len(es), a0, a1)) + r0, a0 = r0 + len(es), a1 + cast_first = groups is not None and used * 2 > n + if groups is None: + # every expert on the card at one load - or grouping is off - so + # one rectangle, rounded to a bucket (see above) + cap = _bucket(cap) + + def experts(lv, buf): + """The stacked experts over one slot buffer [m, cap, D].""" + x = buf + for W1, W3, W2 in lv: + h = F.silu(torch.bmm(x, W1.transpose(1, 2))) * \ + torch.bmm(x, W3.transpose(1, 2)) + y = torch.bmm(h, W2.transpose(1, 2)) + # deeper experts stack residually, so an expert of any depth + # can still be added to the mixture without changing its scale + x = y if len(lv) == 1 else x + y + return x def run(src, *ws): lv = [(ws[i], ws[i + 1], ws[i + 2]) for i in range(0, len(ws), 3)] - # The slot buffer, and everything computed from it, in the COMPUTE - # dtype rather than the residual stream's. The residual stays fp32 - # by design; the dispatch does not need to, and halving this buffer - # is the difference between fitting on the card and not. Autocast - # does not do it for us: the weights are cast TO buf's dtype a few - # lines below, so the matmul runs at whatever buf is. - dt = compute_dtype() - if src.device.type != "cuda": - dt = src.dtype - buf = torch.zeros(n, cap, D, device=src.device, dtype=dt) - buf[e_sorted, slot] = src[t_sorted].to(dt) - if len(lv) == 1: - W1, W3, W2 = (pick(t) for t in lv[0]) - h = F.silu(torch.bmm(buf, W1.transpose(1, 2).to(buf.dtype))) * \ - torch.bmm(buf, W3.transpose(1, 2).to(buf.dtype)) - y = torch.bmm(h, W2.transpose(1, 2).to(buf.dtype)) # [n,cap,D] - return y[e_sorted, slot].to(src.dtype) - # deeper experts stack residually, so an expert of any depth can - # still be added to the mixture without changing its scale - x = buf - for W1, W3, W2 in ((pick(a), pick(b), pick(c)) for a, b, c in lv): - h = F.silu(torch.bmm(x, W1.transpose(1, 2).to(x.dtype))) * \ - torch.bmm(x, W3.transpose(1, 2).to(x.dtype)) - x = x + torch.bmm(h, W2.transpose(1, 2).to(x.dtype)) - return x[e_sorted, slot].to(src.dtype) + if groups is None: + buf = torch.zeros(n, cap, D, device=src.device, dtype=dt) + buf[e_sorted, slot] = src[t_sorted].to(dt) + lvc = [tuple(W.to(dt) for W in t) for t in lv] + return experts(lvc, buf)[e_sorted, slot].to(src.dtype) + # ONE gather per weight, every chosen expert in group order, then + # split into the groups' views. A gather per group was slower than + # the rectangle it replaced: each one's backward is a zero tensor + # the size of the whole card, so twenty groups cost twenty of them + # a row. A split's backward is one concatenation. + sizes = [g[2] for g in groups] + + def gather(W): + G = (W.to(dt).index_select(0, seq_t) if cast_first + else W.index_select(0, seq_t).to(dt)) + return torch.split(G, sizes) + per = [tuple(gather(W) for W in t) for t in lv] + parts = [] + for gi, (c, r0, m, a0, a1) in enumerate(groups): + lvg = [tuple(Ws[gi] for Ws in t) for t in per] + local, sl = e_rank[a0:a1] - r0, slot[a0:a1] + buf = torch.zeros(m, c, D, device=src.device, dtype=dt) + buf[local, sl] = src[t_sorted[a0:a1]].to(dt) + parts.append(experts(lvg, buf)[local, sl]) + return (parts[0] if len(parts) == 1 + else torch.cat(parts)).to(src.dtype) flat_w = tuple(t for lv_ in levels for t in lv_) if self.grad_checkpoint and self.training and torch.is_grad_enabled(): @@ -645,6 +698,25 @@ def run(src, *ws): return out.view(B, T, D) +CAP_STEP = 128 + + +def _bucket(cap): + """ + The dispatch buffer's capacity, rounded so few distinct sizes occur. + + Powers of two up to CAP_STEP, so a small batch pads by at most 2x of + very little; multiples of CAP_STEP above it, so a training chunk pads by + at most CAP_STEP rows. 0 and 1 are left as they are: a character being + written has cap 1 every time. + """ + if cap <= 1: + return cap + if cap <= CAP_STEP: + return 1 << (cap - 1).bit_length() + return -(-cap // CAP_STEP) * CAP_STEP + + def _mem_frac(): """ Peak fraction of the GPU this process actually needs. 0.0 without a GPU. diff --git a/tests/test_dispatch.py b/tests/test_dispatch.py index 03bdcb2..c3c09a1 100644 --- a/tests/test_dispatch.py +++ b/tests/test_dispatch.py @@ -1,6 +1,7 @@ """ -Running only the chosen experts must compute what running all of them did: -the same outputs, and the same gradients on every slot. +The grouped dispatch must compute what one padded rectangle did: the same +outputs, and the same gradients on every slot - for a character being written +and for a chunk whose experts carry very different loads. """ import torch @@ -11,9 +12,9 @@ def _sites(model): return [m for m in model.modules() if isinstance(m, PooledMLP)] -def _run(model, x, subset): +def _run(model, x, grouped): for s in _sites(model): - s.subset_dispatch = subset + s.grouped_dispatch = grouped model.zero_grad(set_to_none=True) logits, loss = model(x[:, :-1], targets=x[:, 1:]) loss.backward() @@ -22,27 +23,80 @@ def _run(model, x, subset): return logits.detach(), grads -def test_subset_dispatch_matches_full(tiny): +def _model(tiny, resident=6): from minagi.build import build_paged from minagi.create import create - create(tiny["weights"], verbose=False) - # 6 slots and top_k 2: a single character reaches 2 of them, under half, - # which is when the subset path runs - model, _, pool, _ = build_paged(tiny["weights"], "cpu", resident=6) + model, _, _, _ = build_paged(tiny["weights"], "cpu", resident=resident) model.train() for s in _sites(model): s.grad_checkpoint = False + return model + + +def _same(a, ga, b, gb): + assert torch.allclose(a, b, atol=1e-5), (a - b).abs().max() + for u, v in zip(ga, gb): + assert (u is None) == (v is None) + if u is not None: + assert torch.allclose(u, v, atol=1e-6), (u - v).abs().max() + + +def test_bucket_sizes(): + from minagi.pool import CAP_STEP, _bucket + assert [_bucket(c) for c in (0, 1, 2, 3, 5, 64, 65, 128)] == \ + [0, 1, 2, 4, 8, 64, 128, 128] + assert _bucket(CAP_STEP + 1) == 2 * CAP_STEP + assert _bucket(1000) == 1024 and _bucket(1025) == 1152 + # few sizes in play across every capacity a 2,048-character chunk can hit + assert len({_bucket(c) for c in range(1, 2049)}) <= 24 + +def test_padding_changes_nothing(tiny, monkeypatch): + """A rounded-up rectangle computes what an exact one did.""" + import minagi.pool as pool_mod + model = _model(tiny) + x = torch.randint(32, 127, (1, 40), generator=torch.Generator().manual_seed(5)) + torch.manual_seed(0) + a, ga = _run(model, x, grouped=False) + monkeypatch.setattr(pool_mod, "_bucket", lambda c: c) + torch.manual_seed(0) + b, gb = _run(model, x, grouped=False) + _same(a, ga, b, gb) + + +def test_grouped_matches_rectangle_when_writing(tiny): + """One character: top_k of the card, one group.""" + model = _model(tiny) g = torch.Generator().manual_seed(3) for n in (2, 3): # one and two characters per forward x = torch.randint(32, 127, (1, n), generator=g) torch.manual_seed(0) - a, ga = _run(model, x, subset=True) + a, ga = _run(model, x, grouped=True) torch.manual_seed(0) - b, gb = _run(model, x, subset=False) - assert torch.allclose(a, b, atol=1e-5), (a - b).abs().max() - for u, v in zip(ga, gb): - assert (u is None) == (v is None) - if u is not None: - assert torch.allclose(u, v, atol=1e-6), (u - v).abs().max() + b, gb = _run(model, x, grouped=False) + _same(a, ga, b, gb) + + +def test_grouped_matches_rectangle_with_uneven_load(tiny, monkeypatch): + """A chunk whose experts carry different loads splits into groups.""" + import minagi.pool as pool_mod + model = _model(tiny) + seen = [] + real = pool_mod._bucket + + def spy(c): + seen.append(c) + return real(c) + monkeypatch.setattr(pool_mod, "_bucket", spy) + + x = torch.randint(32, 127, (1, 97), generator=torch.Generator().manual_seed(9)) + torch.manual_seed(0) + a, ga = _run(model, x, grouped=True) + grouped_sizes = set(real(c) for c in seen) + seen.clear() + torch.manual_seed(0) + b, gb = _run(model, x, grouped=False) + _same(a, ga, b, gb) + # the grouped path really did split the experts by load + assert len(grouped_sizes) >= 2, grouped_sizes diff --git a/tools/bench_hw.py b/tools/bench_hw.py index 3a55eaa..234e823 100644 --- a/tools/bench_hw.py +++ b/tools/bench_hw.py @@ -203,8 +203,9 @@ def step(): def bench_decode(dev, wdir, n_chars, prompt_len=512): """ Writing: one character per forward behind a cache, as serve.py and the - sample log write. Timed with the expert dispatch running every expert on - the card, and running only the ones each character chose. + sample log write. Timed with the expert dispatch as one padded rectangle + over every expert on the card, and grouped - only the experts each + character chose. """ from minagi.build import build_paged from minagi.pool import PooledMLP @@ -217,9 +218,9 @@ def bench_decode(dev, wdir, n_chars, prompt_len=512): g = torch.Generator().manual_seed(0) prompt = torch.randint(32, 127, (1, prompt_len), generator=g).to(dev) out = {"resident": pool.resident, "experts": pool.n_experts()} - for name, subset in (("all_experts", False), ("chosen_only", True)): + for name, subset in (("rectangle", False), ("grouped", True)): for s in sites: - s.subset_dispatch = subset + s.grouped_dispatch = subset caches = model.empty_caches() with torch.no_grad(), amp(dev): logits = model(prompt, caches=caches)[0] @@ -339,7 +340,7 @@ def main(): f"{e['fwd_bwd_ms']:.2f} ms ({e['fwd_bwd_tflops']:.1f} TFLOP/s)") def show_decode(d): - for k in ("all_experts", "chosen_only"): + for k in ("rectangle", "grouped"): v = d[k] print(f" {k:12} {v['chars_per_s']:7.1f} char/s " f"({v['ms_per_char']:.0f} ms a character)") diff --git a/tools/gpu_mem_sampler.ps1 b/tools/gpu_mem_sampler.ps1 new file mode 100644 index 0000000..4df5f52 --- /dev/null +++ b/tools/gpu_mem_sampler.ps1 @@ -0,0 +1,23 @@ +# Usage: pwsh -File tools/gpu_mem_sampler.ps1 -ProcessId [-Out runs/gpu-mem.csv] +# +# Samples one process's GPU memory from Windows' own counters every +# $Every seconds until it exits, appending CSV rows to $Out. +# dedicated_gb - in the GPU's dedicated (VGM) memory +# shared_gb - spilled to shared system memory, which is far slower +param([int]$ProcessId, [string]$Out = "runs/gpu-mem.csv", [int]$Every = 30) + +"time,dedicated_gb,shared_gb,committed_gb" | Out-File -FilePath $Out -Encoding utf8 +while (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue) { + $pat = "pid_$($ProcessId)_" + $s = (Get-Counter '\GPU Process Memory(*)\Dedicated Usage', + '\GPU Process Memory(*)\Shared Usage', + '\GPU Process Memory(*)\Total Committed' ` + -ErrorAction SilentlyContinue).CounterSamples | + Where-Object { $_.InstanceName -like "$pat*" } + $sum = { param($kind) ($s | Where-Object { $_.Path -like "*\$kind" } | + Measure-Object CookedValue -Sum).Sum / 1GB } + $row = "{0},{1:N2},{2:N2},{3:N2}" -f (Get-Date -Format s), + (& $sum 'dedicated usage'), (& $sum 'shared usage'), (& $sum 'total committed') + $row | Out-File -FilePath $Out -Append -Encoding utf8 + Start-Sleep -Seconds $Every +} diff --git a/train.py b/train.py index 153ee87..fdd5925 100644 --- a/train.py +++ b/train.py @@ -1010,6 +1010,16 @@ def log_history(val=None): "born": t["born"], "last_seen": t.get("last_seen"), "uid": t.get("uid"), "trial": getattr(model.pool, "trial", 0)} + if device.type == "cuda": + # what this process holds on the card, so a run that slows + # down or dies can be checked for memory that only grows: + # allocated is live tensors, reserved what the caching + # allocator keeps, peak the most allocated since the start + mb = 1 << 20 + row.update( + mem_alloc_mb=round(torch.cuda.memory_allocated() / mb), + mem_reserved_mb=round(torch.cuda.memory_reserved() / mb), + mem_peak_mb=round(torch.cuda.max_memory_allocated() / mb)) os.makedirs(os.path.dirname(args.history) or ".", exist_ok=True) with open(args.history, "a", encoding="utf-8") as f: f.write(json.dumps(row, separators=(",", ":")) + "\n")