Views
No views yet
router to the model name. E.g. if we set router-gpt-4o-mini as the model, it will use the gpt-4o-mini as the base model.ModernBERT-largeand better than the previous router model
that was based on bert-large-uncased.| Model | Score |
|---|---|
| router-gpt4o-mini with codelion/optillm-modernbert-large | 13.33 |
| router-gpt4o-mini with codelion/optillm-bert-uncased | 6.67 |
| gpt4o-mini | 3.33 |
OptILMClassifier class as we added additional layers to the base model. The additional
effort_encoder is used to take into account the number of tokens a given approach consumes. Also, note
the mapping of the returned index to the APPROACHES list as shown below.1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4from transformers import AutoModel, AutoTokenizer, AutoConfig
5from huggingface_hub import hf_hub_download
6from safetensors import safe_open
7from safetensors.torch import load_model
8from transformers import AutoTokenizer, AutoModel
9
10# Constants
11MAX_LENGTH = 1024
12APPROACHES = ["none", "mcts", "bon", "moa", "rto", "z3", "self_consistency", "pvg", "rstar", "cot_reflection", "plansearch", "leap", "re2"]
13BASE_MODEL = "answerdotai/ModernBERT-large"
14OPTILLM_MODEL_NAME = "codelion/optillm-modernbert-large"
15
16class OptILMClassifier(nn.Module):
17 def __init__(self, base_model, num_labels):
18 super().__init__()
19 self.base_model = base_model
20 self.effort_encoder = nn.Sequential(
21 nn.Linear(1, 64),
22 nn.ReLU(),
23 nn.Linear(64, 64),
24 nn.ReLU()
25 )
26 self.classifier = nn.Linear(base_model.config.hidden_size + 64, num_labels)
27
28 def forward(self, input_ids, attention_mask, effort):
29 outputs = self.base_model(input_ids=input_ids, attention_mask=attention_mask)
30 pooled_output = outputs.last_hidden_state[:, 0] # Shape: (batch_size, hidden_size)
31 effort_encoded = self.effort_encoder(effort.unsqueeze(1)) # Shape: (batch_size, 64)
32 combined_input = torch.cat((pooled_output, effort_encoded), dim=1)
33 logits = self.classifier(combined_input)
34 return logits
35
36def load_optillm_model():
37 device = torch.device("mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu")
38 # Load the base model
39 base_model = AutoModel.from_pretrained(BASE_MODEL)
40 # Create the OptILMClassifier
41 model = OptILMClassifier(base_model, num_labels=len(APPROACHES))
42 model.to(device)
43 # Download the safetensors file
44 safetensors_path = hf_hub_download(repo_id=OPTILLM_MODEL_NAME, filename="model.safetensors")
45 # Load the state dict from the safetensors file
46 load_model(model, safetensors_path)
47
48 tokenizer = AutoTokenizer.from_pretrained(OPTILLM_MODEL_NAME)
49 return model, tokenizer, device
50
51def preprocess_input(tokenizer, system_prompt, initial_query):
52 combined_input = f"{system_prompt}\n\nUser: {initial_query}"
53 encoding = tokenizer.encode_plus(
54 combined_input,
55 add_special_tokens=True,
56 max_length=MAX_LENGTH,
57 padding='max_length',
58 truncation=True,
59 return_attention_mask=True,
60 return_tensors='pt'
61 )
62 return encoding['input_ids'], encoding['attention_mask']
63
64def predict_approach(model, input_ids, attention_mask, device, effort=0.7):
65 model.eval()
66 with torch.no_grad():
67 input_ids = input_ids.to(device)
68 attention_mask = attention_mask.to(device)
69 effort_tensor = torch.tensor([effort], dtype=torch.float).to(device)
70
71 logits = model(input_ids, attention_mask=attention_mask, effort=effort_tensor)
72 probabilities = F.softmax(logits, dim=1)
73 predicted_approach_index = torch.argmax(probabilities, dim=1).item()
74 confidence = probabilities[0][predicted_approach_index].item()
75
76 return APPROACHES[predicted_approach_index], confidencepredict_approach method to get the predicted approach as follows:1# Load the trained model
2router_model, tokenizer, device = load_optillm_model()
3
4# Preprocess the input
5input_ids, attention_mask = preprocess_input(tokenizer, system_prompt, initial_query)
6
7# Predict the best approach
8predicted_approach, _ = predict_approach(router_model, input_ids, attention_mask, device)
9
10print(f"Router predicted approach: {predicted_approach}")1@software{optillm,
2 title = {Optillm: Optimizing inference proxy for LLMs},
3 author = {Asankhaya Sharma},
4 year = {2024},
5 publisher = {GitHub},
6 url = {https://github.com/codelion/optillm}
7}