| |
| """Memory-bounded Mistral-7B last-token hidden-state extraction on TPU. |
| |
| The extractor deliberately loads ``MistralModel`` (no LM head), disables the |
| KV cache, and captures only one vector after each transformer block. It does |
| not request ``output_hidden_states=True`` and therefore does not retain a full |
| ``[batch, sequence, hidden]`` tensor for every layer. |
| |
| Output shards contain: |
| |
| * ``embedding``: ``[N, 4096]`` BF16 last-token input embeddings. |
| * ``hidden_states``: ``[N, 32, 4096]`` BF16 last-token block states. Layers |
| 0..30 are post-block states and layer 31 is post-final-RMSNorm, matching the |
| 32 tensors selected by ``outputs.hidden_states[1:]`` in Transformers. |
| |
| The script is resumable at shard granularity. PyTorch/XLA compiles one graph |
| per static ``(batch_size, bucket_length)`` shape. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import gc |
| import hashlib |
| import json |
| import os |
| import platform |
| import re |
| import sys |
| import time |
| from collections import defaultdict |
| from dataclasses import asdict, dataclass |
| from pathlib import Path |
| from typing import Any, Iterable |
|
|
| |
| os.environ.setdefault("PJRT_DEVICE", "TPU") |
| os.environ.setdefault("XLA_NO_SPECIAL_SCALARS", "1") |
| os.environ.setdefault("TOKENIZERS_PARALLELISM", "true") |
| os.environ.setdefault("OMP_NUM_THREADS", str(os.cpu_count() or 1)) |
| os.environ.setdefault("MALLOC_ARENA_MAX", "2") |
|
|
| import torch |
| import torch_xla |
| from datasets import load_dataset |
| from safetensors.torch import save_file |
| from transformers import AutoTokenizer, MistralModel |
|
|
|
|
| DEFAULT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3" |
| DEFAULT_MODEL_REVISION = "c170c708c41dac9275d15a8fff4eca08d52bab71" |
| DEFAULT_BUCKETS = (128, 256, 512, 1024, 2048) |
|
|
|
|
| @dataclass(frozen=True) |
| class InputRecord: |
| source_index: int |
| text: str |
| question: str = "" |
| answer: str = "" |
| context: str = "" |
| label: int | None = None |
| original_answer: str = "" |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description=__doc__) |
| source = parser.add_mutually_exclusive_group() |
| source.add_argument( |
| "--input-jsonl", |
| type=Path, |
| help="JSONL containing `text`, or paper-style question/context/answer fields.", |
| ) |
| source.add_argument( |
| "--dataset", |
| default="stanfordnlp/coqa", |
| help="Hugging Face dataset id. CoQA receives paper-compatible flattening.", |
| ) |
| parser.add_argument("--split", default="validation") |
| parser.add_argument( |
| "--answer-mode", |
| choices=("reference", "best_answer"), |
| default="reference", |
| help="For structured QA data, append a reference or pre-generated best answer.", |
| ) |
| parser.add_argument( |
| "--answer-view", |
| choices=("full", "first_sentence"), |
| default="full", |
| help="Extract at the full answer's last token or apply the paper's FST rule first.", |
| ) |
| parser.add_argument("--text-column", default="text") |
| parser.add_argument("--max-samples", type=int, default=1000) |
| parser.add_argument("--start-index", type=int, default=0) |
| parser.add_argument("--model-id", default=DEFAULT_MODEL) |
| parser.add_argument("--revision", default=DEFAULT_MODEL_REVISION) |
| parser.add_argument("--cache-dir", type=Path, default=Path("/content/hf-cache")) |
| parser.add_argument("--output-dir", type=Path, required=True) |
| parser.add_argument("--batch-size", type=int, default=1) |
| parser.add_argument("--shard-size", type=int, default=64) |
| parser.add_argument( |
| "--buckets", |
| type=int, |
| nargs="+", |
| default=list(DEFAULT_BUCKETS), |
| help="Static sequence lengths; overlength inputs are left-truncated to the largest.", |
| ) |
| parser.add_argument( |
| "--attn-implementation", |
| choices=("sdpa", "eager"), |
| default="sdpa", |
| ) |
| parser.add_argument("--overwrite", action="store_true") |
| parser.add_argument( |
| "--prepare-only", |
| action="store_true", |
| help="Materialize normalized inputs and manifest without loading Mistral.", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def qa_prompt(context: str, question: str) -> str: |
| return ( |
| "Answer the question as briefly as possible, based only on the context:\n" |
| f" Context:{context.strip()}\n Question:{question.strip()}\n Answer:" |
| ) |
|
|
|
|
| |
| |
| |
| FST_FILTERS = ( |
| "\n", "Q:", "A:", "question:", "answer:", "Question:", "Answer:", |
| "Questions:", "questions:", "QUESTION:", "ANSWER:", "REF", ".Forms", |
| "http", "php", "Question", "Answer", |
| ) |
| FST_WORD_ABBREVIATIONS = { |
| "Mr", "Mrs", "Ms", "Dr", "Prof", "Sr", "Jr", "Gen", "Brig", "Adm", |
| "Rear", "Lt", "Col", "Maj", "Capt", "St", "vs", "etc", "Fig", "Eq", "No", |
| } |
| FST_MULTI_DOT_ABBREVIATION = re.compile(r"(?:[A-Za-z]\.){2,}$") |
| FST_SINGLE_INITIAL = re.compile(r"^[A-Za-z]$") |
|
|
|
|
| def extract_first_sentence(text: str) -> str: |
| text = text.strip() |
| length = len(text) |
| cursor = 0 |
| while cursor < length: |
| char = text[cursor] |
| if char not in ".!?": |
| cursor += 1 |
| continue |
| if char == "." and text[cursor : cursor + 3] == "...": |
| cursor += 3 |
| continue |
| if ( |
| char == "." |
| and 0 < cursor < length - 1 |
| and text[cursor - 1].isdigit() |
| and text[cursor + 1].isdigit() |
| ): |
| cursor += 1 |
| continue |
| left = cursor - 1 |
| while left >= 0 and (text[left].isalpha() or text[left] == "."): |
| left -= 1 |
| token = text[left + 1 : cursor].strip() |
| if char == ".": |
| right_is_letter_dot = ( |
| cursor + 2 < length |
| and text[cursor + 1].isalpha() |
| and text[cursor + 2] == "." |
| ) |
| if cursor > 0 and text[cursor - 1].isalpha() and right_is_letter_dot: |
| cursor += 1 |
| continue |
| if "." in token and FST_MULTI_DOT_ABBREVIATION.match(token + "."): |
| cursor += 1 |
| continue |
| if token in FST_WORD_ABBREVIATIONS: |
| if token == "No": |
| right = cursor + 1 |
| while right < length and text[right].isspace(): |
| right += 1 |
| if right < length and text[right].isdigit(): |
| cursor += 1 |
| continue |
| else: |
| cursor += 1 |
| continue |
| if FST_SINGLE_INITIAL.match(token): |
| right = cursor + 1 |
| while right < length and text[right].isspace(): |
| right += 1 |
| if right < length and text[right].isupper(): |
| cursor += 1 |
| continue |
| return text[: cursor + 1].strip() |
| return text |
|
|
|
|
| def first_sentence_truncation(answer: str) -> str: |
| original = answer.strip() |
| cut_position = len(answer) |
| for marker in FST_FILTERS: |
| marker_position = answer.find(marker) |
| if 0 <= marker_position < cut_position: |
| cut_position = marker_position |
| filtered = answer[:cut_position].strip() or original |
| return extract_first_sentence(filtered) |
|
|
|
|
| def select_answer_view(answer: str, args: argparse.Namespace) -> str: |
| return first_sentence_truncation(answer) if args.answer_view == "first_sentence" else answer |
|
|
|
|
| def record_from_mapping(row: dict[str, Any], source_index: int, args: argparse.Namespace) -> InputRecord: |
| if args.text_column in row and row.get(args.text_column) not in (None, ""): |
| if args.answer_view != "full": |
| raise ValueError( |
| "--answer-view first_sentence requires structured context/question/answer fields, not a prejoined text field" |
| ) |
| text = str(row[args.text_column]) |
| return InputRecord( |
| source_index=source_index, |
| text=text, |
| question=str(row.get("question", "")), |
| answer=str(row.get("answer", row.get("best_answer", ""))), |
| context=str(row.get("context", "")), |
| label=int(row["label"]) if row.get("label") is not None else None, |
| original_answer=str(row.get("answer", row.get("best_answer", ""))), |
| ) |
|
|
| context = str(row.get("context", row.get("story", ""))) |
| question = str(row.get("question", "")) |
| if args.answer_mode == "best_answer": |
| original_answer = str(row.get("best_answer", "")) |
| if not original_answer: |
| raise ValueError(f"row {source_index} has no non-empty best_answer") |
| else: |
| answer_value = row.get("answer", row.get("answers", "")) |
| if isinstance(answer_value, dict): |
| answer_value = answer_value.get("input_text", answer_value.get("text", "")) |
| if isinstance(answer_value, (list, tuple)): |
| answer_value = answer_value[0] if answer_value else "" |
| original_answer = str(answer_value) |
| answer = select_answer_view(original_answer, args) |
| if not question or not answer: |
| raise ValueError( |
| f"row {source_index} cannot be converted: provide `text`, or question plus answer(s)" |
| ) |
| text = f"{qa_prompt(context, question)} {answer}" |
| return InputRecord( |
| source_index=source_index, |
| text=text, |
| question=question, |
| answer=answer, |
| context=context, |
| label=int(row["label"]) if row.get("label") is not None else None, |
| original_answer=original_answer, |
| ) |
|
|
|
|
| def iter_coqa(args: argparse.Namespace) -> Iterable[InputRecord]: |
| dataset = load_dataset( |
| "stanfordnlp/coqa", |
| split=args.split, |
| cache_dir=str(args.cache_dir / "datasets"), |
| ) |
| flat_index = 0 |
| emitted = 0 |
| stop = args.start_index + args.max_samples if args.max_samples else None |
| for sample in dataset: |
| story = sample["story"] |
| questions = sample["questions"] |
| answers = sample["answers"]["input_text"] |
| for question, answer in zip(questions, answers, strict=True): |
| if flat_index >= args.start_index and (stop is None or flat_index < stop): |
| selected_answer = select_answer_view(answer, args) |
| text = f"{qa_prompt(story, question)} {selected_answer}" |
| yield InputRecord( |
| source_index=flat_index, |
| text=text, |
| question=question, |
| answer=selected_answer, |
| context=story, |
| label=None, |
| original_answer=answer, |
| ) |
| emitted += 1 |
| flat_index += 1 |
| if stop is not None and flat_index >= stop: |
| return |
| if emitted == 0: |
| raise ValueError(f"start index {args.start_index} is outside flattened CoQA split") |
|
|
|
|
| def load_records(args: argparse.Namespace) -> list[InputRecord]: |
| if args.input_jsonl: |
| records: list[InputRecord] = [] |
| stop = args.start_index + args.max_samples if args.max_samples else None |
| with args.input_jsonl.open(encoding="utf-8") as handle: |
| for index, line in enumerate(handle): |
| if index < args.start_index: |
| continue |
| if stop is not None and index >= stop: |
| break |
| line = line.strip() |
| if line: |
| records.append(record_from_mapping(json.loads(line), index, args)) |
| return records |
| if args.dataset == "stanfordnlp/coqa": |
| return list(iter_coqa(args)) |
|
|
| dataset = load_dataset( |
| args.dataset, |
| split=args.split, |
| cache_dir=str(args.cache_dir / "datasets"), |
| ) |
| stop = args.start_index + args.max_samples if args.max_samples else len(dataset) |
| return [ |
| record_from_mapping(dict(dataset[index]), index, args) |
| for index in range(args.start_index, min(stop, len(dataset))) |
| ] |
|
|
|
|
| def assign_bucket(token_count: int, buckets: tuple[int, ...]) -> tuple[int, int]: |
| for bucket in buckets: |
| if token_count <= bucket: |
| return bucket, 0 |
| return buckets[-1], token_count - buckets[-1] |
|
|
|
|
| def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None: |
| tmp = path.with_suffix(path.suffix + ".tmp") |
| with tmp.open("w", encoding="utf-8") as handle: |
| for row in rows: |
| handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") |
| tmp.replace(path) |
|
|
|
|
| class LastTokenCapture: |
| """Capture only small last-position slices from the embedding and blocks.""" |
|
|
| def __init__(self, model: MistralModel): |
| self.embedding: torch.Tensor | None = None |
| self.layers: dict[int, torch.Tensor] = {} |
| self.handles = [model.embed_tokens.register_forward_hook(self._embedding_hook)] |
| |
| |
| for layer_index, layer in enumerate(model.layers[:-1]): |
| self.handles.append(layer.register_forward_hook(self._layer_hook(layer_index))) |
|
|
| def _embedding_hook(self, _module: Any, _inputs: Any, output: torch.Tensor) -> None: |
| self.embedding = output[:, -1, :].clone() |
|
|
| def _layer_hook(self, layer_index: int): |
| def hook(_module: Any, _inputs: Any, output: torch.Tensor) -> None: |
| self.layers[layer_index] = output[:, -1, :].clone() |
|
|
| return hook |
|
|
| def clear(self) -> None: |
| self.embedding = None |
| self.layers.clear() |
|
|
| def close(self) -> None: |
| for handle in self.handles: |
| handle.remove() |
|
|
|
|
| def extract_batch( |
| model: MistralModel, |
| capture: LastTokenCapture, |
| device: torch.device, |
| input_ids: torch.Tensor, |
| attention_mask: torch.Tensor, |
| ) -> tuple[torch.Tensor, torch.Tensor]: |
| capture.clear() |
| |
| |
| |
| with torch.no_grad(): |
| outputs = model( |
| input_ids=input_ids.to(device), |
| attention_mask=attention_mask.to(device), |
| use_cache=False, |
| return_dict=True, |
| ) |
| final_state = outputs.last_hidden_state[:, -1, :].clone() |
| if capture.embedding is None or len(capture.layers) != model.config.num_hidden_layers - 1: |
| raise RuntimeError("incomplete hook capture") |
| hidden = torch.stack( |
| [capture.layers[index] for index in range(model.config.num_hidden_layers - 1)] |
| + [final_state], |
| dim=1, |
| ) |
| |
| |
| packed = torch.cat((capture.embedding.unsqueeze(1), hidden), dim=1).cpu() |
| torch_xla.sync(wait=True) |
| return packed[:, 0].contiguous(), packed[:, 1:].contiguous() |
|
|
|
|
| def existing_source_indices(metadata_path: Path) -> set[int]: |
| if not metadata_path.exists(): |
| return set() |
| result: set[int] = set() |
| with metadata_path.open(encoding="utf-8") as handle: |
| for line in handle: |
| if line.strip(): |
| result.add(int(json.loads(line)["source_index"])) |
| return result |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| if args.batch_size < 1 or args.shard_size < args.batch_size: |
| raise ValueError("batch size must be positive and no larger than shard size") |
| buckets = tuple(sorted(set(args.buckets))) |
| if not buckets or buckets[0] < 1: |
| raise ValueError("buckets must contain positive lengths") |
|
|
| output_dir = args.output_dir.resolve() |
| shards_dir = output_dir / "states" / args.split |
| output_dir.mkdir(parents=True, exist_ok=True) |
| shards_dir.mkdir(parents=True, exist_ok=True) |
| inputs_path = output_dir / f"inputs-{args.split}.jsonl" |
| metadata_path = output_dir / f"metadata-{args.split}.jsonl" |
| manifest_path = output_dir / "manifest.json" |
|
|
| tokenizer = AutoTokenizer.from_pretrained( |
| args.model_id, |
| revision=args.revision, |
| cache_dir=str(args.cache_dir), |
| use_fast=True, |
| ) |
| tokenizer.pad_token_id = tokenizer.eos_token_id |
| tokenizer.padding_side = "left" |
| tokenizer.truncation_side = "left" |
|
|
| records = load_records(args) |
| if not records: |
| raise ValueError("no input records") |
| prepared: list[dict[str, Any]] = [] |
| by_bucket: dict[int, list[tuple[InputRecord, int, int]]] = defaultdict(list) |
| for record in records: |
| token_count = len(tokenizer(record.text, add_special_tokens=False)["input_ids"]) |
| bucket, truncated_tokens = assign_bucket(token_count, buckets) |
| by_bucket[bucket].append((record, token_count, truncated_tokens)) |
| prepared.append( |
| { |
| **asdict(record), |
| "input_sha256": hashlib.sha256(record.text.encode("utf-8")).hexdigest(), |
| "original_token_count": token_count, |
| "bucket_length": bucket, |
| "left_truncated_tokens": truncated_tokens, |
| } |
| ) |
| write_jsonl(inputs_path, prepared) |
|
|
| manifest: dict[str, Any] = { |
| "schema_version": 1, |
| "model_id": args.model_id, |
| "model_revision": args.revision, |
| "architecture": "MistralModel (LM head omitted)", |
| "source": str(args.input_jsonl) if args.input_jsonl else args.dataset, |
| "split": args.split, |
| "answer_mode": args.answer_mode, |
| "answer_view": args.answer_view, |
| "num_records": len(records), |
| "start_index": args.start_index, |
| "dtype": "bfloat16", |
| "embedding_shape_per_record": [4096], |
| "hidden_states_shape_per_record": [32, 4096], |
| "hidden_state_semantics": { |
| "0..30": "post-transformer-block, pre-final-RMSNorm", |
| "31": "post-transformer-block-31 and post-final-RMSNorm", |
| }, |
| "token_position": "last non-padding token (inputs are left padded)", |
| "use_cache": False, |
| "output_hidden_states": False, |
| "sequence_buckets": list(buckets), |
| "batch_size": args.batch_size, |
| "shard_size": args.shard_size, |
| "attn_implementation": args.attn_implementation, |
| "xla_no_special_scalars": os.environ["XLA_NO_SPECIAL_SCALARS"], |
| "python": sys.version, |
| "platform": platform.platform(), |
| "torch": torch.__version__, |
| "torch_xla": torch_xla.__version__, |
| "created_unix": time.time(), |
| "status": "prepared" if args.prepare_only else "extracting", |
| } |
| manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") |
| if args.prepare_only: |
| print(json.dumps({"status": "prepared", "records": len(records), "output": str(output_dir)})) |
| return |
|
|
| already_done = set() if args.overwrite else existing_source_indices(metadata_path) |
| if already_done: |
| print(f"Resuming: {len(already_done)} source indices already present") |
|
|
| device = torch_xla.device() |
| print(f"Loading {args.model_id}@{args.revision} as MistralModel BF16 on CPU") |
| model = MistralModel.from_pretrained( |
| args.model_id, |
| revision=args.revision, |
| cache_dir=str(args.cache_dir), |
| dtype=torch.bfloat16, |
| low_cpu_mem_usage=True, |
| attn_implementation=args.attn_implementation, |
| ) |
| model.config.use_cache = False |
| model.eval() |
| print(f"Moving base model (no LM head) to {device}") |
| model.to(device) |
| torch_xla.sync(wait=True) |
| capture = LastTokenCapture(model) |
|
|
| shard_number = 0 |
| if not args.overwrite: |
| existing_shards = sorted(shards_dir.glob("shard-*.safetensors")) |
| if existing_shards: |
| shard_number = max(int(path.stem.split("-")[-1]) for path in existing_shards) + 1 |
|
|
| pending_embeddings: list[torch.Tensor] = [] |
| pending_hidden: list[torch.Tensor] = [] |
| pending_meta: list[dict[str, Any]] = [] |
| all_metadata: list[dict[str, Any]] = [] |
| if metadata_path.exists() and not args.overwrite: |
| with metadata_path.open(encoding="utf-8") as handle: |
| all_metadata = [json.loads(line) for line in handle if line.strip()] |
|
|
| start_time = time.monotonic() |
| completed_this_run = 0 |
|
|
| def flush() -> None: |
| nonlocal shard_number |
| if not pending_meta: |
| return |
| shard_name = f"shard-{shard_number:05d}.safetensors" |
| shard_path = shards_dir / shard_name |
| tensors = { |
| "embedding": torch.cat(pending_embeddings, dim=0).to(torch.bfloat16), |
| "hidden_states": torch.cat(pending_hidden, dim=0).to(torch.bfloat16), |
| } |
| save_file( |
| tensors, |
| str(shard_path), |
| metadata={ |
| "model_id": args.model_id, |
| "model_revision": args.revision, |
| "split": args.split, |
| "dtype": "bfloat16", |
| }, |
| ) |
| for offset, row in enumerate(pending_meta): |
| row["shard"] = f"states/{args.split}/{shard_name}" |
| row["offset"] = offset |
| row["embedding_key"] = "embedding" |
| row["hidden_states_key"] = "hidden_states" |
| all_metadata.extend(pending_meta) |
| write_jsonl(metadata_path, all_metadata) |
| print(f"Saved {shard_path.name}: {len(pending_meta)} records") |
| pending_embeddings.clear() |
| pending_hidden.clear() |
| pending_meta.clear() |
| shard_number += 1 |
|
|
| try: |
| for bucket in buckets: |
| bucket_records = [item for item in by_bucket.get(bucket, []) if item[0].source_index not in already_done] |
| if not bucket_records: |
| continue |
| print(f"Bucket {bucket}: {len(bucket_records)} records") |
| for start in range(0, len(bucket_records), args.batch_size): |
| batch_items = bucket_records[start : start + args.batch_size] |
| |
| |
| actual_size = len(batch_items) |
| while len(batch_items) < args.batch_size: |
| batch_items.append(batch_items[-1]) |
| texts = [item[0].text for item in batch_items] |
| encoded = tokenizer( |
| texts, |
| add_special_tokens=False, |
| padding="max_length", |
| truncation=True, |
| max_length=bucket, |
| return_tensors="pt", |
| ) |
| embeddings, hidden = extract_batch( |
| model, |
| capture, |
| device, |
| encoded["input_ids"], |
| encoded["attention_mask"], |
| ) |
| embeddings = embeddings[:actual_size] |
| hidden = hidden[:actual_size] |
| pending_embeddings.append(embeddings) |
| pending_hidden.append(hidden) |
| for local_index, (record, token_count, truncated_tokens) in enumerate(batch_items[:actual_size]): |
| last_token_id = int(encoded["input_ids"][local_index, -1]) |
| pending_meta.append( |
| { |
| "source_index": record.source_index, |
| "input_sha256": hashlib.sha256(record.text.encode("utf-8")).hexdigest(), |
| "original_token_count": token_count, |
| "bucket_length": bucket, |
| "left_truncated_tokens": truncated_tokens, |
| "last_token_id": last_token_id, |
| "last_token": tokenizer.decode([last_token_id]), |
| } |
| ) |
| completed_this_run += actual_size |
| if len(pending_meta) >= args.shard_size: |
| flush() |
| if completed_this_run % 10 == 0: |
| rate = completed_this_run / max(time.monotonic() - start_time, 1e-9) |
| print(f"Progress: {completed_this_run}/{len(records) - len(already_done)} ({rate:.2f} records/s)") |
| flush() |
| finally: |
| capture.close() |
|
|
| manifest["status"] = "complete" |
| manifest["completed_records"] = len(all_metadata) |
| manifest["num_shards"] = shard_number |
| manifest["elapsed_seconds_this_run"] = time.monotonic() - start_time |
| manifest["completed_unix"] = time.time() |
| manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") |
| del model |
| gc.collect() |
| print(json.dumps({"status": "complete", "records": len(all_metadata), "output": str(output_dir)})) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|