File size: 10,618 Bytes
4ab04b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import hashlib
import json
import struct
import sys
from array import array
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable, Iterator, Sequence

import torch

from .constants import (
    CHAT_DATASET_ID,
    CHAT_DATASET_REVISION,
    COLLATED_SEQUENCE_LENGTH,
    CUTOFF_LENGTH,
    DEFAULT_DATASET_ID,
    DEFAULT_DATASET_REVISION,
    DEFAULT_MODEL_ID,
    DEFAULT_MODEL_REVISION,
    IGNORE_INDEX,
    PREPROCESS_TOKEN_ALIGNMENT,
    PREPROCESSED_MAX_LENGTH,
)

THINK_START = "<think>"
THINK_END = "</think>"
EMPTY_THINK = THINK_START + THINK_END


def infer_sequence_lengths(source_len: int, target_len: int, cutoff_len: int) -> tuple[int, int]:
    """Match the source/target truncation used for the released Uno checkpoint."""
    if target_len * 2 < cutoff_len:
        max_target_len = cutoff_len
    elif source_len * 2 < cutoff_len:
        max_target_len = cutoff_len - source_len
    else:
        max_target_len = int(cutoff_len * (target_len / (source_len + target_len)))
    new_target_len = min(max_target_len, target_len)
    new_source_len = min(max(cutoff_len - new_target_len, 0), source_len)
    return new_source_len, new_target_len


def _encode(tokenizer, text: str) -> list[int]:
    return list(tokenizer.encode(text, add_special_tokens=False))


def granite_assistant_content(content: str) -> str:
    # Matches Granite 4.2's template: answers without reasoning are rendered after an empty think block.
    content = content.strip()
    if THINK_START in content and THINK_END in content:
        return content
    return EMPTY_THINK + content


def normalize_messages(row: dict[str, Any]) -> list[dict[str, str]]:
    """OpenThoughts rows use ShareGPT `conversations`; tulu rows use `messages`."""
    if "conversations" in row and row["conversations"]:
        roles = {"human": "user", "gpt": "assistant", "system": "system"}
        return [{"role": roles[turn["from"]], "content": str(turn.get("value", ""))} for turn in row["conversations"]]
    return [{"role": turn["role"], "content": str(turn.get("content", ""))} for turn in row["messages"]]


def encode_granite_conversation(
    messages: Sequence[dict[str, str]],
    tokenizer,
    *,
    cutoff_length: int = CUTOFF_LENGTH,
    token_alignment: int = PREPROCESS_TOKEN_ALIGNMENT,
) -> dict[str, list[int]]:
    """Encode user/assistant pairs in Granite 4.2's chat format; only assistant turns are supervised."""
    effective_cutoff = cutoff_length - cutoff_length % token_alignment
    system = ""
    if messages and messages[0]["role"] == "system":
        system = messages[0]["content"]
        messages = messages[1:]
    if not messages or len(messages) % 2:
        raise ValueError("Conversations must contain complete user/assistant pairs.")

    input_ids: list[int] = []
    labels: list[int] = []
    total_length = 0
    for index in range(0, len(messages), 2):
        user, assistant = messages[index], messages[index + 1]
        if user["role"] != "user" or assistant["role"] != "assistant":
            raise ValueError("Conversations must alternate user and assistant turns.")
        source_text = (
            ("<|im_start|>system\n" + system + "<|im_end|>\n" if index == 0 else "")
            + "<|im_start|>user\n"
            + user["content"]
            + "<|im_end|>\n<|im_start|>assistant\n"
        )
        target_text = granite_assistant_content(assistant["content"]) + "<|im_end|>\n"
        source_ids = _encode(tokenizer, source_text)
        target_ids = _encode(tokenizer, target_text)
        if total_length >= effective_cutoff:
            break
        source_len, target_len = infer_sequence_lengths(
            len(source_ids), len(target_ids), effective_cutoff - total_length
        )
        input_ids.extend(source_ids[:source_len])
        input_ids.extend(target_ids[:target_len])
        labels.extend([IGNORE_INDEX] * source_len)
        labels.extend(target_ids[:target_len])
        total_length += source_len + target_len

    if not input_ids:
        raise ValueError("Conversation produced no tokens.")
    pad_token_id = tokenizer.pad_token_id
    if pad_token_id is None:
        raise ValueError("The tokenizer must define pad_token_id.")
    pad_len = (-len(input_ids)) % token_alignment
    # The released recipe treats alignment padding as supervised data.
    input_ids.extend([pad_token_id] * pad_len)
    labels.extend([pad_token_id] * pad_len)
    return {"input_ids": input_ids, "labels": labels}


def plan_packing(lengths: Sequence[int], max_length: int = PREPROCESSED_MAX_LENGTH) -> list[list[int]]:
    """Greedy, order-preserving packing of example indices into rows of at most max_length tokens."""
    groups: list[list[int]] = []
    current: list[int] = []
    used = 0
    for index, length in enumerate(lengths):
        if length > max_length:
            raise ValueError(f"Example of length {length} exceeds {max_length}.")
        if current and used + length > max_length:
            groups.append(current)
            current, used = [], 0
        current.append(index)
        used += length
    if current:
        groups.append(current)
    return groups


