MCPcopy Create free account
hub / github.com/ModalityDance/Omni-R1 / Trie

Class Trie

src/transformers/src/transformers/tokenization_utils.py:53–281  ·  view source on GitHub ↗

Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass Loose reference https://en.wikipedia.org/wiki/Trie

Source from the content-addressed store, hash-verified

51
52
53class Trie:
54 """
55 Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass
56 Loose reference https://en.wikipedia.org/wiki/Trie
57 """
58
59 def __init__(self, *args):
60 self.data = {}
61 self._tokens = set()
62 self._termination_char = ""
63 self.update(*args)
64
65 def update(self, *args):
66 """
67 Updates the Trie with new tokens provided as arguments.
68
69 Args:
70 *args: Variable number of words to be added to the Trie.
71 """
72 for token in tuple(*args):
73 self.add(token)
74
75 def add(self, word: str):
76 """
77 Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation.
78 The special key `""` in `self._termination_char` is used to represent termination.
79
80 This function is idempotent, adding twice the same word will leave the trie unchanged
81
82 Example:
83
84 ```python
85 >>> trie = Trie()
86 >>> trie.add("Hello 友達")
87 >>> trie.data
88 {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}
89
90 >>> trie.add("Hello")
91 >>> trie.data
92 {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}
93 ```
94 """
95 if not word:
96 # Prevent empty string
97 return
98
99 self._tokens.add(word)
100 ref = self.data
101 for char in word:
102 ref[char] = ref.setdefault(char, {})
103 ref = ref[char]
104 ref[self._termination_char] = 1
105
106 def split(self, text: str) -> List[str]:
107 """
108 Will look for the words added to the trie within `text`. Output is the original string splitted along the
109 boundaries of the words found.
110

Callers 9

test_trieMethod · 0.90
test_trie_splitMethod · 0.90
test_trie_singleMethod · 0.90
test_trie_finalMethod · 0.90
test_trie_subtokensMethod · 0.90
test_trie_skipMethod · 0.90
__init__Method · 0.85

Calls

no outgoing calls

Tested by 8

test_trieMethod · 0.72
test_trie_splitMethod · 0.72
test_trie_singleMethod · 0.72
test_trie_finalMethod · 0.72
test_trie_subtokensMethod · 0.72
test_trie_skipMethod · 0.72