File size: 13,896 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
"""Causal Stage 1A training windows from stage1 examples.

Speech view: one <|prosody|> token per committed word / backchannel / pause; its
embedding is replaced by the projected, mean-pooled causal Mimi frames.

Text view: the clean last-user-turn transcript with zero prosody tokens, so the
frozen backbone sees exactly the native text path (retention replay).
"""
from __future__ import annotations

import json
import random
import zlib
from pathlib import Path

import numpy as np

PROSODY = '<|prosody|>'
IM_START = '<|im_start|>'
D_IN = 512


def ev_time(e):
    t = e['t']
    if t == 'user_word':
        return float(e['available_at'])
    if t in ('user_event', 'pause'):
        return float(e['end'])
    if t == 'user_turn_end':
        return float(e['at'])
    if t == 'assistant':
        return float(e.get('start', 0.0))
    if t == 'tool_result':
        return float(e['available_at'])
    return 0.0


class MimiStore:
    """Small LRU of memmapped per-session prosody features."""

    def __init__(self, root, max_open=96):
        self.root = Path(root)
        self.max_open = max_open
        self.cache = {}

    def get(self, cohort, sid):
        key = (cohort, sid)
        if key in self.cache:
            return self.cache[key]
        p = self.root / cohort / f'{sid}.npy'
        if not p.exists():
            return None
        arr = np.load(p, mmap_mode='r')
        if len(self.cache) >= self.max_open:
            self.cache.pop(next(iter(self.cache)))
        self.cache[key] = arr
        return arr


def pool(store, ex, pf):
    if not pf:
        return None
    arr = store.get(ex['cohort'], ex['session'])
    if arr is None:
        return None
    f0, f1 = int(pf[0]), int(pf[1])
    f0 = max(0, min(f0, arr.shape[1] - 1))
    f1 = max(f0 + 1, min(f1, arr.shape[1]))
    return np.asarray(arr[:, f0:f1], dtype=np.float32).mean(axis=1)


def build_messages(ex, store, view, prosody_mode='full'):
    """Returns (messages, prosody_vectors) or (None, error).

    prosody_mode (speech views only):
      full    markers + pooled causal Mimi vectors
      none    ASR words as plain text, no markers (ASR-only baseline)
      zero    markers kept, vectors zeroed (removes content and presence)
      shuffle markers kept, vectors permuted within the turn (keeps presence,
              destroys word-level timing/content alignment)
    """
    ul = ex.get('user_last')
    if not ul:
        return None, 'no_user_last'
    events = ex.get('events') or []
    vecs = []

    if view == 'text':
        content = (ul.get('text') or '').strip()
        if not content:
            return None, 'empty_text'
    else:
        words = []
        for e in events:
            if e['t'] not in ('user_word', 'user_event', 'pause'):
                continue
            tm = ev_time(e)
            if not (ul['start'] - 0.01 <= tm <= ul['end'] + 0.01):
                continue
            v = pool(store, ex, e.get('pf'))
            if v is None:
                continue
            words.append((e, v))
        if prosody_mode == 'shuffle' and len(words) > 1:
            rng = random.Random(zlib.crc32(str(ex.get('example_id', '')).encode()))
            vs = [v for _, v in words]
            rng.shuffle(vs)
            words = [(words[i][0], vs[i]) for i in range(len(words))]
        parts = []
        for e, v in words:
            if prosody_mode == 'none':
                if e['t'] == 'user_word':
                    parts.append(str(e.get('text') or ''))
            else:
                parts.append(PROSODY + str(e.get('text') or '')
                             if e['t'] == 'user_word' else PROSODY)
                vecs.append(np.zeros(D_IN, dtype=np.float32)
                            if prosody_mode == 'zero' else v)
        if not parts:
            return None, 'no_speech_events'
        content = ' '.join(parts)

    msgs = [{'role': 'system',
             'content': ex.get('system') or 'You are Aiden, a concise voice assistant.'}]
    if content:
        msgs.append({'role': 'user', 'content': content})

    # Tool flow that belongs to the target turn: assistant call(s), then results.
    tgt_start = float(ex['target']['start'])
    flow = []
    for e in events:
        if e['t'] == 'assistant':
            st = float(e.get('start', 0.0))
            if st >= ul['end'] - 0.6 and st < tgt_start - 1e-6:
                flow.append((st, 1, e))
    call_ids = {c['call_id'] for _, _, e in flow for c in (e.get('tool_calls') or [])}
    for e in events:
        if e['t'] == 'tool_result' and e.get('call_id') in call_ids \
                and float(e['available_at']) <= float(ex['context_cutoff']):
            flow.append((float(e['available_at']), 2, e))
    flow.sort(key=lambda x: (x[0], x[1]))
    for _, _, e in flow:
        if e['t'] == 'assistant':
            m = {'role': 'assistant', 'content': e.get('text', '')}
            calls = e.get('tool_calls') or []
            if calls:
                m['tool_calls'] = [{'type': 'function',
                                    'function': {'name': c['name'],
                                                 'arguments': c['arguments']}}
                                   for c in calls]
            msgs.append(m)
        else:
            msgs.append({'role': 'tool',
                         'content': json.dumps(e.get('payload'), ensure_ascii=False)})

    tgt = ex['target']
    tm = {'role': 'assistant', 'content': tgt.get('text', '')}
    if tgt.get('tool_calls'):
        tm['tool_calls'] = [{'type': 'function',
                             'function': {'name': c['name'], 'arguments': c['arguments']}}
                            for c in tgt['tool_calls']]
    msgs.append(tm)
    return (msgs, vecs), None


