"""Shared output helpers; no model loading or optimizer dependencies.""" from contextlib import contextmanager,redirect_stdout,redirect_stderr import sys import torch def memory(): if not torch.cuda.is_available():return {} torch.cuda.synchronize();free,total=torch.cuda.mem_get_info();g=2**30 return dict(allocated_GiB=torch.cuda.memory_allocated()/g,reserved_GiB=torch.cuda.memory_reserved()/g, peak_allocated_GiB=torch.cuda.max_memory_allocated()/g,device_used_GiB=(total-free)/g,device_total_GiB=total/g) def figures(out,curve): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt for key,name in [('loss','loss_curve.png'),('accuracy','acc_curve.png')]: fig,ax=plt.subplots(figsize=(8,4));found=False for split in ('train_probe','development'): points=[p for p in curve if key in p[split]] if points:ax.plot([p['main_forwards'] for p in points],[p[split][key] for p in points],label=split);found=True if found: ax.set(xlabel='Cumulative main forwards (including probes)',ylabel=key);ax.grid(alpha=.2);ax.legend();fig.tight_layout();fig.savefig(out/name,dpi=160) plt.close(fig) class Tee: def __init__(self,*streams):self.streams=streams def write(self,text): for stream in self.streams:stream.write(text);stream.flush() def flush(self): for stream in self.streams:stream.flush() @staticmethod @contextmanager def redirect(log): with redirect_stdout(Tee(sys.stdout,log)),redirect_stderr(Tee(sys.stderr,log)):yield