File size: 21,510 Bytes
c74e524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
"""Phase 2: duplex text training — control lane + public text + aux prosody head.



Init: base Qwen3.5-4B + Stage 1B LoRA + projector/gate/bias.

New: 6 control tokens, lane-normalised losses, weighted event sampling, 30%

native-text replay to protect intelligence.

"""
from __future__ import annotations

import argparse
import json
import random
import sys
import time
from pathlib import Path

import numpy as np
import torch
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer

sys.path.insert(0, str(Path(__file__).resolve().parent))
from stage1_data import (AnnTurns, JsonlReader, MimiStore, PROSODY,  # noqa: E402
                         build_item_history, collate as collate1)
from stage2_data import CTRL_TOKENS, N_AUX, build_item, collate  # noqa: E402
from train_stage1a import Projector, sched_scale  # noqa: E402

MODEL = Path('/workspace/chroma_duplex_demo/models/qwen3.5-4b')
MIMI = Path('/workspace/chroma_duplex_demo/dataset_features/mimi_user')
ANN = Path('/workspace/chroma_duplex_demo/annotations/duplex_5k')

CTRL_W = torch.tensor([1.0, 1.5, 4.0, 6.0, 3.0, 6.0])
AUX_W = torch.tensor([1.0, 3.0, 3.0, 2.0, 2.0])


class AuxHead(torch.nn.Module):
    def __init__(self, d, n=N_AUX):
        super().__init__()
        self.net = torch.nn.Sequential(
            torch.nn.LayerNorm(d), torch.nn.Linear(d, 512),
            torch.nn.GELU(), torch.nn.Linear(512, n))

    def forward(self, x):
        return self.net(x)


def embed(model, proj, bias, ctrl_emb, batch, vocab):
    ids = batch['input_ids']
    safe = ids.clone()
    safe[safe >= vocab] = 0
    emb = model.get_input_embeddings()(safe).clone()
    if batch['pos'].numel():
        v = proj(batch['vecs']) + bias
        emb[0, batch['pos']] = v.to(emb.dtype)
    if batch.get('ctrl_pos') is not None and batch['ctrl_pos'].numel():
        emb[0, batch['ctrl_pos']] = ctrl_emb[batch['ctrl_lab']].to(emb.dtype)
    return emb


def load_windows(path):
    out = []
    for line in Path(path).read_text().splitlines():
        if line.strip():
            out.append(json.loads(line))
    return out


def load_pools(spec, log=None):
    """Comma-separated pools. Missing files are reported, not fatal."""
    out = []
    for p in [x.strip() for x in (spec or '').split(',') if x.strip()]:
        if Path(p).is_file():
            out += load_windows(p)
        elif log:
            log({'event': 'missing_pool', 'path': p})
    return out


