Views
No views yet
1# Import necessary libraries
2import torch
3import torch.nn as nn
4from transformers import T5Tokenizer, T5ForConditionalGeneration
5
6# Set device
7device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
9# Define the model class (same structure as used during training)
10class CustomT5Model(nn.Module):
11 def __init__(self):
12 super(CustomT5Model, self).__init__()
13 self.t5 = T5ForConditionalGeneration.from_pretrained("t5-large")
14 self.classifier = nn.Linear(1024, 4) # 4 classes for AG News
15
16 def forward(self, input_ids, attention_mask=None):
17 encoder_outputs = self.t5.encoder(
18 input_ids=input_ids,
19 attention_mask=attention_mask,
20 return_dict=True
21 )
22 hidden_states = encoder_outputs.last_hidden_state # (batch_size, seq_len, hidden_dim)
23 logits = self.classifier(hidden_states[:, 0, :]) # Use [CLS] token representation
24 return logits
25
26# Initialize the model
27model = CustomT5Model().to(device)
28
29# Load the saved model weights from Hugging Face
30model_path = "https://huggingface.co/Vijayendra/T5-large-docClassification/resolve/main/best_model.pth"
31model.load_state_dict(torch.hub.load_state_dict_from_url(model_path, map_location=device))
32model.eval()
33
34# Load the tokenizer
35tokenizer = T5Tokenizer.from_pretrained("t5-large")
36
37# Inference function
38def infer(model, tokenizer, text):
39 model.eval()
40 with torch.no_grad():
41 # Preprocess the input text
42 inputs = tokenizer(
43 [f"classify: {text}"],
44 max_length=99,
45 truncation=True,
46 padding="max_length",
47 return_tensors="pt"
48 )
49 input_ids = inputs["input_ids"].to(device)
50 attention_mask = inputs["attention_mask"].to(device)
51
52 # Get model predictions
53 logits = model(input_ids=input_ids, attention_mask=attention_mask)
54 preds = torch.argmax(logits, dim=-1)
55
56 # Map class index to label
57 label_map = {0: "World", 1: "Sports", 2: "Business", 3: "Sci/Tech"}
58 return label_map[preds.item()]
59
60# Example usage
61text = "NASA announces new mission to study asteroids"
62result = infer(model, tokenizer, text)
63print(f"Predicted category: {result}")