davidheineman's picture
Publish coherent math-v1 datasets
7c0f087 verified
Raw History Blame Contribute Delete
5.87 kB
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