| """Hash-bound K2 data, schedules, and lockstep endpoint construction.""" |
|
|
| from __future__ import annotations |
|
|
| from dataclasses import dataclass |
| from typing import TYPE_CHECKING, Any |
|
|
| import numpy as np |
| import torch |
|
|
| from .constants import ( |
| DATA_META_SHA256, |
| EMBEDDING_SHA256, |
| SEEDS, |
| TRAIN_SHA256, |
| VAL_SHA256, |
| split_cell, |
| ) |
| from .io import file_record, json_file |
| from .teacher import teacher_endpoint |
|
|
| if TYPE_CHECKING: |
| from .config import FullConfig |
|
|
|
|
| @dataclass |
| class FrozenData: |
| train: np.ndarray |
| val: np.ndarray |
| embedding: torch.Tensor |
| records: dict[str, Any] |
|
|
|
|
| def load_frozen_data(config: "FullConfig", device: torch.device) -> FrozenData: |
| paths = { |
| "meta": config.artifact("data_meta"), |
| "train": config.artifact("train_data"), |
| "val": config.artifact("val_data"), |
| "embedding": config.artifact("embedding"), |
| } |
| records = { |
| "meta": file_record(paths["meta"], DATA_META_SHA256), |
| "train": file_record(paths["train"], TRAIN_SHA256), |
| "val": file_record(paths["val"], VAL_SHA256), |
| "embedding": file_record(paths["embedding"], EMBEDDING_SHA256), |
| } |
| meta = json_file(paths["meta"], DATA_META_SHA256) |
| expected_meta = { |
| "train_sequences": 3_125_000, |
| "seq_len": 64, |
| "vocab": 50_257, |
| "train_sha256": TRAIN_SHA256, |
| "val_sha256": VAL_SHA256, |
| } |
| errors = [ |
| f"meta.{key}: expected {wanted!r}, got {meta.get(key)!r}" |
| for key, wanted in expected_meta.items() if meta.get(key) != wanted |
| ] |
| train = np.load(paths["train"], mmap_mode="r", allow_pickle=False) |
| val = np.load(paths["val"], mmap_mode="r", allow_pickle=False) |
| embedding_np = np.load(paths["embedding"], mmap_mode="r", allow_pickle=False) |
| if train.shape != (3_125_000, 64) or train.dtype != np.dtype("uint16"): |
| errors.append(f"train must be uint16[3125000,64], got {train.dtype}{train.shape}") |
| if val.ndim != 2 or val.shape[0] < 20_480 or val.shape[1] != 64 or val.dtype != np.dtype("uint16"): |
| errors.append(f"val must be uint16[N>=20480,64], got {val.dtype}{val.shape}") |
| if embedding_np.shape != (50_257, 16) or embedding_np.dtype != np.dtype("float32"): |
| errors.append( |
| f"embedding must be float32[50257,16], got {embedding_np.dtype}{embedding_np.shape}" |
| ) |
| if errors: |
| raise ValueError("frozen K2 data contract mismatch:\n - " + "\n - ".join(errors)) |
| embedding = torch.from_numpy(np.asarray(embedding_np)).to(device=device, dtype=torch.float32) |
| records["meta_contents"] = meta |
| return FrozenData(train=train, val=val, embedding=embedding, records=records) |
|
|
|
|
| def load_schedule(config: "FullConfig", seed: int) -> tuple[np.ndarray, dict[str, Any]]: |
| if seed not in SEEDS: |
| raise ValueError(f"schedule seed must be one of {SEEDS}; got {seed}") |
| path = config.artifact("schedule", seed) |
| record = file_record(path) |
| schedule = np.load(path, mmap_mode="r", allow_pickle=False) |
| if schedule.shape != (30_000, 256) or schedule.dtype != np.dtype("<u4"): |
| raise ValueError( |
| f"schedule_{seed}.npy must be little-endian uint32[30000,256]; " |
| f"got {schedule.dtype}{schedule.shape}" |
| ) |
| if int(schedule.max()) >= 3_125_000: |
| raise ValueError(f"schedule_{seed}.npy contains an out-of-range training index") |
| return schedule, record |
|
|
|
|
| class StepStreams: |
| """Dedicated generators with the exact A6 seed map and one-call methods.""" |
|
|
| def __init__(self, seed: int, device: torch.device) -> None: |
| if seed not in SEEDS: |
| raise ValueError(f"training seed must be one of {SEEDS}; got {seed}") |
| generator_device = device.type if device.type == "cpu" else device |
| self.dequantization = torch.Generator(device=generator_device).manual_seed(seed + 1) |
| self.independent_endpoint = torch.Generator(device=generator_device).manual_seed(3000 + seed) |
| self.time = torch.Generator(device=generator_device).manual_seed(4000 + seed) |
| self.seed = seed |
| self.calls = {"dequantization": 0, "independent_endpoint": 0, "time": 0} |
|
|
| def dequantization_noise(self, shape: tuple[int, int, int], device: torch.device) -> torch.Tensor: |
| self.calls["dequantization"] += 1 |
| return torch.randn(shape, generator=self.dequantization, device=device, dtype=torch.float32) |
|
|
| def independent_noise(self, shape: tuple[int, int, int], device: torch.device) -> torch.Tensor: |
| self.calls["independent_endpoint"] += 1 |
| return torch.randn( |
| shape, generator=self.independent_endpoint, device=device, dtype=torch.float32 |
| ) |
|
|
| def times(self, batch: int, device: torch.device) -> torch.Tensor: |
| self.calls["time"] += 1 |
| return torch.rand( |
| (batch, 1, 1), generator=self.time, device=device, dtype=torch.float32 |
| ) |
|
|
|
|
| @dataclass |
| class TrainingBatch: |
| dataset_ids: torch.Tensor |
| token_ids: torch.Tensor |
| x: torch.Tensor |
| epsilon: torch.Tensor |
| t: torch.Tensor |
| z_t: torch.Tensor |
| target: torch.Tensor |
|
|
|
|
| def construct_training_batch( |
| *, frozen: FrozenData, schedule: np.ndarray, step: int, cell: str, |
| streams: StepStreams, device: torch.device, teacher=None, |
| teacher_event_pair: tuple[torch.cuda.Event, torch.cuda.Event] | None = None, |
| ) -> TrainingBatch: |
| coupling, _ = split_cell(cell) |
| if step < 0 or step >= 30_000: |
| raise IndexError(f"training step must be in [0,30000); got {step}") |
| dataset_ids_np = np.asarray(schedule[step], dtype=np.int64) |
| if dataset_ids_np.shape != (256,): |
| raise ValueError(f"schedule row must have shape [256]; got {dataset_ids_np.shape}") |
| token_ids_np = np.asarray(frozen.train[dataset_ids_np], dtype=np.int64) |
| dataset_ids = torch.from_numpy(dataset_ids_np.copy()).to(device=device) |
| token_ids = torch.from_numpy(token_ids_np).to(device=device) |
| shape = (256, 64, 16) |
| noise = streams.dequantization_noise(shape, device) |
| x = frozen.embedding[token_ids] + 0.05 * noise |
| t = streams.times(256, device) |
| if coupling == "independent": |
| epsilon = streams.independent_noise(shape, device) |
| else: |
| if teacher is None: |
| raise ValueError("triangular cell requires the seed-matched Stage-A teacher") |
| if teacher_event_pair is not None: |
| teacher_event_pair[0].record() |
| epsilon = teacher_endpoint(teacher, x) |
| if teacher_event_pair is not None: |
| teacher_event_pair[1].record() |
| z_t = (1.0 - t) * epsilon + t * x |
| target = x - epsilon |
| tensors = (x, epsilon, t, z_t, target) |
| if any(tensor.dtype != torch.float32 for tensor in tensors): |
| raise AssertionError("all endpoint/interpolation tensors must remain FP32") |
| return TrainingBatch(dataset_ids, token_ids, x, epsilon, t, z_t, target) |
|
|
|
|
| def make_eval_x(frozen: FrozenData, device: torch.device) -> torch.Tensor: |
| ids_np = np.asarray(frozen.val[10_240:20_480], dtype=np.int64) |
| ids = torch.from_numpy(ids_np).to(device=device) |
| generator_device = device.type if device.type == "cpu" else device |
| generator = torch.Generator(device=generator_device).manual_seed(12_345) |
| noise = torch.randn( |
| (10_240, 64, 16), generator=generator, device=device, dtype=torch.float32 |
| ) |
| return frozen.embedding[ids] + 0.05 * noise |
|
|
|
|
| def make_independent_eval_epsilon(seed: int, device: torch.device) -> torch.Tensor: |
| if seed not in SEEDS: |
| raise ValueError(f"evaluation seed must be one of {SEEDS}; got {seed}") |
| generator_device = device.type if device.type == "cpu" else device |
| generator = torch.Generator(device=generator_device).manual_seed(777 + seed) |
| return torch.randn( |
| (10_240, 64, 16), generator=generator, device=device, dtype=torch.float32 |
| ) |
|
|
|
|
| def make_triangular_eval_epsilon(teacher, eval_x: torch.Tensor, batch: int = 256) -> torch.Tensor: |
| if eval_x.shape != (10_240, 64, 16) or eval_x.dtype != torch.float32: |
| raise ValueError("eval_x must be FP32[10240,64,16]") |
| chunks = [ |
| teacher_endpoint(teacher, eval_x[start:start + batch]) |
| for start in range(0, 10_240, batch) |
| ] |
| return torch.cat(chunks, dim=0) |
|
|