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_END = "" 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(" 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()}