File size: 10,753 Bytes
4c5e9dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"""
Helion-V1-Embeddings Training Script
Train a lightweight embedding model for semantic similarity and retrieval
"""

import json
import logging
from typing import List, Dict, Tuple
from pathlib import Path
from datetime import datetime

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class EmbeddingsTrainer:
    """Train embeddings model for Helion-V1-Embeddings."""
    
    def __init__(
        self,
        base_model: str = "sentence-transformers/all-MiniLM-L6-v2",
        output_path: str = "./helion-embeddings-output"
    ):
        self.base_model = base_model
        self.output_path = Path(output_path)
        self.output_path.mkdir(parents=True, exist_ok=True)
    
    def prepare_training_data(self) -> List[Dict]:
        """
        Prepare training data for embeddings.
        Format: sentence pairs with similarity scores.
        """
        training_examples = [
            # High similarity pairs
            {
                "sentence1": "How do I reset my password?",
                "sentence2": "What's the password reset process?",
                "score": 0.95
            },
            {
                "sentence1": "Machine learning training methods",
                "sentence2": "How to train ML models",
                "score": 0.90
            },
            {
                "sentence1": "Python programming tutorial",
                "sentence2": "Learn Python coding",
                "score": 0.88
            },
            
            # Medium similarity pairs
            {
                "sentence1": "Install Python on Windows",
                "sentence2": "Python setup guide",
                "score": 0.70
            },
            {
                "sentence1": "Best restaurants in Paris",
                "sentence2": "Where to eat in France",
                "score": 0.65
            },
            
            # Low similarity pairs
            {
                "sentence1": "How to bake cookies",
                "sentence2": "Machine learning algorithms",
                "score": 0.10
            },
            {
                "sentence1": "Weather forecast tomorrow",
                "sentence2": "Stock market analysis",
                "score": 0.05
            }
        ]
        
        logger.info(f"Prepared {len(training_examples)} training examples")
        return training_examples
    
    def create_contrastive_pairs(self) -> List[Tuple[str, str]]:
        """
        Create pairs for contrastive learning.
        Format: (anchor, positive) pairs.
        """
        pairs = [
            ("What is machine learning?", "Machine learning explained simply"),
            ("How to learn Python?", "Python learning resources"),
            ("Best coding practices", "Software development best practices"),
            ("Data science tutorial", "Learn data science basics"),
            ("Natural language processing", "NLP fundamentals guide"),
            ("Deep learning introduction", "Getting started with deep learning"),
            ("Web development guide", "How to build websites"),
            ("Database design principles", "SQL database design tutorial"),
            ("Cloud computing basics", "Introduction to cloud services"),
            ("API development guide", "How to create REST APIs"),
        ]
        
        logger.info(f"Created {len(pairs)} contrastive pairs")
        return pairs
    
    def train_model(
        self,
        train_examples: List[Dict] = None,
        epochs: int = 3,
        batch_size: int = 16,
        warmup_steps: int = 100
    ):
        """
        Train the embeddings model.
        
        Args:
            train_examples: Training data (if None, uses default)
            epochs: Number of training epochs
            batch_size: Batch size for training
            warmup_steps: Warmup steps for learning rate
        """
        try:
            from sentence_transformers import (
                SentenceTransformer,
                InputExample,
                losses,
                evaluation
            )
            from torch.utils.data import DataLoader
            
            logger.info("Loading base model...")
            model = SentenceTransformer(self.base_model)
            
            # Prepare data
            if train_examples is None:
                train_examples = self.prepare_training_data()
            
            # Convert to InputExample format
            train_data = []
            for example in train_examples:
                train_data.append(InputExample(
                    texts=[example["sentence1"], example["sentence2"]],
                    label=example["score"]
                ))
            
            # Create DataLoader
            train_dataloader = DataLoader(
                train_data,
                shuffle=True,
                batch_size=batch_size
            )
            
            # Define loss function
            train_loss = losses.CosineSimilarityLoss(model)
            
            # Training
            logger.info("Starting training...")
            model.fit(
                train_objectives=[(train_dataloader, train_loss)],
                epochs=epochs,
                warmup_steps=warmup_steps,
                output_path=str(self.output_path),
                show_progress_bar=True,
                save_best_model=True
            )
            
            logger.info(f"โœ… Training complete! Model saved to {self.output_path}")
            
            return model
            
        except ImportError:
            logger.error("sentence-transformers not installed. Install with: pip install sentence-transformers")
            return None
        except Exception as e:
            logger.error(f"Training failed: {e}")
            return None
    
    def evaluate_model(self, model, test_pairs: List[Tuple[str, str, float]] = None):
        """
        Evaluate the trained model.
        
        Args:
            model: Trained SentenceTransformer model
            test_pairs: List of (sentence1, sentence2, expected_similarity)
        """
        from sentence_transformers import util
        
        if test_pairs is None:
            # Default test pairs
            test_pairs = [
                ("How to code?", "Coding tutorial", 0.85),
                ("Weather today", "Stock prices", 0.1),
                ("Machine learning", "AI and ML", 0.95),
            ]
        
        logger.info("Evaluating model...")
        
        total_error = 0
        for sent1, sent2, expected in test_pairs:
            emb1 = model.encode(sent1)
            emb2 = model.encode(sent2)
            similarity = float(util.cos_sim(emb1, emb2)[0][0])
            error = abs(similarity - expected)
            total_error += error
            
            logger.info(f"'{sent1}' <-> '{sent2}'")
            logger.info(f"  Expected: {expected:.2f}, Got: {similarity:.2f}, Error: {error:.2f}")
        
        avg_error = total_error / len(test_pairs)
        logger.info(f"Average error: {avg_error:.3f}")
        
        return avg_error
    
    def create_config_files(self):
        """Create necessary configuration files."""
        
        # Sentence transformers config
        config = {
            "__version__": {
                "sentence_transformers": "2.2.2",
                "transformers": "4.36.0",
                "pytorch": "2.0.0"
            },
            "prompts": {},
            "default_prompt_name": None,
            "similarity_fn_name": "cosine",
            "max_seq_length": 256,
            "do_lower_case": False
        }
        
        with open(self.output_path / "config_sentence_transformers.json", 'w') as f:
            json.dump(config, f, indent=2)
        
        # Modules configuration
        modules = [
            {
                "idx": 0,
                "name": "0",
                "path": "",
                "type": "sentence_transformers.models.Transformer"
            },
            {
                "idx": 1,
                "name": "1",
                "path": "1_Pooling",
                "type": "sentence_transformers.models.Pooling"
            },
            {
                "idx": 2,
                "name": "2",
                "path": "2_Normalize",
                "type": "sentence_transformers.models.Normalize"
            }
        ]
        
        with open(self.output_path / "modules.json", 'w') as f:
            json.dump(modules, f, indent=2)
        
        logger.info("โœ… Configuration files created")


