This repository has been archived on 2026-11-25. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
MeltMind-Archive/artifacts/gpu-concurrency-assessment-2026-11-18/withdrawn-throughput-draft/h2_concurrency_probe_worker.py
T

86 lines
4.5 KiB
Python

"""Fresh H2/seed0, original200-epoch LR prefix, five learning-only epochs."""
import os
from pathlib import Path
import sys
import time
import traceback
import numpy as np
import psutil
import torch
from phase2_h1_worker_v2 import save
from phase2_h2_data import load_part, to_device
from phase2_h2_model import H2Geo, optimizer, lr_epoch
from phase2_h2_pilot_worker import seed, train_step, peaks
from h2_concurrency_probe_common import config
def run(root, n, index):
c, view, stats = config(root)
if n not in (1, 2, 3) or index not in range(n):
raise PermissionError('Unapproved copy')
phase = root / ('n' + str(n)); out = phase / str(index)
out.mkdir(exist_ok=False)
os.sched_setaffinity(0, [c['worker_cpus'][index]])
torch.set_num_threads(1); torch.set_num_interop_threads(1)
if os.environ.get('CUDA_VISIBLE_DEVICES') != c['gpu_uuid'] or os.environ.get('PYTORCH_CUDA_ALLOC_CONF') != 'expandable_segments:True':
raise ValueError('GPU/allocator identity')
start = time.monotonic(); process = psutil.Process(); epoch = steps = 0
rows = []; measure_start = measure_end = None
def barrier(name):
while not (phase / name).exists():
if time.monotonic() - start >= c['job_wall_seconds'] - 30:
raise TimeoutError('Barrier exhausted own window')
time.sleep(.1)
try:
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.cuda.set_device(0); torch.cuda.init(); torch.cuda.reset_peak_memory_stats(); seed()
model = H2Geo().cuda(); opt = optimizer(model)
f = view['folds'][0]; parts = len(f['learning']); total = f['learning_nodes']
save(out / 'ready.json', dict(pid=os.getpid(), unix=time.time(), **peaks()))
barrier('go.json')
for epoch in range(1, 6):
if epoch == 2:
save(out / 'warm.json', dict(epoch=1, pid=os.getpid()))
barrier('measure-go.json'); measure_start = time.monotonic()
begin = time.monotonic(); seen = nodes = 0; load_s = transfer_s = step_s = 0.
io0 = process.io_counters(); cpu0 = time.process_time()
if any(abs(g['lr'] - lr_epoch(epoch)) > 1e-15 for g in opt.param_groups):
raise ValueError('Original learning-rate prefix changed')
order = np.random.default_rng(np.random.SeedSequence([0, epoch])).permutation(parts)
for k in order:
case = f['learning'][int(k)]
t = time.monotonic(); data = load_part(view, case, stats, 'learning', out)
load_s += time.monotonic() - t
t = time.monotonic(); data = to_device(data, 'cuda'); torch.cuda.synchronize()
transfer_s += time.monotonic() - t
t = time.monotonic(); result = train_step(model, opt, data, parts, total)
step_s += time.monotonic() - t
seen += 1; nodes += data['nodes']; steps += 1
save(out / 'progress.json', dict(epoch=epoch, parts=seen, optimizer_steps=steps,
rss=process.memory_info().rss, loss=result['loss'], **peaks()))
del data
if seen != parts or nodes != total:
raise ValueError('Incomplete learning epoch')
io1 = process.io_counters()
row = dict(epoch=epoch, seconds=time.monotonic()-begin,
load_prepare_seconds=load_s, transfer_seconds=transfer_s, train_step_seconds=step_s,
cpu_seconds=time.process_time()-cpu0,
io_delta={k: getattr(io1,k)-getattr(io0,k) for k in io0._fields}, **peaks())
rows.append(row); save(out / 'epochs.json', rows)
for group in opt.param_groups: group['lr'] = lr_epoch(epoch+1)
measure_end = time.monotonic()
save(out / 'result.json', dict(status='COMPLETE', completed_epochs=5, optimizer_steps=steps,
measure_start=measure_start, measure_end=measure_end, epochs=rows, worker_wall=time.monotonic()-start,
cpu_seconds=time.process_time(), test_reads=False, validation_reads=False,
checkpoint_saved=False, role='throughput_only_not_scientific_model', **peaks()))
except BaseException as exc:
save(out / 'failure.json', dict(status='FAILED', type=type(exc).__name__, reason=str(exc),
traceback=traceback.format_exc(), epoch=epoch, steps=steps,
**(peaks() if torch.cuda.is_initialized() else {})))
raise
if __name__ == '__main__':
run(Path(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))