|
| 1 | +""" |
| 2 | +A module for spotting suspicious commands using the embeddings |
| 3 | +from our local LLM and a futher ANN categorisier. |
| 4 | +""" |
| 5 | + |
| 6 | +import os |
| 7 | + |
| 8 | +import torch |
| 9 | +from torch import nn |
| 10 | + |
| 11 | +from codegate.config import Config |
| 12 | +from codegate.inference.inference_engine import LlamaCppInferenceEngine |
| 13 | + |
| 14 | + |
| 15 | +class SimpleNN(nn.Module): |
| 16 | + """ |
| 17 | + A simple neural network with one hidden layer. |
| 18 | +
|
| 19 | + Attributes: |
| 20 | + network (nn.Sequential): The neural network layers. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, input_dim=1, hidden_dim=128, num_classes=2): |
| 24 | + """ |
| 25 | + Initialize the SimpleNN model. The default args should be ok, |
| 26 | + but the input_dim must match the incoming training data. |
| 27 | +
|
| 28 | + Args: |
| 29 | + input_dim (int): Dimension of the input features. |
| 30 | + hidden_dim (int): Dimension of the hidden layer. |
| 31 | + num_classes (int): Number of output classes. |
| 32 | + """ |
| 33 | + super(SimpleNN, self).__init__() |
| 34 | + self.network = nn.Sequential( |
| 35 | + nn.Linear(input_dim, hidden_dim), |
| 36 | + nn.ReLU(), |
| 37 | + nn.Dropout(0.2), |
| 38 | + nn.Linear(hidden_dim, hidden_dim // 2), |
| 39 | + nn.ReLU(), |
| 40 | + nn.Dropout(0.2), |
| 41 | + nn.Linear(hidden_dim // 2, num_classes), |
| 42 | + ) |
| 43 | + |
| 44 | + def forward(self, x): |
| 45 | + """ |
| 46 | + Forward pass through the network. |
| 47 | + """ |
| 48 | + return self.network(x) |
| 49 | + |
| 50 | + |
| 51 | +class SuspiciousCommands: |
| 52 | + """ |
| 53 | + Class to handle suspicious command detection using a neural network. |
| 54 | +
|
| 55 | + Attributes: |
| 56 | + model_path (str): Path to the model. |
| 57 | + inference_engine (LlamaCppInferenceEngine): Inference engine for embedding. |
| 58 | + simple_nn (SimpleNN): Neural network model. |
| 59 | + """ |
| 60 | + |
| 61 | + _instance = None |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def get_instance(model_file=None): |
| 65 | + """ |
| 66 | + Get the singleton instance of SuspiciousCommands. Initialize and load |
| 67 | + from file on the first call if it has not been done. |
| 68 | +
|
| 69 | + Args: |
| 70 | + model_file (str, optional): The file name to load the model from. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + SuspiciousCommands: The singleton instance. |
| 74 | + """ |
| 75 | + if SuspiciousCommands._instance is None: |
| 76 | + SuspiciousCommands._instance = SuspiciousCommands() |
| 77 | + if model_file is None: |
| 78 | + current_file_path = os.path.dirname(os.path.abspath(__file__)) |
| 79 | + model_file = os.path.join(current_file_path, "simple_nn_model.pt") |
| 80 | + SuspiciousCommands._instance.load_trained_model(model_file) |
| 81 | + return SuspiciousCommands._instance |
| 82 | + |
| 83 | + def __init__(self): |
| 84 | + """ |
| 85 | + Initialize the SuspiciousCommands class. |
| 86 | + """ |
| 87 | + conf = Config.get_config() |
| 88 | + if conf and conf.model_base_path and conf.embedding_model: |
| 89 | + self.model_path = f"{conf.model_base_path}/{conf.embedding_model}" |
| 90 | + else: |
| 91 | + self.model_path = "" |
| 92 | + self.inference_engine = LlamaCppInferenceEngine() |
| 93 | + self.simple_nn = SimpleNN() |
| 94 | + |
| 95 | + async def train(self, phrases, labels): |
| 96 | + """ |
| 97 | + Train the neural network with given phrases and labels. |
| 98 | +
|
| 99 | + Args: |
| 100 | + phrases (list of str): List of phrases to train on. |
| 101 | + labels (list of int): Corresponding labels for the phrases. |
| 102 | + """ |
| 103 | + embeds = await self.inference_engine.embed(self.model_path, phrases) |
| 104 | + if isinstance(embeds[0], list): |
| 105 | + embedding_dim = len(embeds[0]) |
| 106 | + else: |
| 107 | + raise ValueError("Embeddings should be a list of lists of floats") |
| 108 | + self.simple_nn = SimpleNN(input_dim=embedding_dim) |
| 109 | + criterion = nn.CrossEntropyLoss() |
| 110 | + optimizer = torch.optim.Adam(self.simple_nn.parameters(), lr=0.001) |
| 111 | + |
| 112 | + # Training loop |
| 113 | + for _ in range(100): |
| 114 | + for data, label in zip(torch.FloatTensor(embeds), torch.LongTensor(labels)): |
| 115 | + optimizer.zero_grad() |
| 116 | + outputs = self.simple_nn(data) |
| 117 | + loss = criterion(outputs, label) |
| 118 | + loss.backward() |
| 119 | + optimizer.step() |
| 120 | + |
| 121 | + def save_model(self, file_name): |
| 122 | + """ |
| 123 | + Save the trained model to a file. |
| 124 | +
|
| 125 | + Args: |
| 126 | + file_name (str): The file name to save the model. |
| 127 | + """ |
| 128 | + if self.simple_nn is not None: |
| 129 | + torch.save( # nosec |
| 130 | + { |
| 131 | + "model_state_dict": self.simple_nn.state_dict(), |
| 132 | + "input_dim": self.simple_nn.network[0].in_features, |
| 133 | + }, |
| 134 | + file_name, |
| 135 | + pickle_protocol=4, # Use a safer pickle protocol |
| 136 | + ) |
| 137 | + |
| 138 | + def load_trained_model(self, file_name, weights_only=True): |
| 139 | + """ |
| 140 | + Load a trained model from a file. |
| 141 | +
|
| 142 | + Args: |
| 143 | + file_name (str): The file name to load the model from. |
| 144 | + weights_only (bool): Whether to load only the weights. |
| 145 | + """ |
| 146 | + # Ensure the file being loaded is trusted |
| 147 | + if not os.path.exists(file_name): |
| 148 | + raise FileNotFoundError(f"Model file {file_name} does not exist.") |
| 149 | + |
| 150 | + checkpoint = torch.load( # nosec |
| 151 | + file_name, map_location=torch.device("cpu"), weights_only=weights_only |
| 152 | + ) |
| 153 | + input_dim = checkpoint["input_dim"] |
| 154 | + self.simple_nn = SimpleNN(input_dim=input_dim) |
| 155 | + self.simple_nn.load_state_dict(checkpoint["model_state_dict"]) |
| 156 | + |
| 157 | + async def compute_embeddings(self, phrases): |
| 158 | + """ |
| 159 | + Compute embeddings for a list of phrases. |
| 160 | +
|
| 161 | + Args: |
| 162 | + phrases (list of str): List of phrases to compute embeddings for. |
| 163 | +
|
| 164 | + Returns: |
| 165 | + torch.Tensor: Tensor of embeddings. |
| 166 | + """ |
| 167 | + embeddings = [] |
| 168 | + embeddings = await self.inference_engine.embed(self.model_path, phrases) |
| 169 | + return torch.tensor(embeddings) |
| 170 | + |
| 171 | + async def classify_phrase(self, phrase, embeddings=None): |
| 172 | + """ |
| 173 | + Classify a single phrase as suspicious or not. |
| 174 | +
|
| 175 | + Args: |
| 176 | + phrase (str): The phrase to classify. |
| 177 | + embeddings (torch.Tensor, optional): Precomputed embeddings for |
| 178 | + the phrase. |
| 179 | +
|
| 180 | + Returns: |
| 181 | + tuple: The predicted class (0 or 1) and its probability. |
| 182 | + """ |
| 183 | + if embeddings is None: |
| 184 | + embeddings = await self.compute_embeddings([phrase]) |
| 185 | + with torch.no_grad(): |
| 186 | + outputs = self.simple_nn(embeddings) |
| 187 | + probabilities = torch.nn.functional.softmax(outputs, dim=1) |
| 188 | + prob, predicted = torch.max(probabilities, 1) |
| 189 | + return predicted.item(), prob.item() |
0 commit comments