def pack_group(examples: Iterable[dict[str, list[int]]]) -> dict[str, list[int]]:
    """Position ids restart per example so SDAR's layout keeps packed samples separate."""
    row = {"input_ids": [], "labels": [], "position_ids": []}
    for example in examples:
        row["input_ids"].extend(example["input_ids"])
        row["labels"].extend(example["labels"])
        row["position_ids"].extend(range(len(example["input_ids"])))
    return row


def _int32_bytes(values: Sequence[int]) -> bytes:
    encoded = array("i", values)
    if encoded.itemsize != 4:
        raise RuntimeError("Dataset hashing requires a 32-bit C integer type.")
    if sys.byteorder != "little":
        encoded.byteswap()
    return encoded.tobytes()


def content_hash_rows(rows: Iterable[dict[str, Sequence[int]]]) -> dict[str, int | str]:
    """Hash row boundaries, input IDs, and labels in source order."""
    digest = hashlib.sha256()
    row_count = 0
    token_count = 0
    supervised_count = 0
    for row in rows:
        input_ids = row["input_ids"]
        labels = row["labels"]
        if len(input_ids) != len(labels):
            raise ValueError(f"Row {row_count} has mismatched input and label lengths.")
        digest.update(struct.pack("<Q", len(input_ids)))
        digest.update(_int32_bytes(input_ids))
        digest.update(_int32_bytes(labels))
        row_count += 1
        token_count += len(input_ids)
        supervised_count += sum(label != IGNORE_INDEX for label in labels)
    return {
        "algorithm": "sha256-rowlen-u64le-input-i32le-label-i32le-v1",
        "content_sha256": digest.hexdigest(),
        "row_count": row_count,
        "token_count": token_count,
        "supervised_token_count": supervised_count,
    }


def iter_hf_dataset(dataset, batch_size: int = 256) -> Iterator[dict[str, Sequence[int]]]:
    for batch in dataset.iter(batch_size=batch_size):
        for input_ids, labels in zip(batch["input_ids"], batch["labels"]):
            yield {"input_ids": input_ids, "labels": labels}


def hash_hf_dataset(dataset) -> dict[str, int | str]:
    return content_hash_rows(iter_hf_dataset(dataset))


def read_dataset_manifest(dataset_path: str | Path) -> dict[str, Any]:
    manifest_path = Path(dataset_path) / "uno_dataset_manifest.json"
    if not manifest_path.is_file():
        raise FileNotFoundError(
            f"Prepared dataset manifest not found: {manifest_path}. Run `python -m training.prepare_mix` first."
        )
    return json.loads(manifest_path.read_text())


def validate_dataset_manifest(manifest: dict[str, Any]) -> None:
    sources = {(s.get("dataset_id"), s.get("revision")) for s in manifest.get("sources", [])}
    expected = {(DEFAULT_DATASET_ID, DEFAULT_DATASET_REVISION), (CHAT_DATASET_ID, CHAT_DATASET_REVISION)}
    if sources != expected:
        raise ValueError(f"Dataset manifest sources {sorted(sources)} differ from the pinned mix.")
    tokenizer = manifest.get("tokenizer", {})
    if (tokenizer.get("model_id"), tokenizer.get("revision")) != (DEFAULT_MODEL_ID, DEFAULT_MODEL_REVISION):
        raise ValueError("Dataset manifest does not use the pinned Granite tokenizer revision.")
    preprocessing = manifest.get("preprocessing", {})
    if preprocessing.get("cutoff_length") != CUTOFF_LENGTH:
        raise ValueError("Dataset cutoff does not match the Uno training recipe.")
    if preprocessing.get("token_alignment") != PREPROCESS_TOKEN_ALIGNMENT:
        raise ValueError("Dataset token alignment must be 3.")
    if preprocessing.get("max_preprocessed_length") != PREPROCESSED_MAX_LENGTH:
        raise ValueError("Dataset maximum row length must be 4095.")
    if manifest.get("hash", {}).get("row_count", 0) <= 0:
        raise ValueError("Dataset manifest has no hashed rows.")


@dataclass
class UnoDataCollator:
    tokenizer: Any
    sequence_length: int = COLLATED_SEQUENCE_LENGTH

    def __post_init__(self) -> None:
        if self.tokenizer.padding_side != "right":
            raise ValueError("Uno training requires right padding.")
        if self.tokenizer.pad_token_id is None:
            raise ValueError("Uno training requires a tokenizer pad token.")

    def __call__(self, features: list[dict[str, Sequence[int]]]) -> dict[str, torch.Tensor]:
        if not features:
            raise ValueError("Cannot collate an empty batch.")
        result = {"input_ids": [], "labels": [], "position_ids": []}
        for feature in features:
            length = len(feature["input_ids"])
            if length > self.sequence_length:
                raise ValueError(f"Prepared row length {length} exceeds sequence length {self.sequence_length}.")
            if len(feature["labels"]) != length:
                raise ValueError("Prepared input IDs and labels must have equal lengths.")
            pad_len = self.sequence_length - length
            positions = list(feature.get("position_ids") or range(length))
            result["input_ids"].append(list(feature["input_ids"]) + [self.tokenizer.pad_token_id] * pad_len)
            result["labels"].append(list(feature["labels"]) + [IGNORE_INDEX] * pad_len)
            # Zero positions mark padding; modify_padded_position_ids_2d renumbers it as its own segment.
            result["position_ids"].append(positions + [0] * pad_len)
        return {key: torch.tensor(value, dtype=torch.long) for key, value in result.items()}