def main():
    """Main training function."""
    import argparse
    
    parser = argparse.ArgumentParser(
        description="Train Helion-V1-Embeddings model"
    )
    parser.add_argument(
        "--base-model",
        default="sentence-transformers/all-MiniLM-L6-v2",
        help="Base model to fine-tune"
    )
    parser.add_argument(
        "--output",
        default="./helion-embeddings-output",
        help="Output directory"
    )
    parser.add_argument(
        "--epochs",
        type=int,
        default=3,
        help="Number of training epochs"
    )
    parser.add_argument(
        "--batch-size",
        type=int,
        default=16,
        help="Batch size"
    )
    parser.add_argument(
        "--data-file",
        type=str,
        help="Path to training data JSON file"
    )
    
    args = parser.parse_args()
    
    # Create trainer
    trainer = EmbeddingsTrainer(
        base_model=args.base_model,
        output_path=args.output
    )
    
    # Load custom data if provided
    train_examples = None
    if args.data_file:
        with open(args.data_file, 'r') as f:
            train_examples = json.load(f)
        logger.info(f"Loaded {len(train_examples)} examples from {args.data_file}")
    
    # Train model
    model = trainer.train_model(
        train_examples=train_examples,
        epochs=args.epochs,
        batch_size=args.batch_size
    )
    
    if model:
        # Evaluate
        trainer.evaluate_model(model)
        
        # Create config files
        trainer.create_config_files()
        
        print("\n" + "="*60)
        print("โœ… Helion-V1-Embeddings Training Complete!")
        print("="*60)
        print(f"๐Ÿ“ Model saved to: {args.output}")
        print("\n๐Ÿ’ก Test your model:")
        print("```python")
        print("from sentence_transformers import SentenceTransformer")
        print(f"model = SentenceTransformer('{args.output}')")
        print("embeddings = model.encode(['Hello world'])")
        print("```")
        print("="*60)


if __name__ == "__main__":
    main()