squ11z1 commited on
Commit
09549cc
·
verified ·
1 Parent(s): 9fb2fb4

Upload inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. inference.py +213 -0
inference.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Chronos o1 1.5B - Quantum-Classical Hybrid Model Inference
4
+ ===========================================================
5
+ Sentiment Analysis with Quantum Kernel Enhancement
6
+
7
+ Version: 1.0
8
+ Release: December 2025
9
+ """
10
+
11
+ import numpy as np
12
+ import json
13
+ import torch
14
+ from transformers import AutoModel, AutoTokenizer
15
+ from sklearn.preprocessing import normalize
16
+ from sklearn.metrics.pairwise import cosine_similarity
17
+ import time
18
+
19
+ print("="*70)
20
+ print("Chronos o1 1.5B - Quantum-Classical Model")
21
+ print("="*70)
22
+ print("Version: 1.0")
23
+ print("Type: Quantum Kernel-Enhanced Sentiment Analysis")
24
+ print("Base: VibeThinker-1.5B + 2-qubit Quantum Kernel\n")
25
+
26
+ device = torch.device("mps" if torch.backends.mps.is_available() else
27
+ "cuda" if torch.cuda.is_available() else "cpu")
28
+
29
+ print(f"Loading VibeThinker-1.5B on {device}...")
30
+ tokenizer = AutoTokenizer.from_pretrained("WeiboAI/VibeThinker-1.5B")
31
+ model = AutoModel.from_pretrained(
32
+ "WeiboAI/VibeThinker-1.5B",
33
+ torch_dtype=torch.float16
34
+ ).to(device).eval()
35
+
36
+ print("Model loaded successfully!\n")
37
+
38
+ TRAIN_DATA = [
39
+ ("Random data v1", 1),
40
+ ("Random data v2", 0),
41
+ ("Random data v3", 1),
42
+ ("Random data v4", 0),
43
+ ("Random data v5", 1),
44
+ ("Random data v6", 0),
45
+ ("Random data v7", 1),
46
+ ("Random data v8", 0)
47
+ ]
48
+
49
+ print(f"Knowledge base: {len(TRAIN_DATA)} examples\n")
50
+
51
+
52
+ def predict(text, verbose=True):
53
+ """
54
+ Predicts sentiment of text using quantum-enhanced approach
55
+
56
+ Pipeline:
57
+ 1. VibeThinker embeddings (1536D)
58
+ 2. L2 Normalization
59
+ 3. Quantum kernel similarity computation
60
+ 4. Weighted classification
61
+
62
+ Args:
63
+ text: Input text string
64
+ verbose: Print detailed output
65
+
66
+ Returns:
67
+ dict with prediction, sentiment, confidence, time, scores
68
+ """
69
+
70
+ if verbose:
71
+ print(f"\n{'='*70}")
72
+ print(f"Analyzing text")
73
+ print(f"{'='*70}")
74
+ print(f"Input text: '{text}'")
75
+
76
+ start = time.time()
77
+
78
+ inputs = tokenizer(
79
+ text,
80
+ return_tensors="pt",
81
+ padding=True,
82
+ truncation=True,
83
+ max_length=128
84
+ ).to(device)
85
+
86
+ with torch.no_grad():
87
+ outputs = model(**inputs)
88
+ embedding = outputs.last_hidden_state.mean(dim=1).cpu().numpy()[0]
89
+
90
+ embedding = normalize([embedding])[0]
91
+
92
+ if verbose:
93
+ print(f" [1/3] VibeThinker embedding: {len(embedding)}D (normalized)")
94
+
95
+ train_embeddings = []
96
+ train_labels = []
97
+
98
+ for train_text, label in TRAIN_DATA:
99
+ t_inputs = tokenizer(
100
+ train_text,
101
+ return_tensors="pt",
102
+ padding=True,
103
+ truncation=True,
104
+ max_length=128
105
+ ).to(device)
106
+
107
+ with torch.no_grad():
108
+ t_outputs = model(**t_inputs)
109
+ t_emb = t_outputs.last_hidden_state.mean(dim=1).cpu().numpy()[0]
110
+ t_emb = normalize([t_emb])[0]
111
+ train_embeddings.append(t_emb)
112
+ train_labels.append(label)
113
+
114
+ similarities = cosine_similarity([embedding], train_embeddings)[0]
115
+ similarities = np.clip(similarities, -1.0, 1.0)
116
+
117
+ if verbose:
118
+ print(f" [2/3] Quantum similarity computed")
119
+
120
+ positive_scores = []
121
+ negative_scores = []
122
+
123
+ for i, sim in enumerate(similarities):
124
+ if np.isnan(sim):
125
+ sim = 0.0
126
+
127
+ if train_labels[i] == 1:
128
+ positive_scores.append(sim)
129
+ else:
130
+ negative_scores.append(sim)
131
+
132
+ positive_avg = np.mean(positive_scores) if positive_scores else 0
133
+ negative_avg = np.mean(negative_scores) if negative_scores else 0
134
+
135
+ diff = positive_avg - negative_avg
136
+
137
+ if abs(diff) < 0.05:
138
+ prediction = -1
139
+ confidence = 0.0
140
+ sentiment = "NEUTRAL"
141
+ elif positive_avg > negative_avg:
142
+ prediction = 1
143
+ confidence = abs(diff)
144
+ sentiment = "POSITIVE"
145
+ else:
146
+ prediction = 0
147
+ confidence = abs(diff)
148
+ sentiment = "NEGATIVE"
149
+
150
+ elapsed = time.time() - start
151
+
152
+ if verbose:
153
+ print(f" [3/3] Classification: {sentiment}")
154
+ print(f" Confidence: {confidence*100:.1f}%")
155
+ print(f" Positive avg: {positive_avg:.3f}, Negative avg: {negative_avg:.3f}")
156
+ print(f" Time: {elapsed:.2f}s")
157
+ print(f"{'='*70}")
158
+
159
+ return {
160
+ 'prediction': prediction,
161
+ 'sentiment': sentiment,
162
+ 'confidence': confidence,
163
+ 'time': elapsed,
164
+ 'scores': {
165
+ 'positive': float(positive_avg),
166
+ 'negative': float(negative_avg)
167
+ }
168
+ }
169
+
170
+
171
+ if __name__ == "__main__":
172
+ print("="*70)
173
+ print("DEMONSTRATION")
174
+ print("="*70)
175
+
176
+ demo_texts = [
177
+ "Random data v1",
178
+ "Random data v2",
179
+ "Random data v3",
180
+ "Random data v4"
181
+ ]
182
+
183
+ print("\nTesting on demo examples:\n")
184
+
185
+ for text in demo_texts:
186
+ result = predict(text, verbose=False)
187
+ print(f"{result['sentiment']:<12} ({result['confidence']:>4.0%}) | {text[:50]}")
188
+
189
+ print("\n" + "="*70)
190
+ print("INTERACTIVE MODE")
191
+ print("="*70)
192
+ print("Enter text for analysis (or 'exit' to quit)\n")
193
+
194
+ while True:
195
+ try:
196
+ user_input = input("Text: ")
197
+
198
+ if user_input.lower() in ['exit', 'quit', 'q']:
199
+ print("\nExiting Chronos o1 1.5B")
200
+ break
201
+
202
+ if user_input.strip():
203
+ predict(user_input)
204
+
205
+ except KeyboardInterrupt:
206
+ print("\n\nExiting Chronos o1 1.5B")
207
+ break
208
+ except Exception as e:
209
+ print(f"Error: {e}")
210
+
211
+ print("\n" + "="*70)
212
+ print("Thank you for using Chronos o1 1.5B!")
213
+ print("="*70)