File size: 8,419 Bytes
c91ee90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""
Test script to verify Phi-3 model can be loaded and used
Run this before deploying to ensure everything works
"""

import sys
import time

def test_imports():
    """Test that all required packages can be imported"""
    print("=" * 60)
    print("πŸ” Testing imports...")
    print("=" * 60)
    
    try:
        import torch
        print(f"βœ… PyTorch: {torch.__version__}")
    except ImportError as e:
        print(f"❌ PyTorch import failed: {e}")
        return False
    
    try:
        import transformers
        print(f"βœ… Transformers: {transformers.__version__}")
    except ImportError as e:
        print(f"❌ Transformers import failed: {e}")
        return False
    
    try:
        import gradio
        print(f"βœ… Gradio: {gradio.__version__}")
    except ImportError as e:
        print(f"❌ Gradio import failed: {e}")
        return False
    
    try:
        from transformers import AutoModelForCausalLM, AutoTokenizer
        print("βœ… AutoModelForCausalLM and AutoTokenizer imported")
    except ImportError as e:
        print(f"❌ Failed to import model classes: {e}")
        return False
    
    print("\nβœ… All imports successful!\n")
    return True


def test_model_loading():
    """Test loading the Phi-3 model (this will download ~7GB on first run)"""
    print("=" * 60)
    print("πŸ” Testing Phi-3 model loading...")
    print("=" * 60)
    print("⚠️  Note: First run will download ~7GB model files")
    print("    This may take several minutes depending on internet speed\n")
    
    try:
        import torch
        from transformers import AutoModelForCausalLM, AutoTokenizer
        
        model_name = "microsoft/Phi-3-mini-4k-instruct"
        
        print(f"πŸ“₯ Loading tokenizer from {model_name}...")
        start_time = time.time()
        tokenizer = AutoTokenizer.from_pretrained(
            model_name,
            trust_remote_code=True
        )
        tokenizer_time = time.time() - start_time
        print(f"βœ… Tokenizer loaded in {tokenizer_time:.2f}s")
        
        print(f"\nπŸ“₯ Loading model from {model_name}...")
        print("   Using CPU (for testing)...")
        start_time = time.time()
        model = AutoModelForCausalLM.from_pretrained(
            model_name,
            device_map="cpu",
            torch_dtype=torch.float32,
            trust_remote_code=True,
            low_cpu_mem_usage=True
        )
        model_time = time.time() - start_time
        print(f"βœ… Model loaded in {model_time:.2f}s")
        
        # Get model info
        param_count = sum(p.numel() for p in model.parameters())
        print(f"\nπŸ“Š Model Information:")
        print(f"   Parameters: {param_count:,}")
        print(f"   Size: ~{param_count * 4 / 1024 / 1024 / 1024:.2f}GB (FP32)")
        
        return True, model, tokenizer
        
    except Exception as e:
        print(f"\n❌ Model loading failed: {e}")
        import traceback
        traceback.print_exc()
        return False, None, None


def test_inference(model, tokenizer):
    """Test model inference with a simple example"""
    print("\n" + "=" * 60)
    print("πŸ” Testing model inference...")
    print("=" * 60)
    
    try:
        import torch
        
        # Test prompt
        test_prompt = "What is artificial intelligence?"
        print(f"\nπŸ“ Test prompt: '{test_prompt}'")
        
        # Format prompt
        messages = [{"role": "user", "content": test_prompt}]
        formatted_prompt = tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True
        )
        
        # Tokenize
        inputs = tokenizer(formatted_prompt, return_tensors="pt")
        
        # Generate
        print("\n⏳ Generating response (this may take 10-30 seconds on CPU)...")
        start_time = time.time()
        
        with torch.no_grad():
            outputs = model.generate(
                **inputs,
                max_new_tokens=50,
                temperature=0.7,
                do_sample=True,
                top_p=0.9,
                pad_token_id=tokenizer.eos_token_id
            )
        
        inference_time = time.time() - start_time
        
        # Decode
        full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
        
        # Extract response
        if "<|assistant|>" in full_response:
            response = full_response.split("<|assistant|>")[-1].strip()
        else:
            response = full_response[len(formatted_prompt):].strip()
        
        print(f"βœ… Response generated in {inference_time:.2f}s")
        print(f"\nπŸ€– Model response:\n{response}\n")
        
        return True
        
    except Exception as e:
        print(f"\n❌ Inference failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_all_tasks(model, tokenizer):
    """Test all three tasks: chat, summarization, sentiment"""
    print("\n" + "=" * 60)
    print("πŸ” Testing all Vish AI tasks...")
    print("=" * 60)
    
    import torch
    
    tasks = [
        {
            "name": "Chat",
            "prompt": "Hello! How can you help me?",
            "max_tokens": 50
        },
        {
            "name": "Summarization",
            "prompt": "Summarize the following text concisely: Artificial Intelligence is transforming industries by automating tasks and improving decision-making. Machine learning enables computers to learn from data without explicit programming. This technology is used in healthcare, finance, and transportation.",
            "max_tokens": 60
        },
        {
            "name": "Sentiment",
            "prompt": "Analyze the sentiment of this text. Respond with POSITIVE, NEGATIVE, or NEUTRAL: I love this product! It's amazing!",
            "max_tokens": 5
        }
    ]
    
    all_passed = True
    
    for task in tasks:
        print(f"\nπŸ“ Testing {task['name']}...")
        print(f"   Prompt: {task['prompt'][:60]}...")
        
        try:
            messages = [{"role": "user", "content": task['prompt']}]
            formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
            inputs = tokenizer(formatted, return_tensors="pt")
            
            with torch.no_grad():
                outputs = model.generate(
                    **inputs,
                    max_new_tokens=task['max_tokens'],
                    temperature=0.7,
                    do_sample=True,
                    pad_token_id=tokenizer.eos_token_id
                )
            
            response = tokenizer.decode(outputs[0], skip_special_tokens=True)
            if "<|assistant|>" in response:
                response = response.split("<|assistant|>")[-1].strip()
            
            print(f"   βœ… {task['name']}: Success")
            print(f"   Response: {response[:100]}...")
            
        except Exception as e:
            print(f"   ❌ {task['name']}: Failed - {e}")
            all_passed = False
    
    return all_passed


def main():
    print("\n" + "=" * 60)
    print("πŸ§ͺ Vish AI - Phi-3 Model Test Suite")
    print("=" * 60)
    
    # Test 1: Imports
    if not test_imports():
        print("\n❌ Import test failed. Please install required packages:")
        print("   pip install -r requirements.txt")
        sys.exit(1)
    
    # Test 2: Model loading
    success, model, tokenizer = test_model_loading()
    if not success:
        print("\n❌ Model loading failed. Check error messages above.")
        sys.exit(1)
    
    # Test 3: Basic inference
    if not test_inference(model, tokenizer):
        print("\n❌ Inference test failed.")
        sys.exit(1)
    
    # Test 4: All tasks
    if not test_all_tasks(model, tokenizer):
        print("\n⚠️  Some task tests failed, but model is functional.")
    
    # Final summary
    print("\n" + "=" * 60)
    print("βœ… All tests passed!")
    print("=" * 60)
    print("\nπŸŽ‰ Your Vish AI setup is ready!")
    print("\nNext steps:")
    print("1. Run the main application: python app.py")
    print("2. Access at: http://localhost:7860")
    print("3. (Optional) Fine-tune the model: python fine_tune_phi3.py")
    print("4. Deploy to Hugging Face Spaces for production")
    print("\n" + "=" * 60)


if __name__ == "__main__":
    main()