Download src/pat/packing.py from ICLRPAT27/PAT-code: direct link, hf CLI and curl.
- Browser
- Download file 6.61 kB
-
https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/packing.py
- Command line
-
hf download hf://ICLRPAT27/PAT-code/src/pat/packing.py
-
curl -L -o packing.py https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/packing.py
6.61 kB
| """Document-local framing, fixed chunks, and next-token supervision. | |
| Input pieces contain content IDs, followed by EOD only when the original | |
| document ends. Each piece gets one BOS; PAT also appends summary rows after | |
| each chunk. Targets follow the original token stream across chunk boundaries, | |
| and never cross a piece boundary or train the appended summary rows. | |
| """ | |
| from __future__ import annotations | |
| from collections.abc import Sequence | |
| from dataclasses import dataclass | |
| import torch | |
| from .config import BOS_ID, EOC_ID, EOD_ID, PATConfig | |
| class PackedBatch: | |
| token_ids: torch.Tensor | |
| lexical_positions: torch.Tensor | |
| source_indices: torch.Tensor | |
| targets: torch.Tensor | |
| piece_lengths: tuple[int, ...] | |
| row_lengths: tuple[int, ...] | |
| row_content_lengths: tuple[int, ...] | |
| row_offsets: tuple[int, ...] | |
| chunk_piece_ids: tuple[int, ...] | |
| piece_chunk_bases: tuple[int, ...] | |
| chunks_per_piece: tuple[int, ...] | |
| eoc_positions: tuple[tuple[int, ...], ...] | |
| def token_count(self) -> int: | |
| return self.targets.numel() | |
| def lexical_token_count(self) -> int: | |
| return int(self.targets.ne(EOD_ID).sum().item()) | |
| def geometry(self, config: PATConfig): | |
| from .kernels.attention import FixedGeometry | |
| device = self.token_ids.device | |
| tensor = lambda values: torch.tensor(values, device=device, dtype=torch.long) | |
| key = ( | |
| "packed_training", | |
| True, | |
| len(self.row_lengths), | |
| max(self.row_lengths), | |
| self.token_ids.numel(), | |
| config.chunk_size, | |
| config.memory_slots[0], | |
| config.max_memory_size, | |
| self.chunks_per_piece, | |
| tuple( | |
| (i, size) | |
| for i, size in enumerate(self.row_content_lengths) | |
| if size != config.chunk_size | |
| ), | |
| ) | |
| return FixedGeometry( | |
| row_offsets=tensor(self.row_offsets), | |
| row_lengths=tensor(self.row_lengths), | |
| row_content_lengths=tensor(self.row_content_lengths), | |
| chunk_piece_id=tensor(self.chunk_piece_ids), | |
| piece_chunk_base=tensor(self.piece_chunk_bases), | |
| eoc_abs_idx=tensor(self.eoc_positions), | |
| token_count=self.token_ids.numel(), | |
| max_row_length=max(self.row_lengths), | |
| max_chunk_index=max(self.chunks_per_piece) - 1, | |
| planner_cache_key=key, | |
| ) | |
| def pack_pieces( | |
| pieces: Sequence[torch.Tensor], | |
| config: PATConfig, | |
| *, | |
| device: torch.device, | |
| document_ends: Sequence[bool] | None = None, | |
| for_inference: bool = False, | |
| ) -> PackedBatch: | |
| if not pieces: | |
| raise ValueError("at least one document piece is required") | |
| if document_ends is not None and len(document_ends) != len(pieces): | |
| raise ValueError("document_ends needs one flag per piece") | |
| token_parts, targets, sources, lexical_positions = [], [], [], [] | |
| ( | |
| row_lengths, | |
| row_contents, | |
| row_offsets, | |
| chunk_piece_ids, | |
| piece_bases, | |
| chunk_counts, | |
| eoc_positions, | |
| ) = [], [], [], [], [], [], [] | |
| piece_lengths = [] | |
| physical_cursor = lexical_cursor = 0 | |
| slots = config.memory_slots[0] | |
| for index, piece in enumerate(pieces): | |
| if piece.ndim != 1 or piece.dtype not in {torch.int32, torch.int64}: | |
| raise ValueError("pieces must be rank-one integer tensors") | |
| piece = piece.to(device=device, dtype=torch.long) | |
| # Every input token is either content or the final EOD. This prevents | |
| # accidental double framing when importing tokenized corpora. | |
| if piece.numel() and bool(((piece < 0) | (piece > EOD_ID)).any().item()): | |
| raise ValueError("input pieces may contain only content IDs and terminal EOD") | |
| ends = bool(piece.numel() and piece[-1].item() == EOD_ID) | |
| if piece.numel() > 1 and bool(piece[:-1].eq(EOD_ID).any().item()): | |
| raise ValueError("EOD may appear only at a document's end") | |
| if document_ends is not None and bool(document_ends[index]) != ends: | |
| raise ValueError("document_ends must agree with the terminal EOD token") | |
| if piece.numel() - int(ends) > config.context_length: | |
| raise ValueError("piece exceeds context_length; split it before batching") | |
| if config.architecture == "FA" and not for_inference: | |
| if not piece.numel(): | |
| raise ValueError("FA training needs at least one target per piece") | |
| # The final target has no following target of its own. Omitting | |
| # that unused input preserves the producer's FlashAttention and | |
| # projection shapes, including their finite-precision arithmetic. | |
| framed = torch.cat((piece.new_tensor([BOS_ID]), piece[:-1])) | |
| else: | |
| framed = torch.cat((piece.new_tensor([BOS_ID]), piece)) | |
| length = framed.numel() | |
| piece_lengths.append(length) | |
| targets.append(piece) | |
| sources.extend(range(lexical_cursor, lexical_cursor + piece.numel())) | |
| lexical_cursor += length | |
| piece_bases.append(len(row_lengths)) | |
| count = 0 | |
| step = config.chunk_size if config.architecture == "PAT" else length | |
| for start in range(0, length, step): | |
| row = framed[start : start + step] | |
| size = row.numel() | |
| row_offsets.append(physical_cursor) | |
| row_contents.append(size) | |
| row_lengths.append(size + slots) | |
| chunk_piece_ids.append(index) | |
| lexical_positions.extend(range(physical_cursor, physical_cursor + size)) | |
| tail = tuple(range(physical_cursor + size, physical_cursor + size + slots)) | |
| eoc_positions.append(tail) | |
| token_parts.append(torch.cat((row, row.new_full((slots,), EOC_ID)))) | |
| physical_cursor += size + slots | |
| count += 1 | |
| chunk_counts.append(count) | |
| return PackedBatch( | |
| token_ids=torch.cat(token_parts), | |
| lexical_positions=torch.tensor(lexical_positions, device=device), | |
| source_indices=torch.tensor(sources, device=device, dtype=torch.long), | |
| targets=torch.cat(targets), | |
| piece_lengths=tuple(piece_lengths), | |
| row_lengths=tuple(row_lengths), | |
| row_content_lengths=tuple(row_contents), | |
| row_offsets=tuple(row_offsets), | |
| chunk_piece_ids=tuple(chunk_piece_ids), | |
| piece_chunk_bases=tuple(piece_bases), | |
| chunks_per_piece=tuple(chunk_counts), | |
| eoc_positions=tuple(eoc_positions), | |
| ) | |