File size: 11,970 Bytes
d975267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/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()