class MultiStore:
    """MimiStore over several roots so human tracks can carry their own features.



    Corpus windows resolve as <root>/<cohort>/<session>.npy; human windows are

    emitted with cohort = source ('oto'|'dt') and session = track id, so they

    resolve against stage3/human_feat without touching the corpus layout.

    """

    def __init__(self, roots, max_open=96):
        self.stores = [MimiStore(r, max_open) for r in roots if Path(r).is_dir()]

    def get(self, cohort, sid):
        for st in self.stores:
            arr = st.get(cohort, sid)
            if arr is not None:
                return arr
        return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--train', default='stage2/examples/train.jsonl')
    ap.add_argument('--val', default='stage2/examples/val.jsonl')
    ap.add_argument('--init', default='stage1/checkpoints/stage1b/lora_final.pt')
    ap.add_argument('--p1-train', default='stage1/examples/train.jsonl')
    ap.add_argument('--out', default='stage2/checkpoints')
    ap.add_argument('--max-len', type=int, default=2048)
    ap.add_argument('--accum', type=int, default=8)
    ap.add_argument('--lr-lora', type=float, default=1e-4)
    ap.add_argument('--lr-proj', type=float, default=2e-4)
    ap.add_argument('--lr-gate', type=float, default=5e-3)
    ap.add_argument('--lr-bias', type=float, default=5e-3)
    ap.add_argument('--lr-aux', type=float, default=3e-4)
    ap.add_argument('--lr-ctrl', type=float, default=1e-3)
    ap.add_argument('--warmup', type=int, default=50)
    ap.add_argument('--samples', type=int, default=20000)
    ap.add_argument('--epochs', type=int, default=1)
    ap.add_argument('--replay', type=float, default=0.30)
    ap.add_argument('--tl-train', default='stage3/timeline/train.jsonl')
    ap.add_argument('--tl-ratio', type=float, default=0.20)
    ap.add_argument('--p2-extra', default='')
    ap.add_argument('--p2-extra-val', default='')
    ap.add_argument('--mimi-extra', default='stage3/human_feat')
    ap.add_argument('--act-w', type=float, default=1.5)
    ap.add_argument('--ctrl-w', type=float, default=2.5)
    ap.add_argument('--aux-w', type=float, default=0.3)
    ap.add_argument('--eval-every', type=int, default=250)
    ap.add_argument('--eval-n', type=int, default=200)
    ap.add_argument('--save-every', type=int, default=500)
    ap.add_argument('--log-every', type=int, default=20)
    ap.add_argument('--max-hours', type=float, default=6)
    ap.add_argument('--seed', type=int, default=2026)
    ap.add_argument('--curriculum', default='all', choices=['all', 'a', 'b', 'c'])
    ap.add_argument('--smoke', action='store_true')
    args = ap.parse_args()
    if args.smoke:
        args.samples, args.accum = 16, 2
        args.eval_every, args.eval_n = 4, 8
        args.save_every, args.log_every, args.warmup = 1000, 2, 2

    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    logf = open(out / 'train.jsonl', 'a')

    def log(rec):
        rec['t'] = round(time.time(), 1)
        logf.write(json.dumps(rec) + '\n')
        logf.flush()
        print(json.dumps(rec), flush=True)

    log({'event': 'start', 'args': vars(args)})

    tok = AutoTokenizer.from_pretrained(MODEL)
    tok.add_special_tokens({'additional_special_tokens': [PROSODY] + CTRL_TOKENS})
    pid = tok.convert_tokens_to_ids(PROSODY)
    ctrl_ids = [tok.convert_tokens_to_ids(t) for t in CTRL_TOKENS]
    pad = tok.pad_token_id or tok.eos_token_id

    model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.bfloat16,
                                                 device_map='cuda', low_cpu_mem_usage=True)
    vocab = model.get_input_embeddings().weight.shape[0]
    for p in model.parameters():
        p.requires_grad_(False)
    ck = torch.load(args.init, map_location='cpu', weights_only=False)
    cfg = ck['lora_cfg']
    model = get_peft_model(model, LoraConfig(
        r=cfg['r'], lora_alpha=cfg['lora_alpha'], lora_dropout=0.05,
        bias='none', task_type='CAUSAL_LM', target_modules=cfg['target_modules']))
    miss = model.load_state_dict(ck['lora'], strict=False)
    model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False})
    model.config.use_cache = False
    model.train()

    hidden = ck['bias'].shape[0]
    proj = Projector(512, hidden).cuda()
    proj.load_state_dict(ck['projector'])
    bias = ck['bias'].cuda().clone().requires_grad_(True)
    aux_head = AuxHead(hidden).cuda()
    act_norm = torch.nn.LayerNorm(hidden).cuda()
    act_head = torch.nn.Linear(hidden, 2).cuda()
    torch.nn.init.normal_(act_head.weight, std=0.02)
    torch.nn.init.zeros_(act_head.bias)
    ctrl_emb = torch.nn.Parameter(torch.randn(6, hidden, device='cuda') * 0.02)
    ctrl_norm = torch.nn.LayerNorm(hidden).cuda()
    ctrl_out = torch.nn.Linear(hidden, 6, bias=False).cuda()
    torch.nn.init.normal_(ctrl_out.weight, std=0.01)
    if 'ctrl_emb' in ck:
        with torch.no_grad():
            ctrl_emb.copy_(ck['ctrl_emb'].cuda())
            ctrl_norm.load_state_dict(ck['ctrl_norm'])
            ctrl_out.load_state_dict(ck['ctrl_out'])
            aux_head.load_state_dict(ck['aux_head'])
            if 'act_head' in ck and ck.get('act_head') is not None:
                act_head.load_state_dict(ck['act_head'])
                if ck.get('act_norm') is not None:
                    act_norm.load_state_dict(ck['act_norm'])
        log({'event': 'warmstart_ctrl', 'from': args.init})

    lora_params = [p for n, p in model.named_parameters() if 'lora_' in n and p.requires_grad]
    proj_rest = [p for n, p in proj.named_parameters() if n != 'gate']
    opt = torch.optim.AdamW([
        {'params': lora_params, 'lr': args.lr_lora, 'weight_decay': 0.01, '_lr': args.lr_lora},
        {'params': proj_rest, 'lr': args.lr_proj, 'weight_decay': 0.01, '_lr': args.lr_proj},
        {'params': [proj.gate], 'lr': args.lr_gate, 'weight_decay': 0.0, '_lr': args.lr_gate},
        {'params': [bias], 'lr': args.lr_bias, 'weight_decay': 0.0, '_lr': args.lr_bias},
        {'params': list(aux_head.parameters()), 'lr': args.lr_aux,
         'weight_decay': 0.01, '_lr': args.lr_aux},
        {'params': list(act_head.parameters()) + list(act_norm.parameters()),
         'lr': args.lr_aux, 'weight_decay': 0.01, '_lr': args.lr_aux},
        {'params': [ctrl_emb, ctrl_out.weight] + list(ctrl_norm.parameters()),
         'lr': args.lr_ctrl, 'weight_decay': 0.0, '_lr': args.lr_ctrl},
    ])
    ctrl_w = [1.0, 1.5, 4.0, 6.0, 3.0, 6.0]
    aux_w = AUX_W.cuda()

    train = load_windows(args.train) + load_pools(args.p2_extra, log)
    val = load_windows(args.val) + load_pools(args.p2_extra_val, log)
    if args.curriculum != 'all':
        def keep(x):
            d = x['decision']
            if args.curriculum == 'a':   # ordinary dialogue + single/no call, short
                return (d in ('respond', 'wait', 'none')
                        and x.get('tool_kind', 'free') in ('single', 'no_call', 'free')
                        and not x.get('is_long'))
            if args.curriculum == 'b':   # targeted floor events + multi-tool + no-call
                return (d in ('continue', 'yield', 'hold', 'stale')
                        or x.get('tool_kind') == 'multi' or x.get('no_call'))
            if args.curriculum == 'c':   # long sessions with tool dependencies
                return bool(x.get('is_long'))
            return True
        train = [x for x in train if keep(x)]
        log({'event': 'curriculum', 'stage': args.curriculum, 'windows': len(train)})
    tl = load_pools(args.tl_train, log)
    store = MultiStore([MIMI] + [p.strip() for p in (args.mimi_extra or '').split(',') if p.strip()])
    p1 = JsonlReader(args.p1_train)
    anns = AnnTurns(ANN)
    w = np.array([max(0.05, float(x.get('weight', 1.0))) for x in train], dtype=np.float64)
    cum = np.cumsum(w / w.sum())
    if tl:
        tl_w = np.array([max(0.05, float(x.get('weight', 1.0))) for x in tl], dtype=np.float64)
        tl_cum = np.cumsum(tl_w / tl_w.sum())
    else:
        tl_cum = np.zeros(0)
    log({'event': 'data', 'windows': len(train), 'val': len(val),
         'by_decision': {d: sum(1 for x in train if x['decision'] == d)
                         for d in ('respond', 'wait', 'continue', 'yield', 'hold',
                                   'stale', 'none')},
         'human_windows': sum(1 for x in train if x.get('cohort') in ('oto', 'dt')),
         'human_val': sum(1 for x in val if x.get('cohort') in ('oto', 'dt')),
         'lora_params': sum(p.numel() for p in lora_params), 'missing_keys': len(miss.missing_keys),
         'tl_windows': len(tl),
         'tl_human': sum(1 for x in tl if x.get('cohort') in ('oto', 'dt')),
         'mimi_roots': len(store.stores)})

    eval_wins = random.Random(5).sample(range(len(val)), min(args.eval_n, len(val)))
    total_opt = max(1, (args.samples * args.epochs) // args.accum)

    def sample_win():
        return train[int(np.searchsorted(cum, random.random()))]

    def build_p2(win):
        return build_item(win, tok, pid, ctrl_ids, store, args.max_len)

    def build_tl():
        return build_item(tl[int(np.searchsorted(tl_cum, random.random()))], tok, pid,
                          ctrl_ids, store, args.max_len, activity_only=True)

    def build_p1():
        for _ in range(8):
            i = random.randrange(len(p1))
            ex = p1.get(i)
            if ex.get('stale_conflict') or not ex.get('user_last'):
                continue
            ut = anns.get(ex['cohort'], ex['session'])
            item, err = build_item_history(ex, tok, pid, store, args.max_len,
                                           'text', False, 'full', ut)
            if not err:
                return item
        return None

    def forward_step(batch, is_p2, is_tl=False):
        batch = {k: (v.cuda() if torch.is_tensor(v) else v) for k, v in batch.items()}
        emb = embed(model, proj, bias, ctrl_emb, batch, vocab)
        out = model(inputs_embeds=emb, attention_mask=batch['attention_mask'],
                    labels=batch['labels'], output_hidden_states=(is_p2 or is_tl),
                    use_cache=False)
        if (batch['labels'] != -100).any():
            text_loss = out.loss
        else:
            text_loss = torch.zeros((), device='cuda')
        ctrl_loss = aux_loss = None
        if is_p2 and batch['ctrl_pos'].numel():
            hs = out.hidden_states[-1][0, batch['ctrl_pos'] - 1].float()
            lg = ctrl_out(ctrl_norm(hs))
            per = torch.nn.functional.cross_entropy(lg, batch['ctrl_lab'], reduction='none')
            cw = torch.tensor([ctrl_w[int(c)] for c in batch['ctrl_lab']], device=lg.device)
            ctrl_loss = (per * cw).sum() / cw.sum().clamp(min=1e-6)
        if is_p2 and batch['aux_pos'].numel():
            hs = out.hidden_states[-1][0, batch['aux_pos']].float()
            al = aux_head(hs)
            per = torch.nn.functional.cross_entropy(al, batch['aux_lab'], reduction='none')
            aw = aux_w[batch['aux_lab']]
            aux_loss = (per * aw).sum() / aw.sum().clamp(min=1e-6)
        act_loss = None
        if batch.get('act_pos') is not None and batch['act_pos'].numel():
            # Probe-only: the activity head is a runtime readout, so it must not
            # reshape the backbone. Letting it backprop (refresh4) cost 3.8 points
            # of onset yield -- the quiet objective leaked into floor decisions.
            hs_a = out.hidden_states[-1][0, batch['act_pos']].float().detach()
            act_loss = torch.nn.functional.cross_entropy(act_head(act_norm(hs_a)),
                                                         batch['act_lab'])
        total = text_loss
        if ctrl_loss is not None:
            total = total + args.ctrl_w * ctrl_loss
        if aux_loss is not None:
            total = total + args.aux_w * aux_loss
        if act_loss is not None:
            total = total + args.act_w * act_loss
        return total, text_loss, ctrl_loss, aux_loss, act_loss, batch

    @torch.no_grad()
    def evaluate():
        model.eval()
        tl = 0.0
        nt = 0
        correct = 0
        total = 0
        per_cls = {}
        for i in eval_wins:
            item, err = build_p2(val[i])
            if err:
                continue
            b = collate([item], pad)
            b = {k: (v.cuda() if torch.is_tensor(v) else v) for k, v in b.items()}
            emb = embed(model, proj, bias, ctrl_emb, b, vocab)
            o = model(inputs_embeds=emb, attention_mask=b['attention_mask'],
                      labels=b['labels'], output_hidden_states=True, use_cache=False)
            tl += float(o.loss)
            nt += 1
            if b['ctrl_pos'].numel():
                hs = o.hidden_states[-1][0, b['ctrl_pos'] - 1].float()
                pred = ctrl_out(ctrl_norm(hs)).argmax(-1)
                ok = (pred == b['ctrl_lab'])
                correct += int(ok.sum())
                total += int(ok.numel())
                for c in range(len(CTRL_TOKENS)):
                    m = b['ctrl_lab'] == c
                    if m.any():
                        s = per_cls.setdefault(c, [0, 0])
                        s[0] += int(ok[m].sum())
                        s[1] += int(m.sum())
        model.train()
        return {'loss': round(tl / max(1, nt), 4), 'ctrl_acc': round(correct / max(1, total), 4),
                'n_ctrl': total,
                'per_ctrl': {CTRL_TOKENS[c]: round(v[0] / max(1, v[1]), 3)
                             for c, v in sorted(per_cls.items())}}

    t0 = time.time()
    micro = opt_step = 0
    run = []
    skip = {}
    for epoch in range(args.epochs):
        log({'event': 'epoch', 'epoch': epoch})
        for k in range(args.samples):
            if tl and random.random() < args.tl_ratio:
                item, err = build_tl()
                if err:
                    skip[err.split(':')[0]] = skip.get(err.split(':')[0], 0) + 1
                    continue
                batch = collate([item], pad)
                is_p2, is_tl = False, True
            elif random.random() < args.replay:
                item = build_p1()
                if item is None:
                    continue
                batch = collate1([item], pad)
                is_p2, is_tl = False, False
            else:
                item, err = build_p2(sample_win())
                if err:
                    skip[err.split(':')[0]] = skip.get(err.split(':')[0], 0) + 1
                    continue
                batch = collate([item], pad)
                is_p2, is_tl = True, False
            total, text_loss, ctrl_loss, aux_loss, act_loss, b = forward_step(batch, is_p2, is_tl)
            if (not torch.isfinite(total)) or float(total.detach()) > 60.0:
                skip['loss_spike'] = skip.get('loss_spike', 0) + 1
                continue
            (total / args.accum).backward()
            run.append(float(total.detach()))
            micro += 1
            if micro % args.accum == 0:
                for g in opt.param_groups:
                    g['lr'] = g['_lr'] * sched_scale(opt_step, args.warmup, total_opt)
                torch.nn.utils.clip_grad_norm_(
                    lora_params + proj_rest + [proj.gate, bias, ctrl_emb, ctrl_out.weight]
                    + list(ctrl_norm.parameters()) + list(aux_head.parameters())
                    + list(act_head.parameters()) + list(act_norm.parameters()), 1.0)
                opt.step()
                opt.zero_grad(set_to_none=True)
                opt_step += 1
                if opt_step % args.log_every == 0:
                    log({'event': 'step', 'step': opt_step,
                         'loss': round(float(np.mean(run[-50:])), 4),
                         'text': round(float(text_loss.detach()), 4),
                         'ctrl': None if ctrl_loss is None else round(float(ctrl_loss.detach()), 4),
                         'aux': None if aux_loss is None else round(float(aux_loss.detach()), 4),
                         'act': None if act_loss is None else round(float(act_loss.detach()), 4),
                         'gate': round(float(proj.gate.detach()), 4),
                         'elapsed_min': round((time.time() - t0) / 60, 1),
                         'skip': skip})
                if opt_step % args.eval_every == 0:
                    log({'event': 'eval', 'step': opt_step, **evaluate(),
                         'peak_gb': round(torch.cuda.max_memory_allocated() / 1e9, 2)})
                if opt_step % args.save_every == 0:
                    save(out, f'stage2_step{opt_step}.pt', model, proj, bias, aux_head,
                         ctrl_emb, ctrl_norm, ctrl_out, pid, opt_step, args,
                         act_head, act_norm)
                if args.max_hours and (time.time() - t0) / 3600 > args.max_hours:
                    break
        if args.max_hours and (time.time() - t0) / 3600 > args.max_hours:
            break

    log({'event': 'final_eval', **evaluate()})
    save(out, 'stage2_final.pt', model, proj, bias, aux_head, ctrl_emb, ctrl_norm,
         ctrl_out, pid, opt_step, args, act_head, act_norm)
    log({'event': 'done', 'opt_steps': opt_step,
         'elapsed_min': round((time.time() - t0) / 60, 1), 'skip': skip})


def save(out, name, model, proj, bias, aux_head, ctrl_emb, ctrl_norm, ctrl_out,

         pid, step, args, act_head=None, act_norm=None):
    lora = {k: v.detach().cpu() for k, v in model.state_dict().items() if 'lora_' in k}
    torch.save({'lora': lora, 'projector': proj.state_dict(),
                'bias': bias.detach().cpu(), 'aux_head': aux_head.state_dict(),
                'ctrl_emb': ctrl_emb.detach().cpu(), 'ctrl_norm': ctrl_norm.state_dict(),
                'ctrl_out': ctrl_out.state_dict(),
                'act_head': act_head.state_dict() if act_head is not None else None,
                'act_norm': act_norm.state_dict() if act_norm is not None else None,
                'pid': pid, 'ctrl_tokens': CTRL_TOKENS, 'step': step,
                'lora_cfg': {'r': 16, 'lora_alpha': 32, 'lora_dropout': 0.05,
                             'target_modules': ['q_proj', 'k_proj', 'v_proj', 'o_proj',
                                                'in_proj_qkv', 'in_proj_z', 'in_proj_b',
                                                'in_proj_a', 'out_proj']},
                'args': vars(args)}, out / name)


if __name__ == '__main__':
    main()