def finalize(msgs, vecs, ex, tok, pid, max_len, et, view, shuffle_vecs=False):
    tools = ex.get('tools') or None
    if shuffle_vecs and len(vecs) > 1:
        rng = random.Random(zlib.crc32(str(ex.get('example_id', '')).encode()))
        rng.shuffle(vecs)
    try:
        text = tok.apply_chat_template(msgs, tools=tools, tokenize=False,
                                       add_generation_prompt=False,
                                       enable_thinking=et)
    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
    # Defensive: skip an empty think block if the template still emitted one.
    if tok.decode(ids[cs:cs + 8]).lstrip().startswith('<think'):
        for k in range(1, 24):
            if '</think' in tok.decode(ids[cs:cs + k]):
                cs += k
                break
        while cs < len(ids) and not tok.decode(ids[cs:cs + 1]).strip():
            cs += 1

    labels = [-100] * len(ids)
    labels[cs:] = ids[cs:]
    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)}'
    mat = np.stack(vecs) if vecs else np.zeros((0, D_IN), dtype=np.float32)
    return {'ids': ids, 'labels': labels, 'pos': pos, 'vecs': mat,
            'meta': {'id': ex.get('example_id'), 'view': view,
                     'n_target': sum(1 for x in labels if x != -100)}}, None


def build_item(ex, tok, pid, store, max_len, view, enable_thinking=True, prosody_mode='full'):
    built, err = build_messages(ex, store, view, prosody_mode)
    if err:
        return None, err
    msgs, vecs = built
    return finalize(msgs, vecs, ex, tok, pid, max_len, enable_thinking, view,
                    shuffle_vecs=(prosody_mode == 'shuffle'))


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)
    pos, vecs, idx = [], [], []
    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
        for p, v in zip(it['pos'], it['vecs']):
            pos.append(p)
            vecs.append(v)
            idx.append(b)
    return {
        'input_ids': torch.from_numpy(input_ids),
        'labels': torch.from_numpy(labels),
        'attention_mask': torch.from_numpy(mask),
        'pos': torch.tensor(pos, dtype=torch.long),
        'vecs': torch.from_numpy(np.stack(vecs)) if vecs else torch.zeros((0, D_IN)),
        'item_idx': torch.tensor(idx, dtype=torch.long),
    }


class JsonlReader:
    def __init__(self, path):
        self.path = Path(path)
        self.fh = open(self.path, 'rb')
        self.offsets = []
        pos = 0
        for line in self.fh:
            self.offsets.append(pos)
            pos += len(line)
        self.fh.seek(0)

    def __len__(self):
        return len(self.offsets)

    def get(self, i):
        self.fh.seek(self.offsets[i])
        return json.loads(self.fh.readline())

    def close(self):
        self.fh.close()


