File size: 3,521 Bytes
0da40b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# SELFIES Tokenizer Documentation

## Overview
This tokenizer is designed specifically for SELFIES (Self-Referencing Embedded Strings) chemical structure notation. It provides a simple mapping between SELFIES tokens and their corresponding IDs for machine learning applications.

## File Format
The tokenizer configuration is stored in a JSON file with the following structure:
```json
{
  "vocab": {
    "[UNK]": 0,
    "[CLS]": 1,
    "[SEP]": 2,
    "[PAD]": 3,
    "[MASK]": 4,
    // ... chemical tokens ...
  },
  "special_tokens": {
    "unk_token": "[UNK]",
    "cls_token": "[CLS]",
    "sep_token": "[SEP]",
    "pad_token": "[PAD]",
    "mask_token": "[MASK]"
  },
  "model_max_length": 512
}
```

## Special Tokens
- `[UNK]`: Used for unknown tokens (ID: 0)
- `[CLS]`: Classification token, added at start of sequence (ID: 1)
- `[SEP]`: Separator token, added at end of sequence (ID: 2)
- `[PAD]`: Padding token (ID: 3)
- `[MASK]`: Masking token for masked language modeling (ID: 4)

## Tokenization Process
Since SELFIES strings are already tokenized by design, the process is straightforward:

1. Split the SELFIES string into tokens (they are naturally delimited by `[]`)
2. Convert each token to its corresponding ID using the vocab mapping
3. Add special tokens as needed ([CLS] at start, [SEP] at end)
4. Pad/truncate to model_max_length if necessary

Example implementation:
```python
import re

class SelfiesTokenizer:
    def __init__(self, tokenizer_path):
        with open(tokenizer_path, 'r') as f:
            config = json.load(f)
        self.vocab = config['vocab']
        self.special_tokens = config['special_tokens']
        self.max_length = config['model_max_length']
        # Create reverse mapping (id -> token) for decoding
        self.id2token = {v: k for k, v in self.vocab.items()}
    
    def tokenize(self, selfies_string):
        """Split SELFIES string into tokens"""
        return re.findall(r'\[.*?\]', selfies_string)
    
    def convert_tokens_to_ids(self, tokens):
        """Convert tokens to their IDs"""
        return [self.vocab.get(token, self.vocab['[UNK]']) for token in tokens]
    
    def encode(self, selfies_string, add_special_tokens=True):
        """Full encoding process"""
        tokens = self.tokenize(selfies_string)
        ids = self.convert_tokens_to_ids(tokens)
        
        if add_special_tokens:
            ids = [self.vocab['[CLS]']] + ids + [self.vocab['[SEP]']]
        
        # Truncate or pad as needed
        if len(ids) > self.max_length:
            ids = ids[:self.max_length]
        else:
            ids.extend([self.vocab['[PAD]']] * (self.max_length - len(ids)))
            
        return ids
    
    def decode(self, ids):
        """Convert IDs back to SELFIES string"""
        tokens = [self.id2token[id] for id in ids]
        # Remove special tokens
        tokens = [t for t in tokens if t not in self.special_tokens.values()]
        return ''.join(tokens)
```

## Usage Example
```python
# Initialize tokenizer
tokenizer = SelfiesTokenizer('tokenizer.json')

# Encode a SELFIES string
selfies = '[C][=C][C][=C][O][H]'
ids = tokenizer.encode(selfies)

# Decode back to SELFIES
decoded = tokenizer.decode(ids)
```

## Notes
- The tokenizer assumes well-formed SELFIES strings as input
- No additional preprocessing is needed since SELFIES tokens are already well-defined
- The vocab mapping preserves IDs from the original tokenizer where possible
- Maximum sequence length is set to 512 tokens by default