File size: 8,083 Bytes
6639f75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""
test_smollm3_robust.py - Test the robust SmolLM3-3B model

This script tests our newly trained model on various schemas to measure
the dramatic improvement in function calling capability.
"""

import torch
import json
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel

def load_trained_model():
    """Load the robust trained model."""
    print("πŸ”„ Loading robust SmolLM3-3B model...")
    
    base_model_name = "HuggingFaceTB/SmolLM3-3B"
    
    # Load tokenizer
    tokenizer = AutoTokenizer.from_pretrained(base_model_name)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    
    # Load base model
    base_model = AutoModelForCausalLM.from_pretrained(
        base_model_name,
        torch_dtype=torch.float32,
        trust_remote_code=True
    )
    
    # Load trained adapter
    model = PeftModel.from_pretrained(base_model, "./smollm3_robust")
    
    # Setup device
    if torch.backends.mps.is_available():
        model = model.to("mps")
        device = "mps"
    else:
        device = "cpu"
    
    print(f"βœ… Model loaded on {device}")
    return model, tokenizer, device

def test_function_call(model, tokenizer, device, schema, question):
    """Test the model on a specific schema and question."""
    
    prompt = f"""<|im_start|>system
You are a helpful assistant that calls functions by responding with valid JSON when given a schema. Always respond with JSON function calls only, never prose.<|im_end|>

<schema>
{json.dumps(schema, indent=2)}
</schema>

<|im_start|>user
{question}<|im_end|>
<|im_start|>assistant
"""
    
    # Tokenize
    inputs = tokenizer(prompt, return_tensors="pt")
    if device == "mps":
        inputs = {k: v.to(device) for k, v in inputs.items()}
    
    # Generate
    model.eval()
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=100,
            temperature=0.1,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id,
            eos_token_id=tokenizer.eos_token_id
        )
    
    # Decode response
    input_length = inputs["input_ids"].shape[1]
    response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
    
    # Clean up response (remove common trailing issues)
    response = response.strip()
    if response.endswith('}"}'):
        response = response[:-2]  # Remove extra "}
    if response.endswith('}}'):
        response = response[:-1]  # Remove extra }
    
    # Validate JSON
    try:
        json_response = json.loads(response)
        is_valid = True
        
        # Check if it has required structure
        has_name = "name" in json_response
        has_args = "arguments" in json_response
        correct_name = json_response.get("name") == schema["name"]
        
        score = sum([is_valid, has_name, has_args, correct_name])
        
    except json.JSONDecodeError as e:
        is_valid = False
        json_response = None
        score = 0
    
    return response, is_valid, json_response, score

def main():
    print("πŸ§ͺ Testing Robust SmolLM3-3B Function Calling")
    print("=" * 55)
    
    # Load model
    model, tokenizer, device = load_trained_model()
    
    # Comprehensive test cases
    test_cases = [
        {
            "name": "Stock Price (Training)",
            "schema": {
                "name": "get_stock_price",
                "description": "Get current stock price for a ticker",
                "parameters": {
                    "type": "object",
                    "properties": {"ticker": {"type": "string"}},
                    "required": ["ticker"]
                }
            },
            "question": "What's Apple stock trading at?"
        },
        {
            "name": "Weather (Seen Pattern)",
            "schema": {
                "name": "get_weather",
                "description": "Get weather for a location",
                "parameters": {
                    "type": "object",
                    "properties": {"location": {"type": "string"}},
                    "required": ["location"]
                }
            },
            "question": "How's the weather in Tokyo?"
        },
        {
            "name": "NEW: Database Query",
            "schema": {
                "name": "execute_sql",
                "description": "Execute SQL query on database",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {"type": "string"},
                        "database": {"type": "string"}
                    },
                    "required": ["query"]
                }
            },
            "question": "Find all users who registered this month"
        },
        {
            "name": "NEW: Complex Parameters",
            "schema": {
                "name": "book_flight",
                "description": "Book a flight ticket",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "from_city": {"type": "string"},
                        "to_city": {"type": "string"},
                        "departure_date": {"type": "string"},
                        "passengers": {"type": "integer"}
                    },
                    "required": ["from_city", "to_city", "departure_date"]
                }
            },
            "question": "Book a flight from New York to London for December 15th"
        },
        {
            "name": "NEW: Financial Transaction",
            "schema": {
                "name": "transfer_funds",
                "description": "Transfer money between accounts",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "amount": {"type": "number"},
                        "from_account": {"type": "string"},
                        "to_account": {"type": "string"},
                        "memo": {"type": "string"}
                    },
                    "required": ["amount", "from_account", "to_account"]
                }
            },
            "question": "Send $500 from checking to savings"
        }
    ]
    
    # Run tests
    total_score = 0
    max_score = len(test_cases) * 4  # 4 points per test
    valid_json_count = 0
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"\nπŸ“‹ Test {i}: {test_case['name']}")
        print(f"❓ Question: {test_case['question']}")
        
        response, is_valid, json_obj, score = test_function_call(
            model, tokenizer, device, test_case['schema'], test_case['question']
        )
        
        print(f"πŸ€– Raw response: {response}")
        
        if is_valid:
            print(f"βœ… Valid JSON: {json_obj}")
            valid_json_count += 1
        else:
            print(f"❌ Invalid JSON")
        
        print(f"πŸ“Š Score: {score}/4")
        total_score += score
        print("-" * 50)
    
    # Summary
    print(f"\nπŸ“Š FINAL RESULTS:")
    print(f"βœ… Valid JSON responses: {valid_json_count}/{len(test_cases)} ({valid_json_count/len(test_cases)*100:.1f}%)")
    print(f"πŸ“ˆ Overall score: {total_score}/{max_score} ({total_score/max_score*100:.1f}%)")
    print(f"🎯 Success criteria: β‰₯80% valid calls")
    
    if valid_json_count/len(test_cases) >= 0.8:
        print(f"πŸ† PASS - Excellent function calling capability!")
    elif valid_json_count/len(test_cases) >= 0.6:
        print(f"🟑 GOOD - Strong improvement, approaching target")
    else:
        print(f"πŸ”„ PROGRESS - Significant improvement from baseline")
    
    # Compare to previous
    print(f"\nπŸ“ˆ IMPROVEMENT COMPARISON:")
    print(f"Previous SmolLM2-1.7B result: 0/3 (0%)")
    print(f"Current SmolLM3-3B result: {valid_json_count}/{len(test_cases)} ({valid_json_count/len(test_cases)*100:.1f}%)")
    print(f"πŸš€ Training loss improvement: 2.38 β†’ 1.49 (37% better)")

if __name__ == "__main__":
    main()