Download training/datasets/generate_embeddings.py from SetMD/beastbullet-experts: direct link, hf CLI and curl.
- Browser
- Download file 8.03 kB
-
https://huggingface.co/SetMD/beastbullet-experts/resolve/main/training/datasets/generate_embeddings.py
- Command line
-
hf download hf://SetMD/beastbullet-experts/training/datasets/generate_embeddings.py
-
curl -L -o generate_embeddings.py https://huggingface.co/SetMD/beastbullet-experts/resolve/main/training/datasets/generate_embeddings.py
8.03 kB
| """ | |
| Generate Embeddings for Expert Datasets | |
| This script uses the trained shared encoder to generate embeddings | |
| for all filtered datasets. These embeddings will be used for expert training. | |
| Usage: | |
| python generate_embeddings.py --encoder_path ../../experts/encoder.onnx | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from typing import List, Dict | |
| import torch | |
| import numpy as np | |
| from tqdm import tqdm | |
| import onnxruntime as ort | |
| from transformers import AutoTokenizer | |
| import jsonlines | |
| class EmbeddingGenerator: | |
| """Generate embeddings using the trained encoder.""" | |
| def __init__(self, encoder_path: str, tokenizer_path: str, device: str = "cpu"): | |
| """ | |
| Initialize the embedding generator. | |
| Args: | |
| encoder_path: Path to ONNX encoder model | |
| tokenizer_path: Path to tokenizer directory | |
| device: Device to use (cpu or cuda) | |
| """ | |
| # Load ONNX model | |
| providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if device == "cuda" else ['CPUExecutionProvider'] | |
| self.session = ort.InferenceSession(encoder_path, providers=providers) | |
| # Load tokenizer | |
| self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) | |
| print(f"✓ Encoder loaded from {encoder_path}") | |
| print(f"✓ Tokenizer loaded from {tokenizer_path}") | |
| print(f"✓ Using device: {device}") | |
| def encode_batch(self, texts: List[str], max_length: int = 512) -> np.ndarray: | |
| """ | |
| Encode a batch of texts to embeddings. | |
| Args: | |
| texts: List of text strings | |
| max_length: Maximum sequence length | |
| Returns: | |
| Embeddings array of shape [batch_size, embed_dim] | |
| """ | |
| # Tokenize | |
| encodings = self.tokenizer( | |
| texts, | |
| max_length=max_length, | |
| padding="max_length", | |
| truncation=True, | |
| return_tensors="np" | |
| ) | |
| # Run inference | |
| outputs = self.session.run( | |
| None, | |
| { | |
| "input_ids": encodings["input_ids"].astype(np.int64), | |
| "attention_mask": encodings["attention_mask"].astype(np.int64) | |
| } | |
| ) | |
| return outputs[0] # [batch_size, embed_dim] | |
| def encode_dataset( | |
| self, | |
| samples: List[Dict], | |
| batch_size: int = 32, | |
| max_length: int = 512 | |
| ) -> np.ndarray: | |
| """ | |
| Encode an entire dataset. | |
| Args: | |
| samples: List of sample dictionaries with 'text' field | |
| batch_size: Batch size for encoding | |
| max_length: Maximum sequence length | |
| Returns: | |
| Embeddings array of shape [num_samples, embed_dim] | |
| """ | |
| all_embeddings = [] | |
| for i in tqdm(range(0, len(samples), batch_size), desc="Encoding"): | |
| batch = samples[i:i+batch_size] | |
| texts = [s["text"] for s in batch] | |
| embeddings = self.encode_batch(texts, max_length) | |
| all_embeddings.append(embeddings) | |
| return np.vstack(all_embeddings) | |
| def generate_expert_embeddings( | |
| expert_dir: Path, | |
| generator: EmbeddingGenerator, | |
| output_dir: Path, | |
| batch_size: int = 32 | |
| ) -> Dict: | |
| """Generate embeddings for an expert's dataset.""" | |
| # Load metadata | |
| metadata_path = expert_dir / "metadata.json" | |
| with open(metadata_path) as f: | |
| metadata = json.load(f) | |
| expert_id = metadata["expert_id"] | |
| print(f"\nGenerating embeddings for {expert_id}...") | |
| # Skip synthetic datasets | |
| if metadata.get("synthetic", False): | |
| print(f" Skipping synthetic dataset") | |
| return metadata | |
| # Load filtered samples | |
| samples_path = expert_dir / "filtered_samples.jsonl" | |
| if not samples_path.exists(): | |
| print(f" Warning: No filtered samples found") | |
| return metadata | |
| samples = [] | |
| with jsonlines.open(samples_path) as reader: | |
| for obj in reader: | |
| samples.append(obj) | |
| print(f" Loaded {len(samples)} samples") | |
| # Generate embeddings | |
| embeddings = generator.encode_dataset(samples, batch_size=batch_size) | |
| print(f" Generated embeddings: {embeddings.shape}") | |
| # Save embeddings | |
| expert_output_dir = output_dir / expert_id | |
| expert_output_dir.mkdir(parents=True, exist_ok=True) | |
| embeddings_path = expert_output_dir / "embeddings.npy" | |
| np.save(embeddings_path, embeddings) | |
| # Save sample texts for reference | |
| texts_path = expert_output_dir / "texts.jsonl" | |
| with jsonlines.open(texts_path, mode='w') as writer: | |
| for sample in samples: | |
| writer.write({"text": sample["text"]}) | |
| # Update metadata | |
| metadata["embeddings_shape"] = embeddings.shape | |
| metadata["embeddings_path"] = str(embeddings_path) | |
| metadata["status"] = "embeddings_generated" | |
| with open(expert_output_dir / "metadata.json", "w") as f: | |
| json.dump(metadata, f, indent=2) | |
| print(f" ✓ Saved to {embeddings_path}") | |
| return metadata | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Generate embeddings for expert datasets") | |
| parser.add_argument("--encoder_path", type=str, required=True, help="Path to ONNX encoder") | |
| parser.add_argument("--tokenizer_path", type=str, required=True, help="Path to tokenizer") | |
| parser.add_argument("--data_dir", type=str, default="../../data_filtered", help="Filtered data directory") | |
| parser.add_argument("--output_dir", type=str, default="../../data_embeddings", help="Output directory") | |
| parser.add_argument("--batch_size", type=int, default=32, help="Batch size") | |
| parser.add_argument("--device", type=str, default="cpu", help="Device (cpu or cuda)") | |
| args = parser.parse_args() | |
| data_dir = Path(args.data_dir) | |
| output_dir = Path(args.output_dir) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| print(f"🧠 Embedding Generation") | |
| print(f"Encoder: {args.encoder_path}") | |
| print(f"Tokenizer: {args.tokenizer_path}") | |
| print(f"Data directory: {data_dir}") | |
| print(f"Output directory: {output_dir}") | |
| print(f"Device: {args.device}") | |
| # Create embedding generator | |
| generator = EmbeddingGenerator( | |
| args.encoder_path, | |
| args.tokenizer_path, | |
| device=args.device | |
| ) | |
| # Process each expert | |
| expert_dirs = sorted([d for d in data_dir.iterdir() if d.is_dir()]) | |
| all_metadata = [] | |
| for expert_dir in expert_dirs: | |
| try: | |
| metadata = generate_expert_embeddings( | |
| expert_dir, | |
| generator, | |
| output_dir, | |
| batch_size=args.batch_size | |
| ) | |
| all_metadata.append(metadata) | |
| except Exception as e: | |
| print(f" ❌ Error: {e}") | |
| continue | |
| # Generate summary | |
| print(f"\n{'='*60}") | |
| print("📊 Embedding Generation Summary") | |
| print(f"{'='*60}") | |
| total_samples = 0 | |
| total_size_mb = 0 | |
| for metadata in all_metadata: | |
| expert_id = metadata["expert_id"] | |
| if "embeddings_shape" in metadata: | |
| shape = metadata["embeddings_shape"] | |
| num_samples = shape[0] | |
| embed_dim = shape[1] | |
| size_mb = (num_samples * embed_dim * 4) / (1024 ** 2) # float32 | |
| total_samples += num_samples | |
| total_size_mb += size_mb | |
| print(f"{expert_id}: {num_samples:,} samples × {embed_dim}d = {size_mb:.1f} MB") | |
| print(f"\nTotal:") | |
| print(f" Samples: {total_samples:,}") | |
| print(f" Storage: {total_size_mb:.1f} MB") | |
| print(f"\n✅ Embedding generation complete!") | |
| print(f"\nNext steps:") | |
| print(f" 1. Train experts: python ../distillation/train_expert.py") | |
| print(f" 2. Validate embeddings: python validate_embeddings.py") | |
| if __name__ == "__main__": | |
| main() | |