class AnnTurns:
    """Cached per-session user turns from the structural annotation (for text view)."""

    def __init__(self, ann_root, max_open=64):
        self.root = Path(ann_root)
        self.max_open = max_open
        self.cache = {}

    def get(self, cohort, sid):
        key = (cohort, sid)
        if key in self.cache:
            return self.cache[key]
        p = self.root / cohort / f'{sid}.json'
        if not p.exists():
            return []
        d = json.loads(p.read_text())
        turns = [t for t in d.get('turns') or [] if t.get('role') == 'user']
        if len(self.cache) >= self.max_open:
            self.cache.pop(next(iter(self.cache)))
        self.cache[key] = turns
        return turns


def build_messages_history(ex, store, view, prosody_mode, user_turns):
    """Full-history variant: every user turn before the target, plus tool flow."""
    if not user_turns:
        return None, 'no_user_turns'
    cutoff = float(ex['context_cutoff'])
    tgt_start = float(ex['target']['start'])
    events = ex.get('events') or []

    uturns = [t for t in user_turns
              if float(t['start']) < tgt_start - 1e-6 and float(t['end']) <= cutoff + 0.5]
    items = [(float(t['start']), 0, 'user', t) for t in uturns]
    for e in events:
        if e['t'] == 'assistant':
            items.append((float(e.get('start', 0.0)), 1, 'assistant', e))
        elif e['t'] == 'tool_result':
            items.append((float(e['available_at']), 2, 'tool', e))
    items.sort(key=lambda x: (x[0], x[1]))

    msgs = [{'role': 'system',
             'content': ex.get('system') or 'You are Aiden, a concise voice assistant.'}]
    vecs = []
    for _, _, kind, obj in items:
        if kind == 'user':
            t = obj
            if view == 'text':
                content = (t.get('text') or '').strip()
                if content:
                    msgs.append({'role': 'user', 'content': content})
                continue
            parts = []
            for e in events:
                if e['t'] not in ('user_word', 'user_event', 'pause'):
                    continue
                et = ev_time(e)
                if not (float(t['start']) - 0.01 <= et <= float(t['end']) + 0.01):
                    continue
                v = pool(store, ex, e.get('pf'))
                if v is None:
                    continue
                if prosody_mode == 'none':
                    if e['t'] == 'user_word':
                        parts.append(str(e.get('text') or ''))
                    continue
                parts.append(PROSODY + str(e.get('text') or '')
                             if e['t'] == 'user_word' else PROSODY)
                vecs.append(np.zeros(D_IN, dtype=np.float32)
                            if prosody_mode == 'zero' else v)
            if parts:
                msgs.append({'role': 'user', 'content': ' '.join(parts)})
        elif kind == 'assistant':
            e = obj
            m = {'role': 'assistant', 'content': e.get('text', '')}
            calls = e.get('tool_calls') or []
            if calls:
                m['tool_calls'] = [{'type': 'function',
                                    'function': {'name': c['name'],
                                                 'arguments': c['arguments']}}
                                   for c in calls]
            msgs.append(m)
        else:
            e = obj
            msgs.append({'role': 'tool',
                         'content': json.dumps(e.get('payload'), ensure_ascii=False)})

    tgt = ex['target']
    tm = {'role': 'assistant', 'content': tgt.get('text', '')}
    if tgt.get('tool_calls'):
        tm['tool_calls'] = [{'type': 'function',
                             'function': {'name': c['name'], 'arguments': c['arguments']}}
                            for c in tgt['tool_calls']]
    msgs.append(tm)
    return (msgs, vecs), None


def build_item_history(ex, tok, pid, store, max_len, view, enable_thinking=True,
                       prosody_mode='full', user_turns=None):
    built, err = build_messages_history(ex, store, view, prosody_mode, user_turns or [])
    if err:
        return None, err
    msgs, vecs = built
    return finalize(msgs, vecs, ex, tok, pid, max_len, enable_thinking, view,
                    shuffle_vecs=(prosody_mode == 'shuffle'))