| """Base model wrapper for Hugging Face and Mock models.""" | |
| from __future__ import annotations | |
| import os | |
| from abc import ABC | |
| from typing import Any, Dict, List, Optional, Tuple, Union | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from aegis.configs.dataclasses import ModelConfig | |
| from aegis.utils.device import get_device, get_torch_dtype | |
| from aegis.utils.logging import get_logger | |
| logger = get_logger("BaseModel") | |
| class DummyMockCausalLM(nn.Module): | |
| """A lightweight mock model that provides trainable parameters and logits for testing/CPU.""" | |
| def __init__(self, vocab_size: int = 1000, hidden_dim: int = 64): | |
| super().__init__() | |
| self.vocab_size = vocab_size | |
| self.embedding = nn.Embedding(vocab_size, hidden_dim) | |
| self.linear = nn.Linear(hidden_dim, vocab_size) | |
| def forward(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs) -> Any: | |
| h = self.embedding(input_ids % self.vocab_size) | |
| logits = self.linear(h) | |
| # Mock HuggingFace CausalLMOutput | |
| class MockOutput: | |
| def __init__(self, logits): | |
| self.logits = logits | |
| return MockOutput(logits) | |
| class DummyMockTokenizer: | |
| """A simple whitespace-based mock tokenizer.""" | |
| def __init__(self, vocab_size: int = 1000): | |
| self.vocab_size = vocab_size | |
| self.pad_token_id = 0 | |
| self.eos_token_id = 1 | |
| self.bos_token_id = 2 | |
| def __call__( | |
| self, | |
| text: Union[str, List[str]], | |
| return_tensors: Optional[str] = "pt", | |
| padding: bool = True, | |
| truncation: bool = True, | |
| max_length: Optional[int] = None, | |
| ) -> Dict[str, torch.Tensor]: | |
| if isinstance(text, str): | |
| text = [text] | |
| all_ids = [] | |
| for t in text: | |
| words = t.split() | |
| ids = [abs(hash(w)) % (self.vocab_size - 3) + 3 for w in words] | |
| if max_length and len(ids) > max_length: | |
| ids = ids[:max_length] | |
| if not ids: | |
| ids = [self.bos_token_id] | |
| all_ids.append(ids) | |
| max_len = max(len(ids) for ids in all_ids) | |
| padded_ids = [] | |
| attn_masks = [] | |
| for ids in all_ids: | |
| pad_count = max_len - len(ids) | |
| padded_ids.append(ids + [self.pad_token_id] * pad_count) | |
| attn_masks.append([1] * len(ids) + [0] * pad_count) | |
| if return_tensors == "pt": | |
| return { | |
| "input_ids": torch.tensor(padded_ids, dtype=torch.long), | |
| "attention_mask": torch.tensor(attn_masks, dtype=torch.long), | |
| } | |
| return {"input_ids": padded_ids, "attention_mask": attn_masks} | |
| def decode(self, token_ids: Union[List[int], torch.Tensor], skip_special_tokens: bool = True) -> str: | |
| if isinstance(token_ids, torch.Tensor): | |
| token_ids = token_ids.tolist() | |
| return " ".join(f"tok_{tid}" for tid in token_ids if tid > 2) | |
| class BaseModel(ABC): | |
| """Abstract base model wrapper supporting both HuggingFace and Mock architectures.""" | |
| def __init__(self, config: ModelConfig): | |
| self.config = config | |
| self.device = get_device(config.device) | |
| self.torch_dtype = get_torch_dtype(config.dtype) | |
| self.is_mock = config.is_mock or config.model_name in ["mock", "dummy", "test"] | |
| self.tokenizer: Any = None | |
| self.model: Any = None | |
| if self.is_mock: | |
| self._init_mock() | |
| else: | |
| self._init_hf() | |
| def _init_mock(self) -> None: | |
| """Initializes a lightweight dummy model for CPU/testing.""" | |
| self.tokenizer = DummyMockTokenizer() | |
| self.model = DummyMockCausalLM().to(self.device) | |
| self.is_mock = True | |
| def _init_hf(self) -> None: | |
| """Initializes a HuggingFace CausalLM model with optional LoRA/PEFT.""" | |
| try: | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| self.tokenizer = AutoTokenizer.from_pretrained( | |
| self.config.model_name, | |
| trust_remote_code=True, | |
| ) | |
| if self.tokenizer.pad_token is None: | |
| self.tokenizer.pad_token = self.tokenizer.eos_token | |
| self.model = AutoModelForCausalLM.from_pretrained( | |
| self.config.model_name, | |
| torch_dtype=self.torch_dtype, | |
| device_map="auto" if self.config.device == "auto" else None, | |
| trust_remote_code=True, | |
| ) | |
| if self.config.device != "auto": | |
| self.model = self.model.to(self.device) | |
| if self.config.lora: | |
| try: | |
| from peft import LoraConfig, get_peft_model, TaskType | |
| peft_config = LoraConfig( | |
| task_type=TaskType.CAUSAL_LM, | |
| r=self.config.lora_r, | |
| lora_alpha=self.config.lora_alpha, | |
| lora_dropout=self.config.lora_dropout, | |
| bias="none", | |
| ) | |
| self.model = get_peft_model(self.model, peft_config) | |
| logger.info(f"Loaded PEFT LoRA for {self.config.model_name}") | |
| except ImportError: | |
| logger.warning("PEFT not installed. Continuing with standard model.") | |
| except Exception as e: | |
| logger.warning( | |
| f"Could not load Hugging Face model '{self.config.model_name}' ({e}). Falling back to Mock model." | |
| ) | |
| self._init_mock() | |
| def generate(self, prompts: Union[str, List[str]], **kwargs) -> List[str]: | |
| """Generates text completions for a batch of prompts.""" | |
| if isinstance(prompts, str): | |
| prompts = [prompts] | |
| if self.is_mock: | |
| # Deterministic mock responses for testing | |
| return [self._mock_generate(p, **kwargs) for p in prompts] | |
| inputs = self.tokenizer( | |
| prompts, | |
| return_tensors="pt", | |
| padding=True, | |
| truncation=True, | |
| max_length=self.config.max_length, | |
| ).to(self.model.device if hasattr(self.model, "device") else self.device) | |
| gen_kwargs = { | |
| "max_new_tokens": kwargs.get("max_new_tokens", 256), | |
| "temperature": kwargs.get("temperature", self.config.temperature), | |
| "top_p": kwargs.get("top_p", self.config.top_p), | |
| "do_sample": kwargs.get("do_sample", True), | |
| "pad_token_id": self.tokenizer.pad_token_id, | |
| } | |
| with torch.no_grad(): | |
| output_ids = self.model.generate(**inputs, **gen_kwargs) | |
| input_len = inputs["input_ids"].shape[1] | |
| completions = [] | |
| for i, out in enumerate(output_ids): | |
| gen_ids = out[input_len:] | |
| text = self.tokenizer.decode(gen_ids, skip_special_tokens=True).strip() | |
| completions.append(text) | |
| return completions | |
| def _mock_generate(self, prompt: str, **kwargs) -> str: | |
| """Fallback mock text generator for unit tests and dummy runs.""" | |
| return '```json\n{"reasoning": "Mock evaluation reasoning.", "verdict": "mock_verdict"}\n```' | |
| def compute_log_probs( | |
| self, | |
| prompts: List[str], | |
| responses: List[str], | |
| ) -> Tuple[torch.Tensor, torch.Tensor]: | |
| """Computes token log probabilities and sequence log probabilities for (prompt, response) pairs. | |
| Returns: | |
| token_log_probs: Tensor of shape (batch_size, response_seq_len) | |
| seq_log_probs: Tensor of shape (batch_size,) | |
| """ | |
| full_texts = [p + " " + r for p, r in zip(prompts, responses)] | |
| target_device = self.device if not hasattr(self.model, "device") else self.model.device | |
| encoded_full = self.tokenizer( | |
| full_texts, | |
| return_tensors="pt", | |
| padding=True, | |
| truncation=True, | |
| max_length=self.config.max_length, | |
| ) | |
| encoded_prompt = self.tokenizer( | |
| prompts, | |
| return_tensors="pt", | |
| padding=True, | |
| truncation=True, | |
| max_length=self.config.max_length, | |
| ) | |
| input_ids = encoded_full["input_ids"].to(target_device) | |
| attention_mask = encoded_full["attention_mask"].to(target_device) | |
| outputs = self.model(input_ids=input_ids, attention_mask=attention_mask) | |
| logits = outputs.logits # (B, L, V) | |
| # Shift logits and labels for autoregressive log probs | |
| shift_logits = logits[:, :-1, :] | |
| shift_labels = input_ids[:, 1:] | |
| shift_mask = attention_mask[:, 1:] | |
| log_probs = F.log_softmax(shift_logits, dim=-1) | |
| token_log_probs = torch.gather(log_probs, 2, shift_labels.unsqueeze(2)).squeeze(2) | |
| # Mask out prompt tokens so we only score the response tokens | |
| response_mask = torch.zeros_like(token_log_probs) | |
| for i in range(len(prompts)): | |
| p_ids = encoded_prompt["input_ids"][i] | |
| p_len = len(p_ids) if isinstance(p_ids, list) else p_ids.shape[0] | |
| start_idx = max(0, p_len - 1) | |
| response_mask[i, start_idx:] = shift_mask[i, start_idx:] | |
| masked_token_log_probs = token_log_probs * response_mask | |
| seq_log_probs = masked_token_log_probs.sum(dim=-1) | |
| return masked_token_log_probs, seq_log_probs | |
| def parameters(self): | |
| return self.model.parameters() | |
| def train(self, mode: bool = True): | |
| self.model.train(mode) | |
| return self | |
| def eval(self): | |
| self.model.eval() | |
| return self | |
| def save_pretrained(self, save_directory: str) -> None: | |
| os.makedirs(save_directory, exist_ok=True) | |
| if hasattr(self.model, "save_pretrained"): | |
| self.model.save_pretrained(save_directory) | |
| if self.tokenizer and hasattr(self.tokenizer, "save_pretrained"): | |
| self.tokenizer.save_pretrained(save_directory) | |
Xet Storage Details
- Size:
- 9.97 kB
- Xet hash:
- c71dae0bf4d0d311e5271609000d16ea266bc59c1ad797d6abfe68f6a242237c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.