#!/usr/bin/env python """DeepH-E3 Hamiltonian training for diamond — with live monitoring. Uses our own 1_data_prepare data. Training runs continuously (no chunking) to keep LR-scheduler state intact. Every CHECK_INTERVAL epochs the val_loss is compared to reference milestones; if it lags more than STALL_RATIO× the reference, training is stopped for investigation. Usage: python train_ham.py [params.json] # train on our data python train_ham.py [params.json] --ref-graph # diagnostic: use reference graph PKL Reference milestones (from diamond-qe reference training): Epoch 300: val_loss = 1.76e-05 LR = 2.00e-03 Epoch 600: val_loss = 8.40e-06 LR = 2.00e-03 Epoch 900: val_loss = 3.92e-06 LR = 1.00e-03 (first LR drop) Epoch 1200: val_loss = 2.63e-06 LR = 2.50e-04 Epoch 1500: val_loss = 2.40e-06 LR = 1.25e-04 Epoch 1800: val_loss = 2.03e-06 LR = 3.13e-05 Epoch 2017: val_loss = 1.98e-06 LR = 1.56e-05 (best model) """ import glob import json import os import re import subprocess import sys import time SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.abspath( os.path.join(SCRIPT_DIR, '..', '..', '1_data_prepare', 'data')) PARAMS_DEFAULT = os.path.abspath( os.path.join(SCRIPT_DIR, '..', '..', '1_data_prepare', 'params.json')) DATASET_DIR = os.path.join(SCRIPT_DIR, 'dataset') GRAPH_DIR = os.path.join(SCRIPT_DIR, '..', 'graph') GRAPH_PKL = os.path.join(GRAPH_DIR, 'HGraph-diamond_qe_e3-rFromDFT-edge=Aij.pkl') REF_GRAPH_PKL = ( '/home/apolyukhin/scripts/ml/diamond-qe/deeph-e3/graph/' 'HGraph-diamond_qe_e3-rFromDFT-edge=Aij.pkl' ) RESULTS_DIR = os.path.join(SCRIPT_DIR, 'results') INI_PATH = os.path.join(SCRIPT_DIR, 'train.ini') LAUNCHER = os.path.join(SCRIPT_DIR, '_launcher.py') TRAIN_LOG = os.path.join(SCRIPT_DIR, 'train.log') # Reference val_loss milestones REF_MILESTONES = { 300: 1.76e-5, 600: 8.40e-6, 900: 3.92e-6, 1200: 2.63e-6, 1500: 2.40e-6, 1800: 2.03e-6, } CHECK_INTERVAL = 300 # check every this many epochs STALL_RATIO = 5.0 # stop if val_loss > STALL_RATIO × reference milestone POLL_SECONDS = 30 # how often to poll the log file def load_params(path=None): with open(path or PARAMS_DEFAULT) as f: return json.load(f) def build_dataset_links(): """Create dataset/ with numbered dirs, each symlinking files from aohamiltonian/.""" os.makedirs(DATASET_DIR, exist_ok=True) disp_dirs = sorted(glob.glob(os.path.join(DATA_DIR, 'disp-*'))) n = 0 for disp_dir in disp_dirs: ao_dir = os.path.abspath( os.path.join(disp_dir, 'reconstruction', 'aohamiltonian')) if not os.path.exists(os.path.join(ao_dir, 'hamiltonians.h5')): print(f' WARNING: no hamiltonians.h5 in {ao_dir}, skipping') continue dest = os.path.join(DATASET_DIR, f'{n:02d}') os.makedirs(dest, exist_ok=True) for fname in os.listdir(ao_dir): link = os.path.join(dest, fname) if not os.path.exists(link): os.symlink(os.path.join(ao_dir, fname), link) n += 1 print(f' {n} dataset dirs ready in {DATASET_DIR}') return n def write_train_ini(params, use_ref_graph=False, num_epoch=None, results_dir=None): """Write train.ini with reference hyperparameters and our own data.""" t = params.get('hamiltonian', {}) save_dir = results_dir or RESULTS_DIR if use_ref_graph: graph_dir_val = REF_GRAPH_PKL processed_data_val = '' save_graph_val = '' print(f' Using REFERENCE graph PKL: {graph_dir_val}') elif os.path.exists(GRAPH_PKL): graph_dir_val = os.path.abspath(GRAPH_PKL) processed_data_val = '' save_graph_val = '' print(f' Using cached graph: {graph_dir_val}') else: graph_dir_val = '' processed_data_val = DATASET_DIR save_graph_val = os.path.abspath(GRAPH_DIR) print(f' Graph not found — will build from {DATASET_DIR}') ini = f"""; DeepH-E3 training config — generated by train_ham.py [basic] device = {t.get('device', 'cuda')} dtype = float save_dir = {save_dir} additional_folder_name = diamond_e3 simplified_output = False seed = 42 checkpoint_dir = use_new_hypp = True [data] graph_dir = {graph_dir_val} DFT_data_dir = processed_data_dir = {processed_data_val} save_graph_dir = {save_graph_val} target_data = hamiltonian dataset_name = diamond_qe_e3 get_overlap = False [train] num_epoch = {num_epoch or t.get('num_epoch', 3000)} batch_size = 1 extra_validation = [] extra_val_test_only = True train_size = {t.get('train_size', 30)} val_size = {t.get('val_size', 10)} test_size = 10 min_lr = 1e-5 [hyperparameters] learning_rate = {t.get('learning_rate', 0.002)} Adam_betas = (0.9, 0.999) scheduler_type = 1 scheduler_params = (factor=0.5, cooldown=40, patience=120, threshold=0.05) revert_decay_patience = 20 revert_decay_rate = 0.8 [target] target = hamiltonian target_blocks_type = all target_blocks = selected_element_pairs = convert_net_out = False [network] cutoff_radius = {t.get('cutoff_radius', 7.4)} only_ij = False spherical_harmonics_lmax = {t.get('lmax', 4)} spherical_basis_irreps = irreps_embed = {t.get('irreps_embed', '64x0e')} irreps_mid = {t.get('irreps_mid', '64x0e+32x1o+16x2e+8x3o+8x4e')} num_blocks = {t.get('num_blocks', 3)} ignore_parity = False irreps_embed_node = irreps_edge_init = irreps_mid_node = irreps_post_node = irreps_out_node = irreps_mid_edge = irreps_post_edge = out_irreps = """ with open(INI_PATH, 'w') as f: f.write(ini) print(f' Written {INI_PATH}') def write_launcher(params): t = params.get('hamiltonian', {}) deeph_e3_dir = t.get('deeph_e3_dir', '/home/apolyukhin/Development/DeepH-E3') with open(LAUNCHER, 'w') as f: f.write(f"""import sys, torch torch.serialization.add_safe_globals([slice]) try: from torch_geometric.data.data import DataEdgeAttr, DataTensorAttr from torch_geometric.data.storage import GlobalStorage torch.serialization.add_safe_globals([DataEdgeAttr, DataTensorAttr, GlobalStorage]) except ImportError: pass sys.path.insert(0, '{deeph_e3_dir}') from deephe3 import DeepHE3Kernel kernel = DeepHE3Kernel() kernel.train('{INI_PATH}') """) def parse_train_log(log_path): """Return {epoch: val_loss} from training log.""" result = {} try: with open(log_path) as f: for line in f: m = re.search(r'Epoch #(\d+)\s+\|.*Val loss:\s+([\d.e+\-]+)', line) if m: result[int(m.group(1))] = float(m.group(2)) except (FileNotFoundError, OSError): pass return result def monitor_loop(proc, log_path=None): """Poll log every POLL_SECONDS; report at CHECK_INTERVAL boundaries. Returns True if stall was detected (proc already terminated), else False. """ log_path = log_path or TRAIN_LOG last_reported = 0 while proc.poll() is None: time.sleep(POLL_SECONDS) history = parse_train_log(log_path) if not history: continue latest = max(history) boundary = (latest // CHECK_INTERVAL) * CHECK_INTERVAL if boundary > last_reported and boundary > 0: last_reported = boundary # Best val_loss up to this boundary window = {ep: v for ep, v in history.items() if ep <= boundary + 20} if not window: continue val = min(window.values()) ref = REF_MILESTONES.get(boundary) if ref: ratio = val / ref flag = 'OK' if ratio < STALL_RATIO else 'STALLED' print(f' [epoch ~{boundary:4d}] val={val:.3e} ' f'ref={ref:.3e} ratio={ratio:.1f}x [{flag}]', flush=True) if ratio > STALL_RATIO: print(f'\nStall detected ({ratio:.1f}x above reference). ' f'Terminating training.') proc.terminate() return True else: print(f' [epoch ~{boundary:4d}] val={val:.3e}', flush=True) return False def main(): use_ref_graph = '--ref-graph' in sys.argv params_path = next((a for a in sys.argv[1:] if not a.startswith('--')), None) params = load_params(params_path) t = params.get('hamiltonian', {}) conda_env = t.get('conda_env', 'deeph') conda_base = params['paths']['conda_base'] # Diagnostic mode: use reference graph, separate results dir and log if use_ref_graph: results_dir = os.path.join(SCRIPT_DIR, 'results_ref') train_log = os.path.join(SCRIPT_DIR, 'train_ref.log') num_epoch = 500 if not os.path.exists(REF_GRAPH_PKL): print(f'ERROR: Reference graph not found:\n {REF_GRAPH_PKL}') sys.exit(1) print('=== DIAGNOSTIC: using reference graph PKL (500 epochs) ===') else: results_dir = RESULTS_DIR train_log = TRAIN_LOG num_epoch = None os.makedirs(results_dir, exist_ok=True) os.makedirs(os.path.abspath(GRAPH_DIR), exist_ok=True) # Build dataset symlinks only if graph PKL is missing (non-ref mode) if not use_ref_graph and not os.path.exists(GRAPH_PKL): print('Step 1: Building dataset symlinks...') n = build_dataset_links() if n == 0: print('ERROR: No aohamiltonian data found. Run reconstruct.py first.') sys.exit(1) else: print('Step 1: Skipped (graph PKL available).') print('Step 2: Writing train.ini...') write_train_ini(params, use_ref_graph=use_ref_graph, num_epoch=num_epoch, results_dir=results_dir) write_launcher(params) print('\nReference milestones:') for ep, vl in sorted(REF_MILESTONES.items()): print(f' Epoch {ep:5d}: val_loss = {vl:.2e}') print(f'\nStall threshold : {STALL_RATIO}× reference') print(f'Training log : {train_log}') print(f'Conda env : {conda_env}') print(f'\nStep 3: Launching training...\n', flush=True) activate = (f'source {conda_base}/etc/profile.d/conda.sh' f' && conda activate {conda_env}') with open(train_log, 'w') as log_f: proc = subprocess.Popen( ['bash', '-c', f'{activate} && python {LAUNCHER}'], stdout=log_f, stderr=subprocess.STDOUT, ) try: stalled = monitor_loop(proc, train_log) except KeyboardInterrupt: print('\nInterrupted — stopping training.') proc.terminate() stalled = False rc = proc.wait() # Final summary history = parse_train_log(train_log) if history: best_ep = min(history, key=history.get) best_val = history[best_ep] last_ep = max(history) last_val = history[last_ep] print(f'\nTraining finished (exit code {rc}).') print(f' Last epoch {last_ep:5d}: val_loss = {last_val:.3e}') print(f' Best epoch {best_ep:5d}: val_loss = {best_val:.3e}') print(f' Reference best (epoch 2017): 1.98e-06') print(f' Ratio to reference best: {best_val / 1.98e-6:.2f}×') else: print(f'\nTraining finished (exit code {rc}). No log data parsed.') if stalled: print('\nInvestigation hints:') print(' - Check train.log for LR at stall point.') print(' - If val_loss is flat, verify data matches reference:') print(' diff sizes: ls -lh 1_data_prepare/data/disp-01/' 'reconstruction/aohamiltonian/hamiltonians.h5') print(' vs reference: /home/apolyukhin/scripts/ml/diamond-qe/' 'disp-01/reconstruction/aohamiltonian/hamiltonians.h5') if __name__ == '__main__': main()