File size: 5,869 Bytes
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec86d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4318522
 
 
 
ec86d11
4318522
 
 
 
 
ec86d11
4318522
 
 
 
ec86d11
 
 
 
 
4318522
 
 
 
ec86d11
 
4318522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c0f087
 
4318522
 
 
 
 
 
 
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
from bisect import bisect_left, bisect_right
from dataclasses import dataclass
from pathlib import Path
import re

import numpy as np
import torch

from refined_v4.train import TokenCorpus
from refined_v4.train_policy import Example, replay as ordinary_replay
from refined_v4.study import write
from .envs import ENC


@dataclass
class WeightedExample(Example):
    weights: list[float]


def context_examples(corpus, start: int, count: int, weighted: bool):
    if not 0 <= start < corpus.tokens or start + count > corpus.tokens or count < 1:
        raise ValueError('SFT slice exceeds the declared budget')
    result = []
    remaining = count
    index = bisect_right(corpus.ends, start)
    while remaining:
        beginning = corpus.ends[index - 1] if index else 0
        offset = start - beginning
        size = min(remaining, corpus.ends[index] - start)
        sequence = corpus.documents[index][:offset + size + 1].astype(np.int64).tolist()
        mask = [0] * (offset + 1) + [1] * size
        if weighted:
            result.append(WeightedExample(sequence, mask, corpus.weights[index][:len(sequence)].tolist()))
        else:
            result.append(Example(sequence, mask))
        start += size
        remaining -= size
        index += 1
    return result


class ContextCorpus(TokenCorpus):
    def take(self, start: int, count: int):
        return context_examples(self, start, count, False)


def answer_weights(ids: list[int], factor: float):
    text = ENC.decode(ids[:-1] if ids[-1] == ENC.eot_token else ids)
    sizes = [len(ENC.decode_single_token_bytes(token)) for token in ids]
    ends = np.cumsum(sizes).tolist()
    starts = [0] + ends[:-1]
    weights = np.ones(len(ids), dtype=np.float32)
    for match in re.finditer(r'(?m)^(?:Answer: |So, the answer is )[^\n]+', text):
        line = match.group()
        answer = line.rsplit(' = ', 1)[-1] if ' = ' in line else line.removeprefix('Answer: ')
        if re.fullmatch(r'[+-]?\d+(?:[./]\d+)?', answer.strip()) is None:
            continue
        start = len(text[:match.end() - len(answer)].encode())
        end = len(text[:match.end()].encode())
        weights[bisect_right(ends, start):bisect_left(starts, end)] = factor
    return weights


def assistant_roles(ids: list[int]):
    text = ENC.decode(ids[:-1] if ids[-1] == ENC.eot_token else ids)
    ends = np.cumsum([len(ENC.decode_single_token_bytes(token)) for token in ids]).tolist()
    starts = [0] + ends[:-1]
    questions = [match.start() for match in re.finditer(r'(?m)^Question:', text)]
    roles = np.zeros(len(ids), dtype=bool)
    for match in re.finditer(r'(?m)^(?:Reasoning:|Answer:)', text):
        following = bisect_right(questions, match.start())
        end = questions[following] if following < len(questions) else len(text)
        first_byte = len(text[:match.start()].encode())
        last_byte = len(text[:end].encode())
        roles[bisect_right(ends, first_byte):bisect_left(starts, last_byte)] = True
    if ids[-1] == ENC.eot_token:
        roles[-1] = True
    return roles


class AnswerCorpus(TokenCorpus):
    answer_weight: float = 32.
    report_path: str = ''
    preserve_context: bool = False
    question_weight: float = 1.

    def __init__(self, path: Path, budget: int):
        super().__init__(path, budget)
        self.weights = []
        answer_tokens = 0
        question_tokens = 0
        previous = 0
        for ids, end in zip(self.documents, self.ends, strict=True):
            count = end - previous
            previous = end
            tokens = ids.tolist()
            roles = assistant_roles(tokens)
            question_tokens += int((~roles[1:count + 1]).sum())
            weights = answer_weights(tokens, self.answer_weight) * np.where(roles, 1., self.question_weight)
            answer_tokens += int((answer_weights(tokens, 2.)[1:count + 1] > 1).sum())
            weights *= count / float(weights[1:count + 1].sum())
            self.weights.append(weights)
        if self.report_path:
            write(Path(self.report_path), dict(prediction_tokens=budget, answer_tokens=answer_tokens,
                question_tokens=question_tokens, question_weight=self.question_weight,
                answer_weight=self.answer_weight, objective='Every prediction remains supervised; weight Question and final numeric answer tokens explicitly, normalized to mean one per document.'))

    def take(self, start: int, count: int):
        if self.preserve_context:
            return context_examples(self, start, count, True)
        if not 0 <= start < self.tokens or start + count > self.tokens or count < 1:
            raise ValueError('SFT slice exceeds the declared budget')
        result = []
        remaining = count
        index = bisect_right(self.ends, start)
        while remaining:
            beginning = self.ends[index - 1] if index else 0
            offset = start - beginning
            size = min(remaining, self.ends[index] - start)
            sequence = self.documents[index][offset:offset + size + 1].astype(np.int64).tolist()
            weights = self.weights[index][offset:offset + size + 1].tolist()
            result.append(WeightedExample(sequence, [0] + [1] * size, weights))
            start += size
            remaining -= size
            index += 1
        return result


def replay(model, examples: list[Example], amp: bool = False):
    probabilities, count = ordinary_replay(model, examples, amp)
    if not count:
        return probabilities,count
    result = []
    for row, values in zip(examples, probabilities, strict=True):
        if isinstance(row, WeightedExample):
            weights = [row.weights[index] for index in range(1, len(row.sequence)) if row.mask[index]]
            values = values * torch.tensor(weights, device=values.device)
        result.append(values)
    return result, count