Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
5.44 kB
"""Corpus preparation and batching for Phase 3 training.
Each condition draws from a different source but goes through the same
path: raw documents -> per-condition text transform -> Llama-3.2 tokens ->
one packed id stream chunked into fixed-length training blocks. Held-out
documents are reserved from a disjoint slice of the source before any
training document is read, so the evaluation set cannot overlap training
text by construction rather than by a post-hoc check.
"""
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Iterator, Optional
import numpy as np
import torch
SANGRAHA_TEXT_FIELD = "text"
ENGLISH_DATASET = "wikimedia/wikipedia"
ENGLISH_CONFIG = "20231101.en"
MIN_DOC_CHARS = 200
def iter_sangraha_docs(path: str) -> Iterator[str]:
"""Yield document texts from the Phase 1 sangraha JSONL, longest-first order preserved."""
with open(path, encoding="utf-8") as f:
for line in f:
text = json.loads(line)[SANGRAHA_TEXT_FIELD]
if len(text) >= MIN_DOC_CHARS:
yield text
def iter_english_docs() -> Iterator[str]:
"""Yield English Wikipedia article texts, streamed rather than downloaded whole."""
from datasets import load_dataset
ds = load_dataset(ENGLISH_DATASET, ENGLISH_CONFIG, split="train", streaming=True)
for row in ds:
text = row["text"]
if len(text) >= MIN_DOC_CHARS:
yield text
@dataclass
class PreparedCorpus:
"""Outcome of preparing one condition's data.
Attributes:
train_ids: 1-D int32 array of packed token ids for training.
heldout_texts: raw document texts reserved for evaluation, disjoint
from every document contributing to train_ids.
n_train_tokens: length of train_ids.
n_docs_consumed: source documents read to fill the training budget.
"""
train_ids: np.ndarray
heldout_texts: list
n_train_tokens: int
n_docs_consumed: int
def prepare_corpus(
docs: Iterator[str],
tokenizer,
target_tokens: int,
n_heldout_docs: int,
transform: Optional[Callable[[str], str]] = None,
) -> PreparedCorpus:
"""Reserve held-out documents, then tokenize training documents up to a token budget.
The first n_heldout_docs documents from the iterator are set aside for
evaluation and never tokenized into train_ids; training consumes the
documents after them. Both halves get the same transform, so a held-out
document is drawn from the same distribution the model trained on.
Args:
docs: source document iterator.
tokenizer: a Llama-3.2 fast tokenizer.
target_tokens: stop once this many training tokens are packed.
n_heldout_docs: documents to reserve before training documents start.
transform: optional per-document text transform (e.g. romanization).
"""
heldout_texts = []
for text in docs:
heldout_texts.append(transform(text) if transform else text)
if len(heldout_texts) >= n_heldout_docs:
break
buffers = []
total = 0
n_docs = 0
for text in docs:
if transform:
text = transform(text)
ids = tokenizer(text, add_special_tokens=False).input_ids
buffers.append(np.asarray(ids, dtype=np.int32))
total += len(ids)
n_docs += 1
if total >= target_tokens:
break
train_ids = np.concatenate(buffers)[:target_tokens] if buffers else np.zeros(0, dtype=np.int32)
return PreparedCorpus(
train_ids=train_ids,
heldout_texts=heldout_texts,
n_train_tokens=int(len(train_ids)),
n_docs_consumed=n_docs,
)
def save_corpus(prepared: PreparedCorpus, out_dir: str, condition: str) -> dict:
"""Write train ids (.npy) and held-out texts (.jsonl); return the written paths."""
out = Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
ids_path = out / f"{condition}_train_ids.npy"
heldout_path = out / f"{condition}_heldout.jsonl"
np.save(ids_path, prepared.train_ids)
with heldout_path.open("w", encoding="utf-8") as f:
for text in prepared.heldout_texts:
f.write(json.dumps({"text": text}, ensure_ascii=False) + "\n")
return {"train_ids": str(ids_path), "heldout": str(heldout_path)}
def load_train_ids(path: str) -> np.ndarray:
return np.load(path)
def load_heldout_texts(path: str) -> list:
with open(path, encoding="utf-8") as f:
return [json.loads(line)["text"] for line in f]
def iter_batches(
ids: np.ndarray, batch_size: int, seq_len: int, seed: int, max_steps: Optional[int] = None
) -> Iterator[torch.Tensor]:
"""Yield (batch_size, seq_len) LongTensor blocks sampled without replacement.
Blocks are non-overlapping windows over the packed stream, visited in a
seeded permutation so a run is reproducible and a shorter run is a
prefix-free random subset rather than the corpus's leading documents.
"""
n_blocks = len(ids) // seq_len
order = np.random.default_rng(seed).permutation(n_blocks)
n_batches = n_blocks // batch_size
if max_steps is not None:
n_batches = min(n_batches, max_steps)
for b in range(n_batches):
sel = order[b * batch_size : (b + 1) * batch_size]
block = np.stack([ids[i * seq_len : (i + 1) * seq_len] for i in sel])
yield torch.from_numpy(block.astype(np.int64))