import os import torch import pickle import numpy as np from models.model import TransformerModel from models.hyperparameter_config import Config from torch.quantization import quantize_dynamic class Inference: def __init__(self, weight_path: str='./models/saved_weights', device: str='cpu', quantized: bool=True): self.device = device self.config = Config self.quantized = quantized self.model = TransformerModel( input_dim=Config['input_dim'], seq_len=Config['seq_len'], hidden_dim=Config['hidden_dim'], num_layers=Config['num_layers'], num_heads=Config['num_heads'], dropout=Config['dropout'], num_classes=Config['num_classes'], pool_type=Config['pool_type'] ) best_weight = sorted([x for x in os.listdir(weight_path) if x.endswith('.pt')], reverse=True)[0] load_weight = torch.load(os.path.join(weight_path, best_weight), weights_only=True) self.model.load_state_dict(state_dict=load_weight) if self.quantized: self.model.eval() self.model = quantize_dynamic( self.model, {torch.nn.Linear}, dtype=torch.qint8 ) self.model.to(self.device) with open("./data/processed/class_dict.pkl", "rb") as f: self.encoder = pickle.load(f) def predict(self, input: torch.Tensor): if not isinstance(input, torch.Tensor): input = torch.from_numpy(input).float().to(self.device) else: input = input.to(self.device) if input.dim() < 3: input = input.unsqueeze(0) self.model.eval() with torch.inference_mode(): output = self.model(input) y_pred = torch.argmax(output, dim=1)[0].item() prediction = [k for k, v in self.encoder.items() if v == y_pred][0] prob = torch.softmax(output, dim=1) pred_prob = prob[0, y_pred].item() return prediction, np.round(pred_prob, 4)