Download training_artifacts/sft_data.py from MercanAI/final_sft_corrected: direct link, hf CLI and curl.
- Browser
- Download file 24.2 kB
-
https://huggingface.co/datasets/MercanAI/final_sft_corrected/resolve/main/training_artifacts/sft_data.py
- Command line
-
hf download hf://datasets/MercanAI/final_sft_corrected/training_artifacts/sft_data.py
-
curl -L -o sft_data.py https://huggingface.co/datasets/MercanAI/final_sft_corrected/resolve/main/training_artifacts/sft_data.py
24.2 kB
| """Adaptive packed assistant-only SFT reader for the pretokenized Turkish corpus. | |
| The packing plan covers every trainable assistant-body target from every non-tool | |
| conversation exactly once. Samples preferentially start at full document | |
| boundaries. When a conversation is longer than the model context, continuation | |
| samples start at the earliest message/turn boundary that still reaches the next | |
| uncovered target. Overlapped prefix targets are masked, so overlap supplies | |
| context without duplicating optimization targets. | |
| Tool-bearing conversations are excluded completely. Short safe runs are padded | |
| after their structural EOS with token id 0; the EOS creates a hard attention | |
| boundary before padding and all padding labels remain masked. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Iterator, Optional | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import DataLoader, IterableDataset, get_worker_info | |
| HEADER_BYTES = 96 | |
| TOKEN_DTYPE = np.dtype("<u2") | |
| SEG_DTYPE = np.dtype([ | |
| ("token_offset", "<u8"), ("header_tokens", "<u2"), ("body_tokens", "<u4"), | |
| ("role_id", "u1"), ("flags", "u1"), | |
| ]) | |
| IDX_DTYPE = np.dtype([ | |
| ("doc_key", "<u8"), ("token_offset", "<u8"), ("token_count", "<u4"), | |
| ("text_utf8_bytes", "<u4"), ("source_id", "u1"), ("category_id", "u1"), | |
| ("flags", "<u2"), ("segment_count", "<u4"), | |
| ]) | |
| ASSISTANT_ROLE_ID = 2 | |
| TOOL_ROLE_ID = 3 | |
| TRAINABLE_FLAG = 1 | |
| EOS_ID = 2 | |
| PAD_FILL_ID = 0 | |
| class SFTShard: | |
| token_path: Path | |
| segment_path: Path | |
| index_path: Path | |
| token_count: int | |
| sample_starts: np.ndarray | |
| sample_valid_lens: np.ndarray | |
| sample_target_lefts: np.ndarray | |
| sample_target_counts: np.ndarray | |
| samples_before_zero_filter: int | |
| tool_segments: int | |
| tool_documents: int | |
| tool_document_tokens: int | |
| zero_target_windows: int | |
| document_aligned_samples: int | |
| turn_aligned_continuations: int | |
| assistant_aligned_continuations: int | |
| hard_continuations: int | |
| padded_samples: int | |
| padded_tokens: int | |
| assistant_target_tokens: int | |
| valid_context_tokens: int | |
| def windows(self) -> int: | |
| return int(self.sample_starts.size) | |
| def _interval_sum( | |
| body_starts: np.ndarray, | |
| body_ends: np.ndarray, | |
| lefts: np.ndarray, | |
| rights: np.ndarray, | |
| ) -> np.ndarray: | |
| """Assistant-body token count in half-open [left, right) intervals.""" | |
| if body_starts.size == 0 or lefts.size == 0: | |
| return np.zeros(lefts.size, dtype=np.int64) | |
| lens = body_ends - body_starts | |
| prefix = np.empty(body_starts.size + 1, dtype=np.int64) | |
| prefix[0] = 0 | |
| np.cumsum(lens, out=prefix[1:]) | |
| first = np.searchsorted(body_ends, lefts, side="right") | |
| last_excl = np.searchsorted(body_starts, rights, side="left") | |
| out = np.zeros(lefts.size, dtype=np.int64) | |
| ok = first < last_excl | |
| if np.any(ok): | |
| ii = first[ok] | |
| jj = last_excl[ok] | |
| ll = lefts[ok] | |
| rr = rights[ok] | |
| value = prefix[jj] - prefix[ii] | |
| value -= np.maximum(0, ll - body_starts[ii]) | |
| tail = jj - 1 | |
| value -= np.maximum(0, body_ends[tail] - rr) | |
| out[ok] = value | |
| return out | |
| def _build_adaptive_plan( | |
| segment_path: Path, | |
| index_path: Path, | |
| seq_len: int, | |
| ) -> dict[str, object]: | |
| """Build exact-once target ranges with document/turn-aligned context.""" | |
| idx = np.memmap(index_path, dtype=IDX_DTYPE, mode="r", offset=HEADER_BYTES) | |
| seg = np.memmap(segment_path, dtype=SEG_DTYPE, mode="r", offset=HEADER_BYTES) | |
| roles = np.asarray(seg["role_id"]) | |
| flags = np.asarray(seg["flags"]) | |
| bad_train = ((flags & TRAINABLE_FLAG) != 0) & (roles != ASSISTANT_ROLE_ID) | |
| if np.any(bad_train): | |
| raise RuntimeError( | |
| f"non-assistant trainable segments in {segment_path.name}: " | |
| f"{int(np.count_nonzero(bad_train))}" | |
| ) | |
| assistant_untrainable = (roles == ASSISTANT_ROLE_ID) & ((flags & TRAINABLE_FLAG) == 0) | |
| if np.any(assistant_untrainable): | |
| raise RuntimeError( | |
| f"assistant segments without trainable flag in {segment_path.name}: " | |
| f"{int(np.count_nonzero(assistant_untrainable))}" | |
| ) | |
| doc_starts = np.asarray(idx["token_offset"], dtype=np.int64) | |
| doc_counts = np.asarray(idx["token_count"], dtype=np.int64) | |
| doc_ends = doc_starts + doc_counts | |
| seg_counts = np.asarray(idx["segment_count"], dtype=np.int64) | |
| cumulative = np.cumsum(seg_counts, dtype=np.int64) | |
| tool_idx = np.flatnonzero(roles == TOOL_ROLE_ID) | |
| tool_segments = int(tool_idx.size) | |
| if tool_idx.size: | |
| tool_docs = np.unique(np.searchsorted(cumulative, tool_idx, side="right")) | |
| if np.any(tool_docs >= len(idx)): | |
| raise RuntimeError(f"segment/index alignment failure in {index_path.name}") | |
| else: | |
| tool_docs = np.empty(0, dtype=np.int64) | |
| is_tool = np.zeros(len(idx), dtype=np.bool_) | |
| is_tool[tool_docs] = True | |
| tool_document_tokens = int(doc_counts[tool_docs].sum()) if tool_docs.size else 0 | |
| assistant_idx = np.flatnonzero( | |
| (roles == ASSISTANT_ROLE_ID) & ((flags & TRAINABLE_FLAG) != 0) | |
| ) | |
| if assistant_idx.size: | |
| assistant_docs = np.searchsorted(cumulative, assistant_idx, side="right") | |
| safe_assistant_idx = assistant_idx[~is_tool[assistant_docs]] | |
| body_starts = ( | |
| np.asarray(seg["token_offset"][safe_assistant_idx], dtype=np.int64) | |
| + np.asarray(seg["header_tokens"][safe_assistant_idx], dtype=np.int64) | |
| ) | |
| body_ends = body_starts + np.asarray( | |
| seg["body_tokens"][safe_assistant_idx], dtype=np.int64 | |
| ) | |
| expected_targets = int( | |
| np.asarray(seg["body_tokens"][safe_assistant_idx], dtype=np.int64).sum() | |
| ) | |
| else: | |
| body_starts = np.empty(0, dtype=np.int64) | |
| body_ends = np.empty(0, dtype=np.int64) | |
| expected_targets = 0 | |
| starts: list[int] = [] | |
| lefts: list[int] = [] | |
| rights: list[int] = [] | |
| valid_lens: list[int] = [] | |
| # 0=document start, 1=user/system turn start, 2=assistant-message start, | |
| # 3=hard token fallback (must remain zero for the verified corpus). | |
| kinds: list[int] = [] | |
| safe_docs = np.flatnonzero(~is_tool) | |
| if safe_docs.size: | |
| cuts = np.flatnonzero(np.diff(safe_docs) > 1) | |
| run_starts = np.r_[0, cuts + 1] | |
| run_ends = np.r_[cuts + 1, safe_docs.size] | |
| for run_a, run_b in zip(run_starts.tolist(), run_ends.tolist()): | |
| first_doc = int(safe_docs[run_a]) | |
| last_doc = int(safe_docs[run_b - 1]) | |
| run_start = int(doc_starts[first_doc]) | |
| run_end = int(doc_ends[last_doc]) | |
| # Raw token position of the first not-yet-covered next-token label. | |
| cursor = run_start + 1 | |
| while cursor < run_end: | |
| doc_id = int(np.searchsorted(doc_ends, cursor, side="right")) | |
| if doc_id > last_doc: | |
| doc_id = last_doc | |
| doc_start = int(doc_starts[doc_id]) | |
| if cursor - doc_start <= seq_len: | |
| start = doc_start | |
| kind = 0 | |
| else: | |
| seg_lo = 0 if doc_id == 0 else int(cumulative[doc_id - 1]) | |
| seg_hi = int(cumulative[doc_id]) | |
| offsets = np.asarray(seg["token_offset"][seg_lo:seg_hi], dtype=np.int64) | |
| doc_roles = np.asarray(seg["role_id"][seg_lo:seg_hi], dtype=np.int64) | |
| threshold = cursor - seq_len | |
| eligible = (offsets >= threshold) & (offsets <= cursor - 1) | |
| # Prefer the most recent user/system boundary that still | |
| # leaves the next uncovered target inside the 8K context. | |
| # This preserves a semantically useful prompt/turn anchor | |
| # whenever one is representable without dropping targets. | |
| preferred = np.flatnonzero( | |
| eligible & ((doc_roles == 1) | (doc_roles == 0)) | |
| ) | |
| if preferred.size: | |
| j = int(preferred[-1]) | |
| start = int(offsets[j]) | |
| kind = 1 | |
| else: | |
| # Some very long assistant messages extend beyond an 8K | |
| # prompt+response window. In that case exact-once target | |
| # coverage is only possible by continuing from the | |
| # assistant message boundary and using its long prefix as | |
| # context. This mirrors finite-context autoregressive LM | |
| # training and is tracked explicitly rather than being | |
| # mislabeled as a user-turn continuation. | |
| message = np.flatnonzero(eligible) | |
| if message.size: | |
| j = int(message[0]) | |
| start = int(offsets[j]) | |
| kind = 2 | |
| else: | |
| # With max single-segment length < seq_len this path | |
| # must stay unused; keep it fail-visible in stats. | |
| start = cursor - 1 | |
| kind = 3 | |
| target_end = min(start + seq_len, run_end - 1) | |
| if target_end < cursor: | |
| raise RuntimeError( | |
| f"adaptive plan failed to advance in {index_path.name}: " | |
| f"cursor={cursor} start={start} target_end={target_end}" | |
| ) | |
| valid_end = min(start + seq_len + 1, run_end) | |
| starts.append(start) | |
| lefts.append(cursor) | |
| rights.append(target_end + 1) | |
| valid_lens.append(valid_end - start) | |
| kinds.append(kind) | |
| cursor = target_end + 1 | |
| sample_starts = np.asarray(starts, dtype=np.int64) | |
| target_lefts = np.asarray(lefts, dtype=np.int64) | |
| target_rights = np.asarray(rights, dtype=np.int64) | |
| sample_valid_lens = np.asarray(valid_lens, dtype=np.int32) | |
| kinds_arr = np.asarray(kinds, dtype=np.int8) | |
| target_counts = _interval_sum(body_starts, body_ends, target_lefts, target_rights) | |
| samples_before_zero_filter = int(sample_starts.size) | |
| keep = target_counts > 0 | |
| zero_target_windows = int(np.count_nonzero(~keep)) | |
| sample_starts = sample_starts[keep] | |
| target_lefts = target_lefts[keep] | |
| sample_valid_lens = sample_valid_lens[keep] | |
| target_counts = target_counts[keep] | |
| kinds_arr = kinds_arr[keep] | |
| assistant_target_tokens = int(target_counts.sum()) | |
| if assistant_target_tokens != expected_targets: | |
| raise RuntimeError( | |
| f"adaptive packing target coverage mismatch in {index_path.name}: " | |
| f"plan={assistant_target_tokens} expected={expected_targets}" | |
| ) | |
| assistant_aligned_continuations = int(np.count_nonzero(kinds_arr == 2)) | |
| hard_continuations = int(np.count_nonzero(kinds_arr == 3)) | |
| if hard_continuations: | |
| raise RuntimeError( | |
| f"adaptive packing required {hard_continuations} hard continuations in " | |
| f"{index_path.name}; verified corpus should permit turn-aligned continuation" | |
| ) | |
| padded = sample_valid_lens < (seq_len + 1) | |
| padded_samples = int(np.count_nonzero(padded)) | |
| padded_tokens = int((seq_len + 1 - sample_valid_lens[padded]).sum()) if padded_samples else 0 | |
| valid_context_tokens = int(np.minimum(sample_valid_lens - 1, seq_len).sum()) | |
| del idx, seg | |
| return { | |
| "sample_starts": sample_starts, | |
| "sample_valid_lens": sample_valid_lens, | |
| "sample_target_lefts": target_lefts, | |
| "sample_target_counts": target_counts.astype(np.int64, copy=False), | |
| "samples_before_zero_filter": samples_before_zero_filter, | |
| "tool_segments": tool_segments, | |
| "tool_documents": int(tool_docs.size), | |
| "tool_document_tokens": tool_document_tokens, | |
| "zero_target_windows": zero_target_windows, | |
| "document_aligned_samples": int(np.count_nonzero(kinds_arr == 0)), | |
| "turn_aligned_continuations": int(np.count_nonzero(kinds_arr == 1)), | |
| "assistant_aligned_continuations": assistant_aligned_continuations, | |
| "hard_continuations": hard_continuations, | |
| "padded_samples": padded_samples, | |
| "padded_tokens": padded_tokens, | |
| "assistant_target_tokens": assistant_target_tokens, | |
| "valid_context_tokens": valid_context_tokens, | |
| } | |
| def discover_sft_shards(data_dir: str | Path, seq_len: int) -> list[SFTShard]: | |
| root = Path(data_dir) / "shards" | |
| token_files = sorted(root.glob("part-*-sft.tokens.bin")) | |
| if not token_files: | |
| raise FileNotFoundError(f"no SFT token shards under {root}") | |
| shards: list[SFTShard] = [] | |
| for token_path in token_files: | |
| stem = token_path.name.replace(".tokens.bin", "") | |
| segment_path = token_path.with_name(stem + ".segments.bin") | |
| index_path = token_path.with_name(stem + ".index.bin") | |
| if not segment_path.exists() or not index_path.exists(): | |
| raise FileNotFoundError(f"missing aligned SFT files for {stem}") | |
| payload = token_path.stat().st_size - HEADER_BYTES | |
| if payload <= 0 or payload % TOKEN_DTYPE.itemsize: | |
| raise ValueError(f"bad token payload size: {token_path}") | |
| token_count = payload // TOKEN_DTYPE.itemsize | |
| plan = _build_adaptive_plan(segment_path, index_path, seq_len) | |
| if int(np.asarray(plan["sample_starts"]).size) == 0: | |
| continue | |
| shards.append( | |
| SFTShard( | |
| token_path=token_path, | |
| segment_path=segment_path, | |
| index_path=index_path, | |
| token_count=token_count, | |
| **plan, | |
| ) | |
| ) | |
| if not shards: | |
| raise RuntimeError("SFT corpus has no usable training samples") | |
| return shards | |
| def corpus_stats(shards: list[SFTShard], seq_len: int) -> dict[str, int | float]: | |
| raw_tokens = sum(s.token_count for s in shards) | |
| windows = sum(s.windows for s in shards) | |
| model_context_tokens = windows * seq_len | |
| valid_context_tokens = sum(s.valid_context_tokens for s in shards) | |
| assistant_target_tokens = sum(s.assistant_target_tokens for s in shards) | |
| return { | |
| "shards": len(shards), | |
| "raw_tokens": raw_tokens, | |
| "windows": windows, | |
| "samples_before_zero_filter": sum(s.samples_before_zero_filter for s in shards), | |
| "filtered_zero_target_windows": sum(s.zero_target_windows for s in shards), | |
| "tool_segments": sum(s.tool_segments for s in shards), | |
| "tool_documents": sum(s.tool_documents for s in shards), | |
| "tool_document_tokens": sum(s.tool_document_tokens for s in shards), | |
| "document_aligned_samples": sum(s.document_aligned_samples for s in shards), | |
| "turn_aligned_continuations": sum(s.turn_aligned_continuations for s in shards), | |
| "assistant_aligned_continuations": sum( | |
| s.assistant_aligned_continuations for s in shards | |
| ), | |
| "hard_continuations": sum(s.hard_continuations for s in shards), | |
| "padded_samples": sum(s.padded_samples for s in shards), | |
| "padded_tokens": sum(s.padded_tokens for s in shards), | |
| "assistant_target_tokens": assistant_target_tokens, | |
| "packed_context_tokens": model_context_tokens, | |
| "valid_context_tokens": valid_context_tokens, | |
| # Backward-compatible key used by trainer logging. With adaptive | |
| # overlap this is model-context/raw and can legitimately exceed 1.0. | |
| "coverage": model_context_tokens / max(1, raw_tokens), | |
| "valid_context_ratio": valid_context_tokens / max(1, model_context_tokens), | |
| "assistant_target_ratio": assistant_target_tokens / max(1, model_context_tokens), | |
| } | |
| def validate_roles(shards: list[SFTShard]) -> dict[str, int]: | |
| role_counts: dict[int, int] = {} | |
| trainable_counts: dict[int, int] = {} | |
| for shard in shards: | |
| seg = np.memmap(shard.segment_path, dtype=SEG_DTYPE, mode="r", offset=HEADER_BYTES) | |
| roles = np.asarray(seg["role_id"]) | |
| flags = np.asarray(seg["flags"]) | |
| for role in np.unique(roles).tolist(): | |
| role = int(role) | |
| mask = roles == role | |
| role_counts[role] = role_counts.get(role, 0) + int(np.count_nonzero(mask)) | |
| tr = mask & ((flags & TRAINABLE_FLAG) != 0) | |
| trainable_counts[role] = trainable_counts.get(role, 0) + int(np.count_nonzero(tr)) | |
| del seg | |
| nonassistant_trainable = sum( | |
| v for role, v in trainable_counts.items() if role != ASSISTANT_ROLE_ID | |
| ) | |
| if nonassistant_trainable: | |
| raise RuntimeError(f"non-assistant trainable segments detected: {nonassistant_trainable}") | |
| return { | |
| "tool_segments_found_and_filtered": role_counts.get(TOOL_ROLE_ID, 0), | |
| "tool_documents_filtered": sum(s.tool_documents for s in shards), | |
| "assistant_segments": role_counts.get(ASSISTANT_ROLE_ID, 0), | |
| "user_segments": role_counts.get(1, 0), | |
| "system_segments": role_counts.get(0, 0), | |
| "nonassistant_trainable": nonassistant_trainable, | |
| } | |
| class PackedSFTStream(IterableDataset): | |
| def __init__( | |
| self, | |
| shards: list[SFTShard], | |
| seq_len: int, | |
| rank: int, | |
| world_size: int, | |
| num_workers: int, | |
| seed: int, | |
| resume_state: Optional[dict[int, list[int]]] = None, | |
| ) -> None: | |
| super().__init__() | |
| self.shards = shards | |
| self.seq_len = seq_len | |
| self.window = seq_len + 1 | |
| self.rank = rank | |
| self.world_size = world_size | |
| self.num_workers = max(1, num_workers) | |
| self.seed = int(seed) | |
| self.resume_state = resume_state or {} | |
| def worker_uid(self) -> int: | |
| info = get_worker_info() | |
| worker_id = 0 if info is None else info.id | |
| return self.rank * self.num_workers + worker_id | |
| def _shard_order(self, epoch: int) -> np.ndarray: | |
| return np.random.default_rng((self.seed, epoch, 0x534654)).permutation(len(self.shards)) | |
| def _sample_order(self, shard_idx: int, epoch: int) -> np.ndarray: | |
| n = self.shards[shard_idx].windows | |
| return np.random.default_rng((self.seed, epoch, shard_idx, 0x4E45444F)).permutation(n) | |
| def _open_shard(self, shard_idx: int): | |
| s = self.shards[shard_idx] | |
| return ( | |
| np.memmap(s.token_path, dtype=TOKEN_DTYPE, mode="r", offset=HEADER_BYTES), | |
| np.memmap(s.segment_path, dtype=SEG_DTYPE, mode="r", offset=HEADER_BYTES), | |
| ) | |
| def _trainable_mask(segments: np.memmap, start: int, end: int) -> np.ndarray: | |
| mask = np.zeros(end - start, dtype=np.bool_) | |
| offsets = segments["token_offset"] | |
| lo = max(0, int(np.searchsorted(offsets, start, side="right")) - 1) | |
| hi = min(len(segments), int(np.searchsorted(offsets, end, side="left")) + 1) | |
| for row in segments[lo:hi]: | |
| if int(row["role_id"]) != ASSISTANT_ROLE_ID or not ( | |
| int(row["flags"]) & TRAINABLE_FLAG | |
| ): | |
| continue | |
| body_start = int(row["token_offset"]) + int(row["header_tokens"]) | |
| body_end = body_start + int(row["body_tokens"]) | |
| a = max(start, body_start) | |
| b = min(end, body_end) | |
| if a < b: | |
| mask[a - start : b - start] = True | |
| return mask | |
| def __iter__(self) -> Iterator[dict[str, torch.Tensor]]: | |
| uid = self.worker_uid() | |
| total_workers = self.world_size * self.num_workers | |
| resumed = self.resume_state.get(uid) | |
| if resumed is not None and len(resumed) == 4 and int(resumed[0]) == uid: | |
| epoch, shard_pos, local_pos = map(int, resumed[1:]) | |
| else: | |
| epoch, shard_pos, local_pos = 0, 0, 0 | |
| while True: | |
| shard_order = self._shard_order(epoch) | |
| while shard_pos < len(shard_order): | |
| shard_idx = int(shard_order[shard_pos]) | |
| perm = self._sample_order(shard_idx, epoch) | |
| mine = perm[uid::total_workers] | |
| shard = self.shards[shard_idx] | |
| tokens_mm, seg_mm = self._open_shard(shard_idx) | |
| while local_pos < len(mine): | |
| sample_idx = int(mine[local_pos]) | |
| start = int(shard.sample_starts[sample_idx]) | |
| valid_len = int(shard.sample_valid_lens[sample_idx]) | |
| target_left = int(shard.sample_target_lefts[sample_idx]) | |
| expected_targets = int(shard.sample_target_counts[sample_idx]) | |
| valid_end = start + valid_len | |
| if valid_len < 2 or valid_len > self.window: | |
| raise RuntimeError("invalid adaptive SFT sample valid length") | |
| raw = np.full(self.window, PAD_FILL_ID, dtype=TOKEN_DTYPE) | |
| source = np.asarray(tokens_mm[start:valid_end], dtype=TOKEN_DTYPE) | |
| if source.size != valid_len: | |
| raise RuntimeError("short adaptive SFT sample") | |
| raw[:valid_len] = source | |
| if valid_len < self.window and int(raw[valid_len - 1]) != EOS_ID: | |
| raise RuntimeError( | |
| "adaptive padding must begin only after a structural EOS boundary" | |
| ) | |
| trainable = np.zeros(self.window, dtype=np.bool_) | |
| trainable[:valid_len] = self._trainable_mask(seg_mm, start, valid_end) | |
| # Context overlap is intentional; never optimize a target | |
| # that belongs to the already-covered prefix. | |
| left_rel = max(0, min(self.window, target_left - start)) | |
| trainable[:left_rel] = False | |
| label_mask = trainable[1:] | |
| actual_targets = int(label_mask.sum()) | |
| if actual_targets != expected_targets: | |
| raise RuntimeError( | |
| f"adaptive target-count mismatch: sample={sample_idx} " | |
| f"actual={actual_targets} expected={expected_targets}" | |
| ) | |
| if actual_targets <= 0: | |
| raise RuntimeError("adaptive plan yielded zero-target sample") | |
| local_pos += 1 | |
| next_state = ( | |
| [uid, epoch, shard_pos + 1, 0] | |
| if local_pos >= len(mine) | |
| else [uid, epoch, shard_pos, local_pos] | |
| ) | |
| yield { | |
| "tokens": torch.from_numpy(raw), | |
| "trainable_mask": torch.from_numpy(trainable), | |
| "state": torch.tensor(next_state, dtype=torch.int64), | |
| "trainable_tokens": torch.tensor(actual_targets, dtype=torch.int64), | |
| } | |
| del tokens_mm, seg_mm | |
| shard_pos += 1 | |
| local_pos = 0 | |
| epoch += 1 | |
| shard_pos = 0 | |
| local_pos = 0 | |
| def build_sft_loader( | |
| data_dir: str | Path, | |
| seq_len: int, | |
| micro_batch_size: int, | |
| rank: int, | |
| world_size: int, | |
| num_workers: int, | |
| prefetch_factor: int, | |
| seed: int, | |
| resume_state: Optional[dict[int, list[int]]] = None, | |
| shards: Optional[list[SFTShard]] = None, | |
| persistent_workers: bool = True, | |
| ) -> tuple[DataLoader, list[SFTShard]]: | |
| if shards is None: | |
| shards = discover_sft_shards(data_dir, seq_len) | |
| ds = PackedSFTStream(shards, seq_len, rank, world_size, num_workers, seed, resume_state) | |
| loader = DataLoader( | |
| ds, | |
| batch_size=micro_batch_size, | |
| num_workers=num_workers, | |
| pin_memory=True, | |
| drop_last=True, | |
| prefetch_factor=prefetch_factor if num_workers > 0 else None, | |
| persistent_workers=bool(persistent_workers and num_workers > 0), | |
| ) | |
| return loader, shards | |