File size: 7,174 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
"""Phase 2 collator: public-text lane + control-token lane + aux prosody labels."""
from __future__ import annotations

import json
import random
import zlib
from pathlib import Path

import numpy as np

from stage1_data import IM_START, PROSODY, MimiStore, pool

CTRL_TOKENS = ['<|respond|>', '<|wait|>', '<|continue|>', '<|yield|>',
               '<|hold|>', '<|stale|>']
N_AUX = 5
D_IN = 512


def build_item(win, tok, pid, ctrl_ids, store, max_len, prosody_mode='full',

               activity_only=False):
    msgs = [{'role': 'system',
             'content': win.get('system') or 'You are Aiden, a concise voice assistant.'}]
    vecs, aux = [], []
    parts = []
    for e in win.get('user_events') or []:
        v = pool(store, win, e.get('pf'))
        if v is None:
            # Keep committed text even when no causal prosody frame covers it;
            # dropping the word too would silently lose user content.
            if e.get('text'):
                parts.append(e['text'])
            continue
        parts.append(PROSODY + (e.get('text') or ''))
        vecs.append(v)
        aux.append(int(e.get('aux', 0)))
    if vecs and prosody_mode == 'zero':
        vecs = [np.zeros(D_IN, dtype=np.float32) for _ in vecs]
    elif vecs and prosody_mode == 'shuffle' and len(vecs) > 1:
        idx = list(range(len(vecs)))
        random.Random(zlib.crc32(str(win.get('id', '')).encode())).shuffle(idx)
        vecs = [vecs[i] for i in idx]
        aux = [aux[i] for i in idx]
    if parts:
        msgs.append({'role': 'user', 'content': ' '.join(parts)})
    else:
        msgs.append({'role': 'user', 'content': ''})
    if win.get('played_prefix'):
        msgs.append({'role': 'assistant', 'content': win['played_prefix']})
    for tc in win.get('tool_ctx') or []:
        # The assistant's own call must precede its result, otherwise the model
        # sees an orphan tool response and re-calls instead of answering.
        msgs.append({'role': 'assistant', 'content': tc.get('filler', ''),
                     'tool_calls': [{'type': 'function',
                                     'function': {'name': tc.get('name'),
                                                  'arguments': tc.get('arguments') or {}}}]})
        msgs.append({'role': 'tool',
                     'content': json.dumps(tc.get('payload'), ensure_ascii=False)})

    if activity_only:
        text = tok.apply_chat_template(msgs, tools=win.get('tools') or None,
                                       tokenize=False,
                                       add_generation_prompt=True,
                                       enable_thinking=False)
        ids = tok(text, add_special_tokens=False)['input_ids']
        if len(ids) > max_len:
            return None, 'too_long'
        pos = [i for i, x in enumerate(ids) if x == pid]
        if len(pos) != len(vecs):
            return None, f'prosody_mismatch:{len(pos)}:{len(vecs)}'
        return {'ids': ids, 'labels': [-100] * len(ids), 'pos': pos,
                'vecs': np.stack(vecs) if vecs else np.zeros((0, D_IN), np.float32),
                'ctrl_pos': [], 'ctrl_lab': [], 'aux_pos': pos, 'aux_lab': aux,
                'act_pos': len(ids) - 1, 'act_lab': int(win.get('activity', 0)),
                'meta': {'id': win.get('id'), 'decision': win.get('decision')}}, None

    tgt = win['target']
    content = (tgt.get('control') or '') + (tgt.get('text') or '')
    m = {'role': 'assistant', 'content': content}
    if tgt.get('tool_calls'):
        m['tool_calls'] = [{'type': 'function',
                            'function': {'name': c['name'],
                                         'arguments': c['arguments']}}
                           for c in tgt['tool_calls']]
    msgs.append(m)

    tools = win.get('tools') or None
    tools_ref = tools
    try:
        text = tok.apply_chat_template(msgs, tools=tools, tokenize=False,
                                       add_generation_prompt=False,
                                       enable_thinking=False)
    except TypeError:
        text = tok.apply_chat_template(msgs, tools=tools, tokenize=False,
                                       add_generation_prompt=False)
    ids = tok(text, add_special_tokens=False)['input_ids']
    if len(ids) > max_len:
        return None, 'too_long'

    im = tok.convert_tokens_to_ids(IM_START)
    last = max((i for i, x in enumerate(ids) if x == im), default=None)
    if last is None:
        return None, 'no_im_start'
    role = tok.encode('assistant\n', add_special_tokens=False)
    cs = last + 1
    for j in range(last + 1, min(len(ids), last + 12)):
        if ids[j:j + len(role)] == role:
            cs = j + len(role)
            break

    labels = [-100] * len(ids)
    labels[cs:] = ids[cs:]
    ctrl_pos, ctrl_lab = [], []
    for i in range(cs, len(ids)):
        if ids[i] in ctrl_ids:
            ctrl_pos.append(i)
            ctrl_lab.append(ctrl_ids.index(ids[i]))
            labels[i] = -100          # control lane gets its own head + weighted loss
    pos = [i for i, x in enumerate(ids) if x == pid]
    if len(pos) != len(vecs):
        return None, f'prosody_mismatch:{len(pos)}:{len(vecs)}'
    if len(pos) != len(aux):
        return None, 'aux_mismatch'

    tgt_control = tgt.get('control')
    act_lab = 1 if (tgt_control in ('<|respond|>', '<|continue|>')
                    or (tgt_control is None and (tgt.get('text') or '').strip())) else 0
    return {'ids': ids, 'labels': labels, 'pos': pos,
            'vecs': np.stack(vecs) if vecs else np.zeros((0, D_IN), np.float32),
            'ctrl_pos': ctrl_pos, 'ctrl_lab': ctrl_lab,
            'aux_pos': pos, 'aux_lab': aux,
            'act_pos': max(0, cs - 1), 'act_lab': act_lab,
            'meta': {'id': win.get('id'), 'decision': win.get('decision')}}, None


def collate(items, pad_id):
    import torch
    L = max(len(it['ids']) for it in items)
    n = len(items)
    input_ids = np.full((n, L), pad_id, dtype=np.int64)
    labels = np.full((n, L), -100, dtype=np.int64)
    mask = np.zeros((n, L), dtype=np.int64)
    for b, it in enumerate(items):
        k = len(it['ids'])
        input_ids[b, :k] = it['ids']
        labels[b, :k] = it['labels']
        mask[b, :k] = 1
    return {
        'input_ids': torch.from_numpy(input_ids),
        'labels': torch.from_numpy(labels),
        'attention_mask': torch.from_numpy(mask),
        'pos': torch.tensor(items[0]['pos'], dtype=torch.long),
        'vecs': torch.from_numpy(items[0]['vecs']),
        'ctrl_pos': torch.tensor(items[0]['ctrl_pos'], dtype=torch.long),
        'ctrl_lab': torch.tensor(items[0]['ctrl_lab'], dtype=torch.long),
        'aux_pos': torch.tensor(items[0]['aux_pos'], dtype=torch.long),
        'aux_lab': torch.tensor(items[0]['aux_lab'], dtype=torch.long),
        'act_pos': torch.tensor([items[0].get('act_pos', 0)], dtype=torch.long),
        'act_lab': torch.tensor([items[0].get('act_lab', 1)], dtype=torch.long),
        'meta': items[0]['meta'],
    }