Download training/distillation/models.py from SetMD/beastbullet-experts: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/SetMD/beastbullet-experts/resolve/main/training/distillation/models.py
- Command line
-
hf download hf://SetMD/beastbullet-experts/training/distillation/models.py
-
curl -L -o models.py https://huggingface.co/SetMD/beastbullet-experts/resolve/main/training/distillation/models.py
11.7 kB
| """ | |
| Student model architectures for micro-experts | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from typing import Tuple, Optional | |
| class MicroExpert(nn.Module): | |
| """ | |
| Tiny expert model: 256-dim embedding → task output | |
| Target size: 500KB - 2MB | |
| """ | |
| def __init__( | |
| self, | |
| input_dim: int = 256, | |
| hidden_dim: int = 256, | |
| output_dim: int = 256, | |
| num_layers: int = 3, | |
| dropout: float = 0.1, | |
| use_residual: bool = True, | |
| use_layer_norm: bool = True, | |
| ): | |
| super().__init__() | |
| self.input_dim = input_dim | |
| self.hidden_dim = hidden_dim | |
| self.output_dim = output_dim | |
| self.num_layers = num_layers | |
| self.use_residual = use_residual | |
| # Input projection | |
| self.input_proj = nn.Linear(input_dim, hidden_dim) | |
| # Hidden layers | |
| self.layers = nn.ModuleList() | |
| for _ in range(num_layers): | |
| layer = nn.ModuleDict({ | |
| 'linear': nn.Linear(hidden_dim, hidden_dim), | |
| 'norm': nn.LayerNorm(hidden_dim) if use_layer_norm else nn.Identity(), | |
| 'dropout': nn.Dropout(dropout), | |
| }) | |
| self.layers.append(layer) | |
| # Output heads | |
| self.output_head = nn.Linear(hidden_dim, output_dim) | |
| self.confidence_head = nn.Linear(hidden_dim, 1) | |
| def forward( | |
| self, | |
| embedding: torch.Tensor, | |
| return_hidden: bool = False | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """ | |
| Args: | |
| embedding: Input embedding (batch_size, input_dim) | |
| return_hidden: Whether to return hidden states | |
| Returns: | |
| output_embedding: Task-specific output (batch_size, output_dim) | |
| confidence: Confidence score (batch_size, 1) | |
| """ | |
| # Input projection | |
| x = self.input_proj(embedding) | |
| x = F.gelu(x) | |
| hidden_states = [] | |
| # Hidden layers with residual connections | |
| for layer in self.layers: | |
| residual = x | |
| x = layer['linear'](x) | |
| x = F.gelu(x) | |
| x = layer['norm'](x) | |
| x = layer['dropout'](x) | |
| if self.use_residual: | |
| x = x + residual | |
| if return_hidden: | |
| hidden_states.append(x) | |
| # Output heads | |
| output_embedding = self.output_head(x) | |
| confidence = torch.sigmoid(self.confidence_head(x)) | |
| if return_hidden: | |
| return output_embedding, confidence, hidden_states | |
| return output_embedding, confidence | |
| def get_num_parameters(self) -> int: | |
| """Get total number of parameters""" | |
| return sum(p.numel() for p in self.parameters()) | |
| def get_size_mb(self) -> float: | |
| """Get model size in MB""" | |
| param_size = sum(p.numel() * p.element_size() for p in self.parameters()) | |
| buffer_size = sum(b.numel() * b.element_size() for b in self.buffers()) | |
| return (param_size + buffer_size) / (1024 ** 2) | |
| class ClassificationExpert(MicroExpert): | |
| """Expert for classification tasks""" | |
| def __init__( | |
| self, | |
| input_dim: int = 256, | |
| hidden_dim: int = 256, | |
| num_classes: int = 2, | |
| num_layers: int = 3, | |
| dropout: float = 0.1, | |
| ): | |
| super().__init__( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| output_dim=hidden_dim, # Keep embedding output | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| ) | |
| # Classification head | |
| self.classifier = nn.Linear(hidden_dim, num_classes) | |
| def forward( | |
| self, | |
| embedding: torch.Tensor, | |
| return_logits: bool = True | |
| ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: | |
| """ | |
| Returns: | |
| output_embedding: Transformed embedding | |
| confidence: Confidence score | |
| logits: Classification logits (if return_logits=True) | |
| """ | |
| output_embedding, confidence = super().forward(embedding) | |
| if return_logits: | |
| logits = self.classifier(output_embedding) | |
| return output_embedding, confidence, logits | |
| return output_embedding, confidence, None | |
| class GenerationExpert(MicroExpert): | |
| """Expert for text generation tasks""" | |
| def __init__( | |
| self, | |
| input_dim: int = 256, | |
| hidden_dim: int = 256, | |
| vocab_size: int = 32000, | |
| num_layers: int = 3, | |
| dropout: float = 0.1, | |
| max_length: int = 128, | |
| ): | |
| super().__init__( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| output_dim=hidden_dim, | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| ) | |
| self.max_length = max_length | |
| # Generation head | |
| self.lm_head = nn.Linear(hidden_dim, vocab_size) | |
| def forward( | |
| self, | |
| embedding: torch.Tensor, | |
| return_logits: bool = True | |
| ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: | |
| """ | |
| Returns: | |
| output_embedding: Transformed embedding | |
| confidence: Confidence score | |
| logits: Next-token logits (if return_logits=True) | |
| """ | |
| output_embedding, confidence = super().forward(embedding) | |
| if return_logits: | |
| logits = self.lm_head(output_embedding) | |
| return output_embedding, confidence, logits | |
| return output_embedding, confidence, None | |
| class QAExpert(MicroExpert): | |
| """Expert for question answering tasks""" | |
| def __init__( | |
| self, | |
| input_dim: int = 256, | |
| hidden_dim: int = 256, | |
| num_layers: int = 3, | |
| dropout: float = 0.1, | |
| ): | |
| super().__init__( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| output_dim=hidden_dim, | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| ) | |
| # QA heads (start and end positions) | |
| self.qa_outputs = nn.Linear(hidden_dim, 2) | |
| def forward( | |
| self, | |
| embedding: torch.Tensor, | |
| return_positions: bool = True | |
| ) -> Tuple[torch.Tensor, torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]: | |
| """ | |
| Returns: | |
| output_embedding: Transformed embedding | |
| confidence: Confidence score | |
| positions: (start_logits, end_logits) if return_positions=True | |
| """ | |
| output_embedding, confidence = super().forward(embedding) | |
| if return_positions: | |
| logits = self.qa_outputs(output_embedding) | |
| start_logits, end_logits = logits.split(1, dim=-1) | |
| return output_embedding, confidence, (start_logits.squeeze(-1), end_logits.squeeze(-1)) | |
| return output_embedding, confidence, None | |
| class TokenClassificationExpert(MicroExpert): | |
| """Expert for token classification (NER, POS tagging)""" | |
| def __init__( | |
| self, | |
| input_dim: int = 256, | |
| hidden_dim: int = 256, | |
| num_labels: int = 9, # For NER: O, B-PER, I-PER, etc. | |
| num_layers: int = 3, | |
| dropout: float = 0.1, | |
| ): | |
| super().__init__( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| output_dim=hidden_dim, | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| ) | |
| # Token classification head | |
| self.classifier = nn.Linear(hidden_dim, num_labels) | |
| def forward( | |
| self, | |
| embedding: torch.Tensor, | |
| return_logits: bool = True | |
| ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: | |
| """ | |
| Returns: | |
| output_embedding: Transformed embedding | |
| confidence: Confidence score | |
| logits: Token classification logits (if return_logits=True) | |
| """ | |
| output_embedding, confidence = super().forward(embedding) | |
| if return_logits: | |
| logits = self.classifier(output_embedding) | |
| return output_embedding, confidence, logits | |
| return output_embedding, confidence, None | |
| def create_expert_model( | |
| task_type: str, | |
| input_dim: int = 256, | |
| hidden_dim: int = 256, | |
| num_layers: int = 3, | |
| dropout: float = 0.1, | |
| **task_specific_args | |
| ) -> nn.Module: | |
| """ | |
| Factory function to create appropriate expert model based on task type | |
| Args: | |
| task_type: Type of task (classification, generation, qa, token_classification) | |
| input_dim: Input embedding dimension | |
| hidden_dim: Hidden layer dimension | |
| num_layers: Number of hidden layers | |
| dropout: Dropout probability | |
| **task_specific_args: Task-specific arguments | |
| Returns: | |
| Expert model instance | |
| """ | |
| if task_type == "classification": | |
| return ClassificationExpert( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| num_classes=task_specific_args.get("num_classes", 2), | |
| ) | |
| elif task_type == "generation": | |
| return GenerationExpert( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| vocab_size=task_specific_args.get("vocab_size", 32000), | |
| max_length=task_specific_args.get("max_length", 128), | |
| ) | |
| elif task_type == "qa": | |
| return QAExpert( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| ) | |
| elif task_type == "token_classification": | |
| return TokenClassificationExpert( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| num_labels=task_specific_args.get("num_labels", 9), | |
| ) | |
| else: | |
| # Default to base MicroExpert | |
| return MicroExpert( | |
| input_dim=input_dim, | |
| hidden_dim=hidden_dim, | |
| output_dim=task_specific_args.get("output_dim", 256), | |
| num_layers=num_layers, | |
| dropout=dropout, | |
| ) | |
| if __name__ == "__main__": | |
| # Test model creation and size | |
| print("Testing MicroExpert models...\n") | |
| # Base expert | |
| model = MicroExpert(input_dim=256, hidden_dim=256, num_layers=3) | |
| print(f"Base MicroExpert:") | |
| print(f" Parameters: {model.get_num_parameters():,}") | |
| print(f" Size: {model.get_size_mb():.2f} MB") | |
| # Classification expert | |
| model = ClassificationExpert(num_classes=4) | |
| print(f"\nClassification Expert (4 classes):") | |
| print(f" Parameters: {model.get_num_parameters():,}") | |
| print(f" Size: {model.get_size_mb():.2f} MB") | |
| # Generation expert | |
| model = GenerationExpert(vocab_size=32000) | |
| print(f"\nGeneration Expert (vocab=32000):") | |
| print(f" Parameters: {model.get_num_parameters():,}") | |
| print(f" Size: {model.get_size_mb():.2f} MB") | |
| # Test forward pass | |
| batch_size = 4 | |
| embedding = torch.randn(batch_size, 256) | |
| model = ClassificationExpert(num_classes=2) | |
| output_emb, confidence, logits = model(embedding) | |
| print(f"\nForward pass test:") | |
| print(f" Input shape: {embedding.shape}") | |
| print(f" Output embedding shape: {output_emb.shape}") | |
| print(f" Confidence shape: {confidence.shape}") | |
| print(f" Logits shape: {logits.shape}") | |
| print("\n✓ All tests passed!") | |