Skip to content

Commit 115f198

Browse files
authored
Tokenizer test (#8)
* tokenizer test * format fix
1 parent 04d96fd commit 115f198

File tree

5 files changed

+281
-3
lines changed

5 files changed

+281
-3
lines changed

src/transformers/models/auto/tokenization_auto.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,6 @@
141141
"cohere",
142142
(None, "CohereTokenizerFast" if is_tokenizers_available() else None),
143143
),
144-
145144
("convbert", ("ConvBertTokenizer", "ConvBertTokenizerFast" if is_tokenizers_available() else None)),
146145
(
147146
"cpm",

src/transformers/models/cohere/tokenization_cohere_fast.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,8 @@ def __init__(
118118
):
119119
if add_prefix_space is not None:
120120
logger.warning_once(
121-
"You set `add_prefix_space`. The tokenizer needs to be converted from the slow tokenizers"
121+
"You set `add_prefix_space`. The tokenizer needs to be converted from the slow tokenizers but Cohere tokenizer does not have a slow tokenizer. The `add_prefix_space` argument will be ignored."
122122
)
123-
kwargs["from_slow"] = True
124123

125124
super().__init__(
126125
vocab_file=vocab_file,

tests/models/cohere/__init__.py

Whitespace-only changes.

tests/models/cohere/test_modeling_cohere.py

Whitespace-only changes.
Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
# coding=utf-8
2+
# Copyright 2022 The HuggingFace Team. All rights reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
import unittest
17+
18+
from transformers import CohereTokenizerFast
19+
from transformers.testing_utils import require_jinja, require_tokenizers
20+
21+
from ...test_tokenization_common import TokenizerTesterMixin
22+
23+
24+
@require_tokenizers
25+
class CohereTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
26+
slow_tokenizer_class = None
27+
rust_tokenizer_class = CohereTokenizerFast
28+
tokenizer_class = CohereTokenizerFast
29+
test_rust_tokenizer = True
30+
test_slow_tokenizer = False
31+
from_pretrained_vocab_key = "tokenizer_file"
32+
special_tokens_map = {
33+
"bos_token": "<BOS_TOKEN>",
34+
"eos_token": "<|END_OF_TURN_TOKEN|>",
35+
"unk_token": "<UNK>",
36+
"pad_token": "<PAD>",
37+
}
38+
39+
def setUp(self):
40+
super().setUp()
41+
tokenizer = CohereTokenizerFast.from_pretrained("CohereForAI/c4ai-command-r-v01")
42+
tokenizer.save_pretrained(self.tmpdirname)
43+
44+
def get_rust_tokenizer(self, **kwargs):
45+
kwargs.update(self.special_tokens_map)
46+
return CohereTokenizerFast.from_pretrained(self.tmpdirname, **kwargs)
47+
48+
@unittest.skip("This needs a slow tokenizer. Cohere does not have one!")
49+
def test_encode_decode_with_spaces(self):
50+
return
51+
52+
def test_encodings_from_sample_data(self):
53+
"""
54+
Assert that the created tokens are the same than the hard-coded ones
55+
"""
56+
tokenizer = self.get_rust_tokenizer()
57+
58+
INPUT_SENTENCES = ["The quick brown fox<|END_OF_TURN_TOKEN|>", "jumps over the lazy dog<|END_OF_TURN_TOKEN|>"]
59+
TARGET_TOKENS = [[5, 2162, 6629, 19883, 73388, 255001], [5, 81, 25092, 2515, 1690, 46189, 9507, 255001]]
60+
61+
computed_tokens = tokenizer.batch_encode_plus(INPUT_SENTENCES)["input_ids"]
62+
self.assertListEqual(TARGET_TOKENS, computed_tokens)
63+
64+
decoded_tokens = tokenizer.batch_decode(computed_tokens)
65+
self.assertListEqual(decoded_tokens, INPUT_SENTENCES)
66+
67+
def test_padding(self, max_length=10):
68+
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
69+
with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
70+
tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
71+
# tokenizer_r.pad_token = None # Hotfixing padding = None
72+
# Simple input
73+
s = "This is a simple input"
74+
s2 = ["This is a simple input 1", "This is a simple input 2"]
75+
p = ("This is a simple input", "This is a pair")
76+
p2 = [
77+
("This is a simple input 1", "This is a simple input 2"),
78+
("This is a simple pair 1", "This is a simple pair 2"),
79+
]
80+
81+
# Simple input tests
82+
try:
83+
tokenizer_r.encode(s, max_length=max_length)
84+
tokenizer_r.encode_plus(s, max_length=max_length)
85+
86+
tokenizer_r.batch_encode_plus(s2, max_length=max_length)
87+
tokenizer_r.encode(p, max_length=max_length)
88+
tokenizer_r.batch_encode_plus(p2, max_length=max_length)
89+
except ValueError:
90+
self.fail("Cohere Tokenizer should be able to deal with padding")
91+
92+
tokenizer_r.pad_token = None # Hotfixing padding = None
93+
self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length")
94+
95+
# Simple input
96+
self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length")
97+
98+
# Simple input
99+
self.assertRaises(
100+
ValueError,
101+
tokenizer_r.batch_encode_plus,
102+
s2,
103+
max_length=max_length,
104+
padding="max_length",
105+
)
106+
107+
# Pair input
108+
self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length")
109+
110+
# Pair input
111+
self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length")
112+
113+
# Pair input
114+
self.assertRaises(
115+
ValueError,
116+
tokenizer_r.batch_encode_plus,
117+
p2,
118+
max_length=max_length,
119+
padding="max_length",
120+
)
121+
122+
@require_jinja
123+
def test_tokenization_for_chat(self):
124+
tokenizer = self.get_rust_tokenizer()
125+
test_chats = [
126+
[{"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}],
127+
[
128+
{"role": "system", "content": "You are a helpful chatbot."},
129+
{"role": "user", "content": "Hello!"},
130+
{"role": "assistant", "content": "Nice to meet you."},
131+
],
132+
]
133+
tokenized_chats = [tokenizer.apply_chat_template(test_chat) for test_chat in test_chats]
134+
expected_tokens = [
135+
[5, 255000, 255008, 5659, 1955, 1671, 19264, 171597, 21, 255001, 255000, 255006, 28339, 8, 255001],
136+
[
137+
5,
138+
255000,
139+
255008,
140+
5659,
141+
1955,
142+
1671,
143+
19264,
144+
171597,
145+
21,
146+
255001,
147+
255000,
148+
255006,
149+
28339,
150+
8,
151+
255001,
152+
255000,
153+
255007,
154+
97190,
155+
1726,
156+
5694,
157+
1933,
158+
21,
159+
255001,
160+
],
161+
]
162+
for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens):
163+
self.assertListEqual(tokenized_chat, expected_tokens)
164+
165+
@require_jinja
166+
def test_tokenization_for_tool_use(self):
167+
tokenizer = self.get_rust_tokenizer()
168+
169+
conversation = [{"role": "user", "content": "Whats the biggest penguin in the world?"}]
170+
171+
tools = [
172+
{
173+
"name": "internet_search",
174+
"description": "Returns a list of relevant document snippets for a textual query retrieved from the internet",
175+
"parameter_definitions": {
176+
"query": {"description": "Query to search the internet with", "type": "str", "required": True}
177+
},
178+
},
179+
{
180+
"name": "directly_answer",
181+
"description": "Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history",
182+
"parameter_definitions": {},
183+
},
184+
]
185+
186+
tool_use_prompt = tokenizer.apply_tool_use_template(
187+
conversation,
188+
tools=tools,
189+
tokenize=False,
190+
add_generation_prompt=True,
191+
)
192+
193+
expected_prompt = '''<BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
194+
The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.
195+
196+
# System Preamble
197+
## Basic Rules
198+
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.
199+
200+
# User Preamble
201+
## Task and Context
202+
You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
203+
204+
## Style Guide
205+
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.
206+
207+
## Available Tools
208+
Here is a list of tools that you have available to you:
209+
210+
```python
211+
def internet_search(query: str) -> List[Dict]:
212+
"""Returns a list of relevant document snippets for a textual query retrieved from the internet
213+
214+
Args:
215+
query (str): Query to search the internet with
216+
"""
217+
pass
218+
```
219+
220+
```python
221+
def directly_answer() -> List[Dict]:
222+
"""Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history
223+
"""
224+
pass
225+
```<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Write 'Action:' followed by a json-formatted list of actions that you want to perform in order to produce a good response to the user's last input. You can use any of the supplied tools any number of times, but you should aim to execute the minimum number of necessary actions for the input. You should use the `directly-answer` tool if calling the other tools is unnecessary. The list of actions you want to call should be formatted as a list of json objects, for example:
226+
```json
227+
[
228+
{
229+
"tool_name": title of the tool in the specification,
230+
"parameters": a dict of parameters to input into the tool as they are defined in the specs, or {} if it takes no parameters
231+
}
232+
]```<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>'''
233+
234+
self.assertEqual(tool_use_prompt, expected_prompt)
235+
236+
@require_jinja
237+
def test_tokenization_for_grounded_generation(self):
238+
tokenizer = self.get_rust_tokenizer()
239+
conversation = [{"role": "user", "content": "Whats the biggest penguin in the world?"}]
240+
241+
documents = [
242+
{"title": "Tall penguins", "text": "Emperor penguins are the tallest growing up to 122 cm in height."},
243+
{"title": "Penguin habitats", "text": "Emperor penguins only live in Antarctica."},
244+
]
245+
246+
grounded_generation_prompt = tokenizer.apply_grounded_generation_template(
247+
conversation,
248+
documents=documents,
249+
citation_mode="accurate", # or "fast"
250+
tokenize=False,
251+
add_generation_prompt=True,
252+
)
253+
254+
expected_prompt = """<BOS_TOKEN><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|># Safety Preamble
255+
The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.
256+
257+
# System Preamble
258+
## Basic Rules
259+
You are a powerful conversational AI trained by Cohere to help people. You are augmented by a number of tools, and your job is to use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see a specific instruction instructing you what kind of response to generate. When you answer the user's requests, you cite your sources in your answers, according to those instructions.
260+
261+
# User Preamble
262+
## Task and Context
263+
You help people answer their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You should focus on serving the user's needs as best you can, which will be wide-ranging.
264+
265+
## Style Guide
266+
Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|USER_TOKEN|>Whats the biggest penguin in the world?<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|><results>
267+
Document: 0
268+
title: Tall penguins
269+
text: Emperor penguins are the tallest growing up to 122 cm in height.
270+
271+
Document: 1
272+
title: Penguin habitats
273+
text: Emperor penguins only live in Antarctica.
274+
</results><|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>Carefully perform the following instructions, in order, starting each with a new line.
275+
Firstly, Decide which of the retrieved documents are relevant to the user's last input by writing 'Relevant Documents:' followed by comma-separated list of document numbers. If none are relevant, you should instead write 'None'.
276+
Secondly, Decide which of the retrieved documents contain facts that should be cited in a good answer to the user's last input by writing 'Cited Documents:' followed a comma-separated list of document numbers. If you dont want to cite any of them, you should instead write 'None'.
277+
Thirdly, Write 'Answer:' followed by a response to the user's last input in high quality natural english. Use the retrieved documents to help you. Do not insert any citations or grounding markup.
278+
Finally, Write 'Grounded answer:' followed by a response to the user's last input in high quality natural english. Use the symbols <co: doc> and </co: doc> to indicate when a fact comes from a document in the search result, e.g <co: 0>my fact</co: 0> for a fact from document 0.<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>"""
279+
280+
self.assertEqual(grounded_generation_prompt, expected_prompt)

0 commit comments

Comments
 (0)