File size: 6,548 Bytes
7a60a87 | 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | import os
import tempfile
import unittest
import torch
from transformers import AutoTokenizer
from datasets import Dataset
from specforge.data.preprocessing import build_eagle3_dataset
from specforge.utils import safe_conversations_generator
# ANSI color codes
RED = "\033[91m"
RESET = "\033[0m"
def print_with_loss_mask(tokenizer, input_ids, loss_mask, title=""):
"""Print text with loss_mask=1 (assistant) parts in RED."""
input_ids = input_ids.flatten()
loss_mask = loss_mask.flatten()
print(f"\n{'=' * 60}")
print(f"{title}")
print("=" * 60)
# Group consecutive tokens by loss_mask value
current_mask = loss_mask[0].item()
current_ids = [input_ids[0].item()]
for i in range(1, len(input_ids)):
if loss_mask[i].item() == current_mask:
current_ids.append(input_ids[i].item())
else:
# Decode and print current group
text = tokenizer.decode(current_ids, skip_special_tokens=False)
if current_mask == 1:
print(f"{RED}{text}{RESET}", end="")
else:
print(text, end="")
current_ids = [input_ids[i].item()]
current_mask = loss_mask[i].item()
# Print remaining tokens
if current_ids:
text = tokenizer.decode(current_ids, skip_special_tokens=False)
if current_mask == 1:
print(f"{RED}{text}{RESET}")
else:
print(text)
print("=" * 60)
# Tools definition from specforge/data/tools.py
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"description": "The unit of temperature",
"enum": ["celsius", "fahrenheit"],
},
},
"required": ["location"],
},
},
},
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web for information",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query",
},
"num_results": {
"type": "integer",
"description": "Number of results to return",
},
},
"required": ["query"],
},
},
},
]
# 1 sample from test_parsers.py: tool_use_messages
TOOL_USE_CONVERSATION = [
{"role": "user", "content": "我想知道今天北京和上海的天气怎么样?"},
{
"role": "assistant",
"content": "我来帮您查询北京和上海的天气情况。",
"tool_calls": [
{
"type": "function",
"function": {
"name": "get_weather",
"arguments": {"location": "北京", "date": "today"},
},
},
{
"type": "function",
"function": {
"name": "get_weather",
"arguments": {"location": "上海", "date": "today"},
},
},
],
},
{
"role": "tool",
"content": '{"location": "北京", "temperature": 25, "condition": "晴朗", "humidity": "45%"}',
},
{
"role": "tool",
"content": '{"location": "上海", "temperature": 28, "condition": "多云", "humidity": "65%"}',
},
{
"role": "assistant",
"content": "根据查询结果,北京今天晴朗,25°C;上海多云,28°C。两地都比较适合出行。",
},
]
class TestBuildEagle3Dataset(unittest.TestCase):
"""Test for build_eagle3_dataset with tools from specforge/data/tools.py."""
@classmethod
def setUpClass(cls):
cls.model_name = "Qwen/Qwen3.5-35B-A3B"
cls.template_key = "qwen3.5"
cls.tokenizer = AutoTokenizer.from_pretrained(
cls.model_name, trust_remote_code=True
)
cls.max_length = 65535
def test_build_eagle3_dataset_basic(self):
"""Test build_eagle3_dataset with 1 tool_use conversation sample."""
# Create a HF Dataset with 1 sample
data_file = os.path.join(
os.path.dirname(__file__), "data", "tool_use_conversation.jsonl"
)
with tempfile.TemporaryDirectory() as tmp_dir:
dataset = Dataset.from_generator(
generator=safe_conversations_generator,
gen_kwargs={"file_path": data_file},
cache_dir=tmp_dir,
keep_in_memory=True,
)
result_dataset = build_eagle3_dataset(
dataset=dataset,
tokenizer=self.tokenizer,
chat_template=self.template_key,
max_length=self.max_length,
shuffle_seed=42,
num_proc=1,
cache_dir=None,
cache_key=None,
)
# Verify the dataset has the expected columns
self.assertIn("input_ids", result_dataset.column_names)
self.assertIn("loss_mask", result_dataset.column_names)
self.assertIn("attention_mask", result_dataset.column_names)
self.assertEqual(len(result_dataset), 1)
# Decode input_ids to text
input_ids = result_dataset[0]["input_ids"].squeeze()
loss_mask = result_dataset[0]["loss_mask"].squeeze()
# Print full text with loss_mask=1 in RED
print_with_loss_mask(
self.tokenizer,
input_ids,
loss_mask,
title="[build_eagle3_dataset] Full text (RED = loss_mask=1):",
)
# Verify assistant tokens exist
assistant_indices = torch.where(loss_mask == 1)[0]
self.assertTrue(len(assistant_indices) > 0, "No assistant tokens found")
if __name__ == "__main__":
unittest.main(verbosity=2)
|