text stringlengths 1 93.6k |
|---|
f.extractall(data_dir)
|
os.remove(data_dir / "text8.zip")
|
data = (data_dir / "text8").read_text()
|
# get all the unique characters that occur in this text
|
chars = sorted(list(set(data)))
|
vocab_size = len(chars)
|
print("all the unique characters:", "".join(chars))
|
print(f"vocab size: {vocab_size:,}")
|
# create a mapping from characters to integers
|
stoi = {ch: i for i, ch in enumerate(chars)}
|
itos = {i: ch for i, ch in enumerate(chars)}
|
def encode(s):
|
return [stoi[c] for c in s] # encoder: take a string, output a list of integers
|
# encode both to integers
|
n = len(data)
|
train_data = data[: int(n * 0.9)]
|
val_data = data[int(n * 0.9) : int(n * 0.95)]
|
test_data = data[int(n * 0.95) :]
|
train_ids = encode(train_data)
|
val_ids = encode(val_data)
|
test_ids = encode(test_data)
|
print(f"train has {len(train_ids):,} tokens")
|
print(f"val has {len(val_ids):,} tokens")
|
print(f"test has {len(test_ids):,} tokens")
|
# export to bin files
|
train_ids = np.array(train_ids, dtype=np.uint16)
|
val_ids = np.array(val_ids, dtype=np.uint16)
|
test_ids = np.array(test_ids, dtype=np.uint16)
|
train_ids.tofile(data_dir / "train.bin")
|
val_ids.tofile(data_dir / "val.bin")
|
test_ids.tofile(data_dir / "test.bin")
|
print(f"Saved to {data_dir / 'train.bin'}, {data_dir / 'val.bin'}, {data_dir / 'test.bin'}")
|
# save the meta information as well, to help us encode/decode later
|
meta = {
|
"vocab_size": vocab_size,
|
"itos": itos,
|
"stoi": stoi,
|
}
|
with open(os.path.join(data_dir / "meta.pkl"), "wb") as f:
|
pickle.dump(meta, f)
|
print(f"text8 dataset downloaded and prepared in dir {data_dir}")
|
class Text8Dataset(Dataset):
|
def __init__(self, data_dir: Union[str, pathlib.Path], split: str, download: bool, seq_len: int):
|
"""
|
seq_len should include context length. Example: seq_len=512 for modeling 256 chars with 256 char of context.
|
context is only used for correct preparation of val/test sets.
|
"""
|
self.root_dir = pathlib.Path(data_dir)
|
self.split = split
|
self.seq_len = seq_len
|
fname = {"train": "train.bin", "val": "val.bin", "test": "test.bin"}[self.split]
|
assert self.split in ["train", "val", "test"]
|
data_dir = self.root_dir / "text8"
|
if not os.path.exists(data_dir):
|
if download:
|
prepare_text8(data_dir)
|
else:
|
raise NotADirectoryError(f"dir {data_dir} does not exist and download is False")
|
self.data = np.memmap(data_dir / fname, np.uint16, "r")
|
def __getitem__(self, index) -> torch.Tensor:
|
seq = torch.from_numpy(self.data[index : index + self.seq_len].astype(np.int64))
|
return seq
|
def __len__(self):
|
return self.data.size - self.seq_len
|
def char_ids_to_str(char_ids: Union[list[int], np.array, torch.Tensor]) -> str:
|
"""Decode a 1D sequence of character IDs to a string."""
|
return "".join([TEXT8_CHARS[i] for i in char_ids])
|
def batch_to_str(text_batch: Union[list[list], np.array, torch.Tensor]) -> list[str]:
|
"""Decode a batch of character IDs to a list of strings."""
|
return [char_ids_to_str(row_char_ids) for row_char_ids in text_batch]
|
def batch_to_images(image_batch: torch.Tensor, ncols: int = None) -> plt.Figure:
|
if ncols is None:
|
ncols = math.ceil(math.sqrt(len(image_batch)))
|
if image_batch.size(-1) == 3: # for color images (CIFAR-10)
|
image_batch = (image_batch + 1) / 2
|
grid = make_grid(image_batch.permute(0, 3, 1, 2), ncols, pad_value=1).permute(1, 2, 0)
|
fig = plt.figure(figsize=(grid.size(1) / 30, grid.size(0) / 30))
|
plt.imshow(grid.cpu().clip(min=0, max=1), interpolation="nearest")
|
plt.grid(False)
|
plt.axis("off")
|
return fig
|
# <FILESEP>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.