MCPcopy Create free account
hub / github.com/OpenSparseLLMs/MoM / tokenize

Function tokenize

training/preprocess.py:17–61  ·  view source on GitHub ↗

Tokenize the input text and split into chunks of specified context length. Args: examples: Dictionary containing the input text. tokenizer: Initialized tokenizer. seq_len: Total sequence length for each training sample. Default: 2

(
    examples: Dict[str, List[Any]],
    tokenizer: AutoTokenizer,
    seq_len: int = 2048,
    ctx_len: int = None,
    return_offsets: bool = False
)

Source from the content-addressed store, hash-verified

15
16
17def tokenize(
18 examples: Dict[str, List[Any]],
19 tokenizer: AutoTokenizer,
20 seq_len: int = 2048,
21 ctx_len: int = None,
22 return_offsets: bool = False
23) -> Dict[str, List[List[int]]]:
24 """
25 Tokenize the input text and split into chunks of specified context length.
26
27 Args:
28 examples:
29 Dictionary containing the input text.
30 tokenizer:
31 Initialized tokenizer.
32 seq_len:
33 Total sequence length for each training sample. Default: 2048.
34 ctx_len:
35 Max contiguous length to preserve (will not be split). Default: `None`.
36 return_offsets:
37 Return cumulative offsets for concatenated inputs. Default: `False`.
38
39 Returns:
40 Dictionary containing tokenized and chunked input ids, and optionally offsets.
41 """
42 text = examples['text']
43 input_ids = tokenizer(text)['input_ids']
44 # further split each input into chunks of length `ctx_len` if provided
45 if ctx_len is not None:
46 input_ids = [seq[i:i+ctx_len] for seq in input_ids for i in range(0, len(seq), ctx_len)]
47 lens = torch.tensor([len(seq) for seq in input_ids]).cumsum(0)
48 total_len = lens[-1] // seq_len * seq_len
49
50 input_ids = list(chain(*input_ids))
51 # each yielded sample is of length `seq_len`
52 input_ids = [input_ids[i:i+seq_len] for i in range(0, total_len, seq_len)]
53
54 if not return_offsets:
55 return {'input_ids': input_ids}
56
57 # insert boundaries into cumulative offsets
58 offsets = torch.cat((lens, torch.arange(0, total_len, seq_len))).unique().sort()[0] % seq_len
59 # split offsets according the start positions
60 offsets = [i.tolist() + [seq_len] for i in offsets.tensor_split(torch.where(offsets.eq(0))[0][1:])][:len(input_ids)]
61 return {'input_ids': input_ids, 'offsets': offsets}
62
63
64def preprocess(

Callers 1

preprocessFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected