File size: 2,306 Bytes
86e3bb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import numpy as np
import torch

from kawk50m.binary_dataset import PackedTokenDataset


def test_dataset_builds_causal_lm_batches_and_epoch_permutation(tmp_path) -> None:
    token_path = tmp_path / "tokens.bin"
    np.arange(21, dtype=np.uint16).tofile(token_path)
    dataset = PackedTokenDataset(token_path, sequence_length=4)

    assert len(dataset) == 5
    inputs, labels = dataset.evaluation_batch(
        batch_index=0,
        batch_size=2,
        rank=0,
        world_size=1,
        device=torch.device("cpu"),
    )
    assert inputs.tolist() == [[0, 1, 2, 3], [4, 5, 6, 7]]
    # Hugging Face causal-LM heads shift labels internally. Returning an
    # already shifted target here would train the model to predict x[t+2].
    assert labels.tolist() == inputs.tolist()
    assert labels.data_ptr() != inputs.data_ptr()

    visited = []
    for micro_step in range(len(dataset)):
        train_inputs, _ = dataset.training_batch(
            micro_step=micro_step,
            batch_size=1,
            rank=0,
            world_size=1,
            seed=42,
            device=torch.device("cpu"),
        )
        visited.append(train_inputs[0, 0].item() // 4)
    assert sorted(visited) == list(range(len(dataset)))

    offset_inputs, _ = dataset.training_batch(
        micro_step=0,
        batch_size=1,
        rank=0,
        world_size=1,
        seed=42,
        sample_offset=1,
        device=torch.device("cpu"),
    )
    next_inputs, _ = dataset.training_batch(
        micro_step=1,
        batch_size=1,
        rank=0,
        world_size=1,
        seed=42,
        device=torch.device("cpu"),
    )
    assert offset_inputs.tolist() == next_inputs.tolist()


def test_dataset_reads_multiple_binary_shards_from_glob(tmp_path) -> None:
    np.arange(9, dtype=np.uint16).tofile(tmp_path / "part-000.bin")
    np.arange(100, 109, dtype=np.uint16).tofile(tmp_path / "part-001.bin")

    dataset = PackedTokenDataset(
        str(tmp_path / "part-*.bin"),
        sequence_length=4,
    )

    assert len(dataset) == 4
    assert dataset.sequence(0).tolist() == [0, 1, 2, 3, 4]
    assert dataset.sequence(1).tolist() == [4, 5, 6, 7, 8]
    assert dataset.sequence(2).tolist() == [100, 101, 102, 103, 104]
    assert dataset.sequence(3).tolist() == [104, 105, 106, 107, 108]