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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Memory-bounded Mistral-7B last-token hidden-state extraction on TPU.
|
| 3 |
+
|
| 4 |
+
The extractor deliberately loads ``MistralModel`` (no LM head), disables the
|
| 5 |
+
KV cache, and captures only one vector after each transformer block. It does
|
| 6 |
+
not request ``output_hidden_states=True`` and therefore does not retain a full
|
| 7 |
+
``[batch, sequence, hidden]`` tensor for every layer.
|
| 8 |
+
|
| 9 |
+
Output shards contain:
|
| 10 |
+
|
| 11 |
+
* ``embedding``: ``[N, 4096]`` BF16 last-token input embeddings.
|
| 12 |
+
* ``hidden_states``: ``[N, 32, 4096]`` BF16 last-token block states. Layers
|
| 13 |
+
0..30 are post-block states and layer 31 is post-final-RMSNorm, matching the
|
| 14 |
+
32 tensors selected by ``outputs.hidden_states[1:]`` in Transformers.
|
| 15 |
+
|
| 16 |
+
The script is resumable at shard granularity. PyTorch/XLA compiles one graph
|
| 17 |
+
per static ``(batch_size, bucket_length)`` shape.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import gc
|
| 24 |
+
import hashlib
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import platform
|
| 28 |
+
import re
|
| 29 |
+
import sys
|
| 30 |
+
import time
|
| 31 |
+
from collections import defaultdict
|
| 32 |
+
from dataclasses import asdict, dataclass
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from typing import Any, Iterable
|
| 35 |
+
|
| 36 |
+
# Set these before importing torch_xla/JAX-backed packages.
|
| 37 |
+
os.environ.setdefault("PJRT_DEVICE", "TPU")
|
| 38 |
+
os.environ.setdefault("XLA_NO_SPECIAL_SCALARS", "1")
|
| 39 |
+
os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
|
| 40 |
+
os.environ.setdefault("OMP_NUM_THREADS", str(os.cpu_count() or 1))
|
| 41 |
+
os.environ.setdefault("MALLOC_ARENA_MAX", "2")
|
| 42 |
+
|
| 43 |
+
import torch
|
| 44 |
+
import torch_xla
|
| 45 |
+
from datasets import load_dataset
|
| 46 |
+
from safetensors.torch import save_file
|
| 47 |
+
from transformers import AutoTokenizer, MistralModel
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
DEFAULT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
|
| 51 |
+
DEFAULT_MODEL_REVISION = "c170c708c41dac9275d15a8fff4eca08d52bab71"
|
| 52 |
+
DEFAULT_BUCKETS = (128, 256, 512, 1024, 2048)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass(frozen=True)
|
| 56 |
+
class InputRecord:
|
| 57 |
+
source_index: int
|
| 58 |
+
text: str
|
| 59 |
+
question: str = ""
|
| 60 |
+
answer: str = ""
|
| 61 |
+
context: str = ""
|
| 62 |
+
label: int | None = None
|
| 63 |
+
original_answer: str = ""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def parse_args() -> argparse.Namespace:
|
| 67 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 68 |
+
source = parser.add_mutually_exclusive_group()
|
| 69 |
+
source.add_argument(
|
| 70 |
+
"--input-jsonl",
|
| 71 |
+
type=Path,
|
| 72 |
+
help="JSONL containing `text`, or paper-style question/context/answer fields.",
|
| 73 |
+
)
|
| 74 |
+
source.add_argument(
|
| 75 |
+
"--dataset",
|
| 76 |
+
default="stanfordnlp/coqa",
|
| 77 |
+
help="Hugging Face dataset id. CoQA receives paper-compatible flattening.",
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument("--split", default="validation")
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--answer-mode",
|
| 82 |
+
choices=("reference", "best_answer"),
|
| 83 |
+
default="reference",
|
| 84 |
+
help="For structured QA data, append a reference or pre-generated best answer.",
|
| 85 |
+
)
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--answer-view",
|
| 88 |
+
choices=("full", "first_sentence"),
|
| 89 |
+
default="full",
|
| 90 |
+
help="Extract at the full answer's last token or apply the paper's FST rule first.",
|
| 91 |
+
)
|
| 92 |
+
parser.add_argument("--text-column", default="text")
|
| 93 |
+
parser.add_argument("--max-samples", type=int, default=1000)
|
| 94 |
+
parser.add_argument("--start-index", type=int, default=0)
|
| 95 |
+
parser.add_argument("--model-id", default=DEFAULT_MODEL)
|
| 96 |
+
parser.add_argument("--revision", default=DEFAULT_MODEL_REVISION)
|
| 97 |
+
parser.add_argument("--cache-dir", type=Path, default=Path("/content/hf-cache"))
|
| 98 |
+
parser.add_argument("--output-dir", type=Path, required=True)
|
| 99 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
| 100 |
+
parser.add_argument("--shard-size", type=int, default=64)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--buckets",
|
| 103 |
+
type=int,
|
| 104 |
+
nargs="+",
|
| 105 |
+
default=list(DEFAULT_BUCKETS),
|
| 106 |
+
help="Static sequence lengths; overlength inputs are left-truncated to the largest.",
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--attn-implementation",
|
| 110 |
+
choices=("sdpa", "eager"),
|
| 111 |
+
default="sdpa",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument("--overwrite", action="store_true")
|
| 114 |
+
parser.add_argument(
|
| 115 |
+
"--prepare-only",
|
| 116 |
+
action="store_true",
|
| 117 |
+
help="Materialize normalized inputs and manifest without loading Mistral.",
|
| 118 |
+
)
|
| 119 |
+
return parser.parse_args()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def qa_prompt(context: str, question: str) -> str:
|
| 123 |
+
return (
|
| 124 |
+
"Answer the question as briefly as possible, based only on the context:\n"
|
| 125 |
+
f" Context:{context.strip()}\n Question:{question.strip()}\n Answer:"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# Verbatim behavior of the released postprocess_answers/extract_first_sentence
|
| 130 |
+
# path, reorganized into dependency-free functions. This is deliberately not
|
| 131 |
+
# nltk sentence tokenization: the paper uses this rule-based scanner.
|
| 132 |
+
FST_FILTERS = (
|
| 133 |
+
"\n", "Q:", "A:", "question:", "answer:", "Question:", "Answer:",
|
| 134 |
+
"Questions:", "questions:", "QUESTION:", "ANSWER:", "REF", ".Forms",
|
| 135 |
+
"http", "php", "Question", "Answer",
|
| 136 |
+
)
|
| 137 |
+
FST_WORD_ABBREVIATIONS = {
|
| 138 |
+
"Mr", "Mrs", "Ms", "Dr", "Prof", "Sr", "Jr", "Gen", "Brig", "Adm",
|
| 139 |
+
"Rear", "Lt", "Col", "Maj", "Capt", "St", "vs", "etc", "Fig", "Eq", "No",
|
| 140 |
+
}
|
| 141 |
+
FST_MULTI_DOT_ABBREVIATION = re.compile(r"(?:[A-Za-z]\.){2,}$")
|
| 142 |
+
FST_SINGLE_INITIAL = re.compile(r"^[A-Za-z]$")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def extract_first_sentence(text: str) -> str:
|
| 146 |
+
text = text.strip()
|
| 147 |
+
length = len(text)
|
| 148 |
+
cursor = 0
|
| 149 |
+
while cursor < length:
|
| 150 |
+
char = text[cursor]
|
| 151 |
+
if char not in ".!?":
|
| 152 |
+
cursor += 1
|
| 153 |
+
continue
|
| 154 |
+
if char == "." and text[cursor : cursor + 3] == "...":
|
| 155 |
+
cursor += 3
|
| 156 |
+
continue
|
| 157 |
+
if (
|
| 158 |
+
char == "."
|
| 159 |
+
and 0 < cursor < length - 1
|
| 160 |
+
and text[cursor - 1].isdigit()
|
| 161 |
+
and text[cursor + 1].isdigit()
|
| 162 |
+
):
|
| 163 |
+
cursor += 1
|
| 164 |
+
continue
|
| 165 |
+
left = cursor - 1
|
| 166 |
+
while left >= 0 and (text[left].isalpha() or text[left] == "."):
|
| 167 |
+
left -= 1
|
| 168 |
+
token = text[left + 1 : cursor].strip()
|
| 169 |
+
if char == ".":
|
| 170 |
+
right_is_letter_dot = (
|
| 171 |
+
cursor + 2 < length
|
| 172 |
+
and text[cursor + 1].isalpha()
|
| 173 |
+
and text[cursor + 2] == "."
|
| 174 |
+
)
|
| 175 |
+
if cursor > 0 and text[cursor - 1].isalpha() and right_is_letter_dot:
|
| 176 |
+
cursor += 1
|
| 177 |
+
continue
|
| 178 |
+
if "." in token and FST_MULTI_DOT_ABBREVIATION.match(token + "."):
|
| 179 |
+
cursor += 1
|
| 180 |
+
continue
|
| 181 |
+
if token in FST_WORD_ABBREVIATIONS:
|
| 182 |
+
if token == "No":
|
| 183 |
+
right = cursor + 1
|
| 184 |
+
while right < length and text[right].isspace():
|
| 185 |
+
right += 1
|
| 186 |
+
if right < length and text[right].isdigit():
|
| 187 |
+
cursor += 1
|
| 188 |
+
continue
|
| 189 |
+
else:
|
| 190 |
+
cursor += 1
|
| 191 |
+
continue
|
| 192 |
+
if FST_SINGLE_INITIAL.match(token):
|
| 193 |
+
right = cursor + 1
|
| 194 |
+
while right < length and text[right].isspace():
|
| 195 |
+
right += 1
|
| 196 |
+
if right < length and text[right].isupper():
|
| 197 |
+
cursor += 1
|
| 198 |
+
continue
|
| 199 |
+
return text[: cursor + 1].strip()
|
| 200 |
+
return text
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def first_sentence_truncation(answer: str) -> str:
|
| 204 |
+
original = answer.strip()
|
| 205 |
+
cut_position = len(answer)
|
| 206 |
+
for marker in FST_FILTERS:
|
| 207 |
+
marker_position = answer.find(marker)
|
| 208 |
+
if 0 <= marker_position < cut_position:
|
| 209 |
+
cut_position = marker_position
|
| 210 |
+
filtered = answer[:cut_position].strip() or original
|
| 211 |
+
return extract_first_sentence(filtered)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def select_answer_view(answer: str, args: argparse.Namespace) -> str:
|
| 215 |
+
return first_sentence_truncation(answer) if args.answer_view == "first_sentence" else answer
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def record_from_mapping(row: dict[str, Any], source_index: int, args: argparse.Namespace) -> InputRecord:
|
| 219 |
+
if args.text_column in row and row.get(args.text_column) not in (None, ""):
|
| 220 |
+
if args.answer_view != "full":
|
| 221 |
+
raise ValueError(
|
| 222 |
+
"--answer-view first_sentence requires structured context/question/answer fields, not a prejoined text field"
|
| 223 |
+
)
|
| 224 |
+
text = str(row[args.text_column])
|
| 225 |
+
return InputRecord(
|
| 226 |
+
source_index=source_index,
|
| 227 |
+
text=text,
|
| 228 |
+
question=str(row.get("question", "")),
|
| 229 |
+
answer=str(row.get("answer", row.get("best_answer", ""))),
|
| 230 |
+
context=str(row.get("context", "")),
|
| 231 |
+
label=int(row["label"]) if row.get("label") is not None else None,
|
| 232 |
+
original_answer=str(row.get("answer", row.get("best_answer", ""))),
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
context = str(row.get("context", row.get("story", "")))
|
| 236 |
+
question = str(row.get("question", ""))
|
| 237 |
+
if args.answer_mode == "best_answer":
|
| 238 |
+
original_answer = str(row.get("best_answer", ""))
|
| 239 |
+
if not original_answer:
|
| 240 |
+
raise ValueError(f"row {source_index} has no non-empty best_answer")
|
| 241 |
+
else:
|
| 242 |
+
answer_value = row.get("answer", row.get("answers", ""))
|
| 243 |
+
if isinstance(answer_value, dict):
|
| 244 |
+
answer_value = answer_value.get("input_text", answer_value.get("text", ""))
|
| 245 |
+
if isinstance(answer_value, (list, tuple)):
|
| 246 |
+
answer_value = answer_value[0] if answer_value else ""
|
| 247 |
+
original_answer = str(answer_value)
|
| 248 |
+
answer = select_answer_view(original_answer, args)
|
| 249 |
+
if not question or not answer:
|
| 250 |
+
raise ValueError(
|
| 251 |
+
f"row {source_index} cannot be converted: provide `text`, or question plus answer(s)"
|
| 252 |
+
)
|
| 253 |
+
text = f"{qa_prompt(context, question)} {answer}"
|
| 254 |
+
return InputRecord(
|
| 255 |
+
source_index=source_index,
|
| 256 |
+
text=text,
|
| 257 |
+
question=question,
|
| 258 |
+
answer=answer,
|
| 259 |
+
context=context,
|
| 260 |
+
label=int(row["label"]) if row.get("label") is not None else None,
|
| 261 |
+
original_answer=original_answer,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def iter_coqa(args: argparse.Namespace) -> Iterable[InputRecord]:
|
| 266 |
+
dataset = load_dataset(
|
| 267 |
+
"stanfordnlp/coqa",
|
| 268 |
+
split=args.split,
|
| 269 |
+
cache_dir=str(args.cache_dir / "datasets"),
|
| 270 |
+
)
|
| 271 |
+
flat_index = 0
|
| 272 |
+
emitted = 0
|
| 273 |
+
stop = args.start_index + args.max_samples if args.max_samples else None
|
| 274 |
+
for sample in dataset:
|
| 275 |
+
story = sample["story"]
|
| 276 |
+
questions = sample["questions"]
|
| 277 |
+
answers = sample["answers"]["input_text"]
|
| 278 |
+
for question, answer in zip(questions, answers, strict=True):
|
| 279 |
+
if flat_index >= args.start_index and (stop is None or flat_index < stop):
|
| 280 |
+
selected_answer = select_answer_view(answer, args)
|
| 281 |
+
text = f"{qa_prompt(story, question)} {selected_answer}"
|
| 282 |
+
yield InputRecord(
|
| 283 |
+
source_index=flat_index,
|
| 284 |
+
text=text,
|
| 285 |
+
question=question,
|
| 286 |
+
answer=selected_answer,
|
| 287 |
+
context=story,
|
| 288 |
+
label=None,
|
| 289 |
+
original_answer=answer,
|
| 290 |
+
)
|
| 291 |
+
emitted += 1
|
| 292 |
+
flat_index += 1
|
| 293 |
+
if stop is not None and flat_index >= stop:
|
| 294 |
+
return
|
| 295 |
+
if emitted == 0:
|
| 296 |
+
raise ValueError(f"start index {args.start_index} is outside flattened CoQA split")
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def load_records(args: argparse.Namespace) -> list[InputRecord]:
|
| 300 |
+
if args.input_jsonl:
|
| 301 |
+
records: list[InputRecord] = []
|
| 302 |
+
stop = args.start_index + args.max_samples if args.max_samples else None
|
| 303 |
+
with args.input_jsonl.open(encoding="utf-8") as handle:
|
| 304 |
+
for index, line in enumerate(handle):
|
| 305 |
+
if index < args.start_index:
|
| 306 |
+
continue
|
| 307 |
+
if stop is not None and index >= stop:
|
| 308 |
+
break
|
| 309 |
+
line = line.strip()
|
| 310 |
+
if line:
|
| 311 |
+
records.append(record_from_mapping(json.loads(line), index, args))
|
| 312 |
+
return records
|
| 313 |
+
if args.dataset == "stanfordnlp/coqa":
|
| 314 |
+
return list(iter_coqa(args))
|
| 315 |
+
|
| 316 |
+
dataset = load_dataset(
|
| 317 |
+
args.dataset,
|
| 318 |
+
split=args.split,
|
| 319 |
+
cache_dir=str(args.cache_dir / "datasets"),
|
| 320 |
+
)
|
| 321 |
+
stop = args.start_index + args.max_samples if args.max_samples else len(dataset)
|
| 322 |
+
return [
|
| 323 |
+
record_from_mapping(dict(dataset[index]), index, args)
|
| 324 |
+
for index in range(args.start_index, min(stop, len(dataset)))
|
| 325 |
+
]
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def assign_bucket(token_count: int, buckets: tuple[int, ...]) -> tuple[int, int]:
|
| 329 |
+
for bucket in buckets:
|
| 330 |
+
if token_count <= bucket:
|
| 331 |
+
return bucket, 0
|
| 332 |
+
return buckets[-1], token_count - buckets[-1]
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
|
| 336 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 337 |
+
with tmp.open("w", encoding="utf-8") as handle:
|
| 338 |
+
for row in rows:
|
| 339 |
+
handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
|
| 340 |
+
tmp.replace(path)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class LastTokenCapture:
|
| 344 |
+
"""Capture only small last-position slices from the embedding and blocks."""
|
| 345 |
+
|
| 346 |
+
def __init__(self, model: MistralModel):
|
| 347 |
+
self.embedding: torch.Tensor | None = None
|
| 348 |
+
self.layers: dict[int, torch.Tensor] = {}
|
| 349 |
+
self.handles = [model.embed_tokens.register_forward_hook(self._embedding_hook)]
|
| 350 |
+
# The final raw block output is replaced with post-final-norm below so
|
| 351 |
+
# the indexing agrees with Transformers output_hidden_states[1:].
|
| 352 |
+
for layer_index, layer in enumerate(model.layers[:-1]):
|
| 353 |
+
self.handles.append(layer.register_forward_hook(self._layer_hook(layer_index)))
|
| 354 |
+
|
| 355 |
+
def _embedding_hook(self, _module: Any, _inputs: Any, output: torch.Tensor) -> None:
|
| 356 |
+
self.embedding = output[:, -1, :].clone()
|
| 357 |
+
|
| 358 |
+
def _layer_hook(self, layer_index: int):
|
| 359 |
+
def hook(_module: Any, _inputs: Any, output: torch.Tensor) -> None:
|
| 360 |
+
self.layers[layer_index] = output[:, -1, :].clone()
|
| 361 |
+
|
| 362 |
+
return hook
|
| 363 |
+
|
| 364 |
+
def clear(self) -> None:
|
| 365 |
+
self.embedding = None
|
| 366 |
+
self.layers.clear()
|
| 367 |
+
|
| 368 |
+
def close(self) -> None:
|
| 369 |
+
for handle in self.handles:
|
| 370 |
+
handle.remove()
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def extract_batch(
|
| 374 |
+
model: MistralModel,
|
| 375 |
+
capture: LastTokenCapture,
|
| 376 |
+
device: torch.device,
|
| 377 |
+
input_ids: torch.Tensor,
|
| 378 |
+
attention_mask: torch.Tensor,
|
| 379 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 380 |
+
capture.clear()
|
| 381 |
+
# PyTorch/XLA rotary-embedding buffers currently need tensor version
|
| 382 |
+
# counters, which torch.inference_mode() disables. no_grad() avoids
|
| 383 |
+
# autograd retention while remaining compatible with XLA views.
|
| 384 |
+
with torch.no_grad():
|
| 385 |
+
outputs = model(
|
| 386 |
+
input_ids=input_ids.to(device),
|
| 387 |
+
attention_mask=attention_mask.to(device),
|
| 388 |
+
use_cache=False,
|
| 389 |
+
return_dict=True,
|
| 390 |
+
)
|
| 391 |
+
final_state = outputs.last_hidden_state[:, -1, :].clone()
|
| 392 |
+
if capture.embedding is None or len(capture.layers) != model.config.num_hidden_layers - 1:
|
| 393 |
+
raise RuntimeError("incomplete hook capture")
|
| 394 |
+
hidden = torch.stack(
|
| 395 |
+
[capture.layers[index] for index in range(model.config.num_hidden_layers - 1)]
|
| 396 |
+
+ [final_state],
|
| 397 |
+
dim=1,
|
| 398 |
+
)
|
| 399 |
+
# One device-to-host transfer per batch. This is the XLA execution
|
| 400 |
+
# barrier and JIT-compiles the static bucket on its first occurrence.
|
| 401 |
+
packed = torch.cat((capture.embedding.unsqueeze(1), hidden), dim=1).cpu()
|
| 402 |
+
torch_xla.sync(wait=True)
|
| 403 |
+
return packed[:, 0].contiguous(), packed[:, 1:].contiguous()
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def existing_source_indices(metadata_path: Path) -> set[int]:
|
| 407 |
+
if not metadata_path.exists():
|
| 408 |
+
return set()
|
| 409 |
+
result: set[int] = set()
|
| 410 |
+
with metadata_path.open(encoding="utf-8") as handle:
|
| 411 |
+
for line in handle:
|
| 412 |
+
if line.strip():
|
| 413 |
+
result.add(int(json.loads(line)["source_index"]))
|
| 414 |
+
return result
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def main() -> None:
|
| 418 |
+
args = parse_args()
|
| 419 |
+
if args.batch_size < 1 or args.shard_size < args.batch_size:
|
| 420 |
+
raise ValueError("batch size must be positive and no larger than shard size")
|
| 421 |
+
buckets = tuple(sorted(set(args.buckets)))
|
| 422 |
+
if not buckets or buckets[0] < 1:
|
| 423 |
+
raise ValueError("buckets must contain positive lengths")
|
| 424 |
+
|
| 425 |
+
output_dir = args.output_dir.resolve()
|
| 426 |
+
shards_dir = output_dir / "states" / args.split
|
| 427 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 428 |
+
shards_dir.mkdir(parents=True, exist_ok=True)
|
| 429 |
+
inputs_path = output_dir / f"inputs-{args.split}.jsonl"
|
| 430 |
+
metadata_path = output_dir / f"metadata-{args.split}.jsonl"
|
| 431 |
+
manifest_path = output_dir / "manifest.json"
|
| 432 |
+
|
| 433 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 434 |
+
args.model_id,
|
| 435 |
+
revision=args.revision,
|
| 436 |
+
cache_dir=str(args.cache_dir),
|
| 437 |
+
use_fast=True,
|
| 438 |
+
)
|
| 439 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 440 |
+
tokenizer.padding_side = "left"
|
| 441 |
+
tokenizer.truncation_side = "left"
|
| 442 |
+
|
| 443 |
+
records = load_records(args)
|
| 444 |
+
if not records:
|
| 445 |
+
raise ValueError("no input records")
|
| 446 |
+
prepared: list[dict[str, Any]] = []
|
| 447 |
+
by_bucket: dict[int, list[tuple[InputRecord, int, int]]] = defaultdict(list)
|
| 448 |
+
for record in records:
|
| 449 |
+
token_count = len(tokenizer(record.text, add_special_tokens=False)["input_ids"])
|
| 450 |
+
bucket, truncated_tokens = assign_bucket(token_count, buckets)
|
| 451 |
+
by_bucket[bucket].append((record, token_count, truncated_tokens))
|
| 452 |
+
prepared.append(
|
| 453 |
+
{
|
| 454 |
+
**asdict(record),
|
| 455 |
+
"input_sha256": hashlib.sha256(record.text.encode("utf-8")).hexdigest(),
|
| 456 |
+
"original_token_count": token_count,
|
| 457 |
+
"bucket_length": bucket,
|
| 458 |
+
"left_truncated_tokens": truncated_tokens,
|
| 459 |
+
}
|
| 460 |
+
)
|
| 461 |
+
write_jsonl(inputs_path, prepared)
|
| 462 |
+
|
| 463 |
+
manifest: dict[str, Any] = {
|
| 464 |
+
"schema_version": 1,
|
| 465 |
+
"model_id": args.model_id,
|
| 466 |
+
"model_revision": args.revision,
|
| 467 |
+
"architecture": "MistralModel (LM head omitted)",
|
| 468 |
+
"source": str(args.input_jsonl) if args.input_jsonl else args.dataset,
|
| 469 |
+
"split": args.split,
|
| 470 |
+
"answer_mode": args.answer_mode,
|
| 471 |
+
"answer_view": args.answer_view,
|
| 472 |
+
"num_records": len(records),
|
| 473 |
+
"start_index": args.start_index,
|
| 474 |
+
"dtype": "bfloat16",
|
| 475 |
+
"embedding_shape_per_record": [4096],
|
| 476 |
+
"hidden_states_shape_per_record": [32, 4096],
|
| 477 |
+
"hidden_state_semantics": {
|
| 478 |
+
"0..30": "post-transformer-block, pre-final-RMSNorm",
|
| 479 |
+
"31": "post-transformer-block-31 and post-final-RMSNorm",
|
| 480 |
+
},
|
| 481 |
+
"token_position": "last non-padding token (inputs are left padded)",
|
| 482 |
+
"use_cache": False,
|
| 483 |
+
"output_hidden_states": False,
|
| 484 |
+
"sequence_buckets": list(buckets),
|
| 485 |
+
"batch_size": args.batch_size,
|
| 486 |
+
"shard_size": args.shard_size,
|
| 487 |
+
"attn_implementation": args.attn_implementation,
|
| 488 |
+
"xla_no_special_scalars": os.environ["XLA_NO_SPECIAL_SCALARS"],
|
| 489 |
+
"python": sys.version,
|
| 490 |
+
"platform": platform.platform(),
|
| 491 |
+
"torch": torch.__version__,
|
| 492 |
+
"torch_xla": torch_xla.__version__,
|
| 493 |
+
"created_unix": time.time(),
|
| 494 |
+
"status": "prepared" if args.prepare_only else "extracting",
|
| 495 |
+
}
|
| 496 |
+
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
| 497 |
+
if args.prepare_only:
|
| 498 |
+
print(json.dumps({"status": "prepared", "records": len(records), "output": str(output_dir)}))
|
| 499 |
+
return
|
| 500 |
+
|
| 501 |
+
already_done = set() if args.overwrite else existing_source_indices(metadata_path)
|
| 502 |
+
if already_done:
|
| 503 |
+
print(f"Resuming: {len(already_done)} source indices already present")
|
| 504 |
+
|
| 505 |
+
device = torch_xla.device()
|
| 506 |
+
print(f"Loading {args.model_id}@{args.revision} as MistralModel BF16 on CPU")
|
| 507 |
+
model = MistralModel.from_pretrained(
|
| 508 |
+
args.model_id,
|
| 509 |
+
revision=args.revision,
|
| 510 |
+
cache_dir=str(args.cache_dir),
|
| 511 |
+
dtype=torch.bfloat16,
|
| 512 |
+
low_cpu_mem_usage=True,
|
| 513 |
+
attn_implementation=args.attn_implementation,
|
| 514 |
+
)
|
| 515 |
+
model.config.use_cache = False
|
| 516 |
+
model.eval()
|
| 517 |
+
print(f"Moving base model (no LM head) to {device}")
|
| 518 |
+
model.to(device)
|
| 519 |
+
torch_xla.sync(wait=True)
|
| 520 |
+
capture = LastTokenCapture(model)
|
| 521 |
+
|
| 522 |
+
shard_number = 0
|
| 523 |
+
if not args.overwrite:
|
| 524 |
+
existing_shards = sorted(shards_dir.glob("shard-*.safetensors"))
|
| 525 |
+
if existing_shards:
|
| 526 |
+
shard_number = max(int(path.stem.split("-")[-1]) for path in existing_shards) + 1
|
| 527 |
+
|
| 528 |
+
pending_embeddings: list[torch.Tensor] = []
|
| 529 |
+
pending_hidden: list[torch.Tensor] = []
|
| 530 |
+
pending_meta: list[dict[str, Any]] = []
|
| 531 |
+
all_metadata: list[dict[str, Any]] = []
|
| 532 |
+
if metadata_path.exists() and not args.overwrite:
|
| 533 |
+
with metadata_path.open(encoding="utf-8") as handle:
|
| 534 |
+
all_metadata = [json.loads(line) for line in handle if line.strip()]
|
| 535 |
+
|
| 536 |
+
start_time = time.monotonic()
|
| 537 |
+
completed_this_run = 0
|
| 538 |
+
|
| 539 |
+
def flush() -> None:
|
| 540 |
+
nonlocal shard_number
|
| 541 |
+
if not pending_meta:
|
| 542 |
+
return
|
| 543 |
+
shard_name = f"shard-{shard_number:05d}.safetensors"
|
| 544 |
+
shard_path = shards_dir / shard_name
|
| 545 |
+
tensors = {
|
| 546 |
+
"embedding": torch.cat(pending_embeddings, dim=0).to(torch.bfloat16),
|
| 547 |
+
"hidden_states": torch.cat(pending_hidden, dim=0).to(torch.bfloat16),
|
| 548 |
+
}
|
| 549 |
+
save_file(
|
| 550 |
+
tensors,
|
| 551 |
+
str(shard_path),
|
| 552 |
+
metadata={
|
| 553 |
+
"model_id": args.model_id,
|
| 554 |
+
"model_revision": args.revision,
|
| 555 |
+
"split": args.split,
|
| 556 |
+
"dtype": "bfloat16",
|
| 557 |
+
},
|
| 558 |
+
)
|
| 559 |
+
for offset, row in enumerate(pending_meta):
|
| 560 |
+
row["shard"] = f"states/{args.split}/{shard_name}"
|
| 561 |
+
row["offset"] = offset
|
| 562 |
+
row["embedding_key"] = "embedding"
|
| 563 |
+
row["hidden_states_key"] = "hidden_states"
|
| 564 |
+
all_metadata.extend(pending_meta)
|
| 565 |
+
write_jsonl(metadata_path, all_metadata)
|
| 566 |
+
print(f"Saved {shard_path.name}: {len(pending_meta)} records")
|
| 567 |
+
pending_embeddings.clear()
|
| 568 |
+
pending_hidden.clear()
|
| 569 |
+
pending_meta.clear()
|
| 570 |
+
shard_number += 1
|
| 571 |
+
|
| 572 |
+
try:
|
| 573 |
+
for bucket in buckets:
|
| 574 |
+
bucket_records = [item for item in by_bucket.get(bucket, []) if item[0].source_index not in already_done]
|
| 575 |
+
if not bucket_records:
|
| 576 |
+
continue
|
| 577 |
+
print(f"Bucket {bucket}: {len(bucket_records)} records")
|
| 578 |
+
for start in range(0, len(bucket_records), args.batch_size):
|
| 579 |
+
batch_items = bucket_records[start : start + args.batch_size]
|
| 580 |
+
# Pad the final partial batch with a duplicate so each bucket has
|
| 581 |
+
# exactly one compiled shape, then discard the duplicate output.
|
| 582 |
+
actual_size = len(batch_items)
|
| 583 |
+
while len(batch_items) < args.batch_size:
|
| 584 |
+
batch_items.append(batch_items[-1])
|
| 585 |
+
texts = [item[0].text for item in batch_items]
|
| 586 |
+
encoded = tokenizer(
|
| 587 |
+
texts,
|
| 588 |
+
add_special_tokens=False,
|
| 589 |
+
padding="max_length",
|
| 590 |
+
truncation=True,
|
| 591 |
+
max_length=bucket,
|
| 592 |
+
return_tensors="pt",
|
| 593 |
+
)
|
| 594 |
+
embeddings, hidden = extract_batch(
|
| 595 |
+
model,
|
| 596 |
+
capture,
|
| 597 |
+
device,
|
| 598 |
+
encoded["input_ids"],
|
| 599 |
+
encoded["attention_mask"],
|
| 600 |
+
)
|
| 601 |
+
embeddings = embeddings[:actual_size]
|
| 602 |
+
hidden = hidden[:actual_size]
|
| 603 |
+
pending_embeddings.append(embeddings)
|
| 604 |
+
pending_hidden.append(hidden)
|
| 605 |
+
for local_index, (record, token_count, truncated_tokens) in enumerate(batch_items[:actual_size]):
|
| 606 |
+
last_token_id = int(encoded["input_ids"][local_index, -1])
|
| 607 |
+
pending_meta.append(
|
| 608 |
+
{
|
| 609 |
+
"source_index": record.source_index,
|
| 610 |
+
"input_sha256": hashlib.sha256(record.text.encode("utf-8")).hexdigest(),
|
| 611 |
+
"original_token_count": token_count,
|
| 612 |
+
"bucket_length": bucket,
|
| 613 |
+
"left_truncated_tokens": truncated_tokens,
|
| 614 |
+
"last_token_id": last_token_id,
|
| 615 |
+
"last_token": tokenizer.decode([last_token_id]),
|
| 616 |
+
}
|
| 617 |
+
)
|
| 618 |
+
completed_this_run += actual_size
|
| 619 |
+
if len(pending_meta) >= args.shard_size:
|
| 620 |
+
flush()
|
| 621 |
+
if completed_this_run % 10 == 0:
|
| 622 |
+
rate = completed_this_run / max(time.monotonic() - start_time, 1e-9)
|
| 623 |
+
print(f"Progress: {completed_this_run}/{len(records) - len(already_done)} ({rate:.2f} records/s)")
|
| 624 |
+
flush()
|
| 625 |
+
finally:
|
| 626 |
+
capture.close()
|
| 627 |
+
|
| 628 |
+
manifest["status"] = "complete"
|
| 629 |
+
manifest["completed_records"] = len(all_metadata)
|
| 630 |
+
manifest["num_shards"] = shard_number
|
| 631 |
+
manifest["elapsed_seconds_this_run"] = time.monotonic() - start_time
|
| 632 |
+
manifest["completed_unix"] = time.time()
|
| 633 |
+
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
| 634 |
+
del model
|
| 635 |
+
gc.collect()
|
| 636 |
+
print(json.dumps({"status": "complete", "records": len(all_metadata), "output": str(output_dir)}))
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
if __name__ == "__main__":
|
| 640 |
+
main()
|